没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
试读
3页
我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中。 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到最初体型 4.变色食物:吃了会根据食物颜色改变蛇的颜色 #coding=UTF-8 from Tkinter import * from random import randint import tkMessageBox class Grid(object): def __init__(self, master=None,height=16, width=24, offset=10, gri
资源推荐
资源详情
资源评论
使用使用Python写一个贪吃蛇游戏实例代码写一个贪吃蛇游戏实例代码
我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中。
特殊食物特殊食物:
1.绿色:普通,吃了增加体型
2.红色:吃了减少体型
3.金色:吃了回到最初体型
4.变色食物:吃了会根据食物颜色改变蛇的颜色
#coding=UTF-8
from Tkinter import *
from random import randint
import tkMessageBox
class Grid(object):
def __init__(self, master=None,height=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(self,new):
self.body.insert(0, new)
self.grid.draw(new, self.color)
for i in range(0,3):
pop = self.body.pop()
self.grid.draw(pop, self.grid.bg)
资源评论
weixin_38735790
- 粉丝: 4
- 资源: 899
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功