python实现贪吃蛇

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

# encoding:utf-8

importtkMessageBox

fromTkinter import Tk, Canvas, Frame

from random import randint

import sys

class Grid:

def __init__(self, master = None, window_width = 500, window_height = 500, grid_width = 25):

self.width = grid_width

self.bg = 7

self.start = 2 # 50 / 25

self.end = 18 # 450 / 25

self.color = ['yellow', 'red', 'pink', 'black', 'orange', 'green', 'purple', 'cyan']

self.canvas = Canvas(master, width = window_width, height = window_height, bg = self.color[self.bg])

self.draw_wall()

self.canvas.pack()

defdraw_rect(self, x, y, clr):

self.canvas.create_rectangle(x, y, x + self.width, y + self.width, fill = self.color[clr], outline = self.color[self.bg])

defdraw_wall(self):

w = self.width

s = self.start * w

e = self.end * w

fori in range(s, e, w):

self.canvas.create_rectangle(i, s, i + w, s + w, fill = 'green', outline = self.color[self.bg])

self.canvas.create_rectangle(i, e - w, i + w, e, fill = 'green', outline = self.color[self.bg])

self.canvas.create_rectangle(s, i, s + w, i + w, fill = 'green', outline = self.color[self.bg])

self.canvas.create_rectangle(e - w, i, e, i + w, fill = 'green', outline = self.color[self.bg])

classsnakenode:

def __init__(self, clr, x, y):

self.clr = clr

self.x = x

self.y = y

class Food:

def __init__(self, Grid):

self.grid = Grid

self.set_food()

defset_food(self):

min = self.grid.start + 1

max = self.grid.end - 2

self.x = randint(min, max) * 25

self.y = randint(min, max) * 25

self.clr = randint(0, len(self.grid.color) - 2)

def display(self):

self.grid.draw_rect(self.x, self.y, self.clr)

class snake:

def __init__(self, Grid):

self.grid = Grid

self.init_snake()

self.direction = 'Up'

self.dir_x = [0, 0, -1, 1]

self.dir_y = [-1, 1, 0, 0]

self.dir = {'Up':0, 'Down':1, 'Left':2, 'Right':3}

self.pause = 1

self.dead = 0

self.food = Food(self.grid)

self.display_food()

definit_snake(self):

s1 = snakenode(0, 100, 300)

s2 = snakenode(1, 100, 325)

s3 = snakenode(2, 100, 350)

self.body = [s1, s2, s3]

defdisplay_snake(self):

for node in self.body:

self.grid.draw_rect(node.x, node.y, node.clr)

defdisplay_food(self):

for node in self.body:

ifnode.x == self.food.x and node.y == self.food.y:

self.food.set_food()

else:

break

self.food.display()

def move(self):

index = self.dir[self.direction]

m = self.dir_x[index] * self.grid.width + self.body[0].x

n = self.dir_y[index] * self.grid.width + self.body[0].y

if m == self.food.x and n == self.food.y: # 吃到食物sn = snakenode(self.food.clr, m, n)

self.body.insert(0, sn)

self.display_food()

return

s = (m / self.grid.width)

t = (n / self.grid.width)

b1 = s == self.grid.start or s == self.grid.end - 1

b2 = t == self.grid.start or t == self.grid.end - 1

if b1 or b2: # 撞到墙

self.dead = 1

相关文档
最新文档