资源简介
利用python编写了一个经典的贪吃蛇小游戏,运行python代码后可以实现可视化的方式玩贪吃蛇游戏,附有完整的代码以及代码注释。
代码片段和文件信息
#coding=UTF-8
from Tkinter import *
from random import randint
# import tkMessageBox
class Grid(object):
def __init__(self master=Noneheight=16 width=24 offset=10 grid_width=50 bg=“#808080“):
self.height = height
self.width = width
self.offset = offset
self.grid_width = grid_width
self.bg = bg
self.canvas = Canvas(master width=self.width*self.grid_width+2*self.offset height=self.height*self.grid_width+
2*self.offset bg=self.bg)
self.canvas.pack(side=RIGHT fill=Y)
def draw(self pos color ):
x = pos[0] * self.grid_width + self.offset
y = pos[1] * self.grid_width + self.offset
#outline属性要与网格的背景色(self.bg)相同,要不然会很丑
self.canvas.create_rectangle(x y x + self.grid_width y + self.grid_width fill=color outline=self.bg)
class Food(object):
def __init__(self grid color = “#23D978“):
self.grid = grid
self.color = color
self.set_pos()
self.type = 1
def set_pos(self):
x = randint(0 self.grid.width - 1)
y = randint(0 self.grid.height - 1)
self.pos = (x y)
def display(self):
self.grid.draw(self.pos self.color)
class Snake(object):
def __init__(self grid color = “#000000“):
self.grid = grid
self.color = color
self.body = [(8 11) (8 12) (8 13)]
self.direction = “Up“
for i in self.body:
self.grid.draw(i self.color)
#这个方法用于游戏重新开始时初始化贪吃蛇的位置
def initial(self):
while not len(self.body) == 0:
pop = self.body.pop()
self.grid.draw(pop self.grid.bg)
self.body = [(8 11) (8 12) (8 13)]
self.direction = “Up“
self.color = “#000000“
for i in self.body:
self.grid.draw(i self.color)
#蛇像一个指定点移动
def move(self new):
self.body.insert(0 new)
pop = self.body.pop()
self.grid.draw(pop self.grid.bg)
self.grid.draw(new self.color)
#蛇像一个指定点移动,并增加长度
def add(self new):
self.body.insert(0 new)
self.grid.draw(new self.color)
#蛇吃到了特殊食物1,剪短自身的长度
def cut_down(selfnew):
self.body.insert(0 new)
self.grid.draw(new self.color)
for i in range(03):
pop = self.body.pop()
self.grid.draw(pop self.grid.bg)
#蛇吃到了特殊食物2,回到最初长度
def init(self new):
self.body.insert(0 new)
self.grid.draw(new self.color)
while len(self.body) > 3:
pop = self.body.pop()
self.grid.draw(pop self.grid.bg)
#蛇吃到了特殊食物3,改变了自身的颜色纯属好玩
def change(self new color):
self.color = color
self.body.insert(0 new)
for item in self.body:
self.grid.draw(item self.color)
class S
相关资源
- 二级考试python试题12套(包括选择题和
- pywin32_python3.6_64位
- python+ selenium教程
- PycURL(Windows7/Win32)Python2.7安装包 P
- 英文原版-Scientific Computing with Python
- 7.图像风格迁移 基于深度学习 pyt
- 基于Python的学生管理系统
- A Byte of Python(简明Python教程)(第
- Python实例174946
- Python 人脸识别
- Python 人事管理系统
- 基于python-flask的个人博客系统
- 计算机视觉应用开发流程
- python 调用sftp断点续传文件
- python socket游戏
- 基于Python爬虫爬取天气预报信息
- python函数编程和讲解
- Python开发的个人博客
- 基于python的三层神经网络模型搭建
- python实现自动操作windows应用
- python人脸识别(opencv)
- python 绘图(方形、线条、圆形)
- python疫情卡UN管控
- python 连连看小游戏源码
- 基于PyQt5的视频播放器设计
- 一个简单的python爬虫
- csv文件行列转换python实现代码
- Python操作Mysql教程手册
- Python Machine Learning Case Studies
- python获取硬件信息
评论
共有 条评论