一,首先我们可以使用Python的tkinter函数库来生成一个窗口

代码如下:

import tkinter as tk //导入tkinter函数库win = tk.Tk() //创建一个窗口win.title("Python Snake") //设置窗口的标题win.mainloop() //保留窗口

代码运行效果如下:

我们可以看到怎样一个窗口,但目前的效果还是远远不够的,所以,我们还需要对这个窗口进行一个优化。

二:基本参数设置

贪吃蛇的蛇身和墙都用方格来表示,所以先设置一下方格的边长,还有窗体的高度和宽度。这里的30是像素。

side = 30 //正方形边长height = 20*side //20个正方形的边长width = 20*side //20个正方形的边长

但是此时运行显然是显示不出来的,因为还没有设置进去。

这里可以用geometry函数来设置。

s = str(width) + "x" + str(height)win.geometry(s)

怎样一个窗口就设置好了

三:贪吃蛇的初始化

定义初始化函数:

def init():

首先,新建一个画布工具。面积和窗口一样.,然后放置在指定地方,所有格子贴在一起不好看,设个间距,然后填充

def init():canvas = tk.Canvas(win,height=height,width=width) //新建画布工具canvas.pack() //放置在指定地方margin = 4 //间距for i in range(20):for j in range(20):canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill = "grey")

效果如下:

然后把墙设置出来,用黑色表示。

if(i == 0 or i == 19 or j == 0 or j == 19)://墙体显示 canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill = "black")

那么,接下来再放蛇进去。我这里把初始位置设为(6,6)

start_x = 6 //蛇的初始坐标Xstart_y = 6 //蛇的初始坐标Y

蛇最初占两个格子,向右移动,这里初始为绿色,这样明显一点。

if((i == start_x and j == start_y)or (i == start_x+1 and j == start_y)): //蛇的初始移动向右canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill = "green")

在函数外面定义一个空列表snake=[],然后在刚刚初始化蛇身的代码后面,把蛇身保存进列表。

snake.append([i,j])

四:随机生成cookie

定义一个生成cookie的函数:(这里我们就不讲述详细步骤了)

import random//生成cookiedef set_cookie():ci=random.randint(0,19) //随机生成cookie的横纵坐标cj=random.randint(0,19)//保证生成的cookie不在蛇身里while [ci,cj] in snake:ci=random.randint(1,18) //随机生成cookiecj=random.randint(1,18)return [ci,cj]ci,cj=set_cookie() //生成cookieif i == ci and j == cj: canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill = "red")

五:蛇的移动与转向

其实这里就是把列表里的蛇的坐标更新一下,然后在窗口里更新图像即可。(这里我们还是就不讲述详细步骤了)

def snake_move():move = [1,0]del(snake[0])snake.append([snake[len(snake)-1][0]+move[0],snake[len(snake)-1][1]+move[1]])def update():win.update()canvas.create_rectangle(snake[0][0]*side,snake[0][1]*side,(snake[0][0]+1)*side-margin,(snake[0][1]+1)*side-margin,fill="grey")snake_move()canvas.create_rectangle((snake[len(snake)-1][0])*side,(snake[len(snake)-1][1])*side,(snake[len(snake)-1][0]+1)*side-margin,(snake[len(snake)-1][1]+1)*side-margin,fill="yellow")win.after(500,update)def rotage(event):if move[1] and event.keysym=='Left':move[0]=-1move[1]=0elif move[1] and event.keysym=='Right':move[0]=1move[1]=0elif move[0] and event.keysym=='Up':move[0]=0move[1]=-1elifmove[0] and event.keysym=='Down':move[0]=0move[1]=1

别忘记在主函数里完成聚焦和绑定:

canvas.focus_set()canvas.bind("",rotage)canvas.bind("",rotage)canvas.bind("",rotage)canvas.bind("",rotage)

六:蛇吃cookie的相关操作

cookie=[]cookie.append([ci,cj])def check():if snake[len(snake)-1] == cookie[0]:return Truereturn Falsedef eat():cookie[0][0],cookie[0][1]=set_cookie()canvas.create_rectangle(cookie[0][0]*side,cookie[0][1]*side,(cookie[0][0]+1)*side-margin,(cookie[0][1]+1)*side-margin,fill="red")snake.insert(0,[snake[0][0]-move[0],snake[0][1]-move[1]])if snake[0][0]>=19 or snake[0][0]=19 or snake[0][1]<=0:canvas.create_rectangle(snake[0][0]*side,snake[0][1]*side,(snake[0][0]+1)*side-margin,(snake[0][1]+1)*side-margin,fill="black")if check():eat()

七:游戏的结束和计分功能

def check_lose():x=snake[len(snake)-1][0]y=snake[len(snake)-1][1]check=[]for i in range(len(snake)):check.append([snake[i][0],snake[i][1]])del(check[len(check)-1])if [x,y] in check:return Trueif x=19 or y=19:return Trueif check_lose():win.destroy()return import timetime.sleep(2000)

八:分数输出

score=[0]score[0]+=10t=[]t.append(time.time())from tkinter import messageboxresult="Your Score is "+str(score[0])+", time is "+str(int(t[1]-t[0]))+" second"messagebox.showinfo("Game Over!",result)

九,最后,我们来看看完整代码

import tkinter as tkfrom tkinter import messageboximport randomimport timeside=30#正方形边长height=20*side#20个正方形的边长width=20*side#20个正方形的边长margin=4#间距snake=[]#蛇身的坐标move=[1,0]#移动方向cookie=[]#cookiescore=[0]#得分t=[]#时间#窗口初始化def init():ci,cj=set_cookie()#生成cookiestart_x=6#蛇的初始坐标start_y=6cookie.append([ci,cj])#保存cookiefor i in range(20):for j in range(20):canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill="grey")if(i==0 or i==19 or j==0 or j==19):#墙体显示 canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill="black")if((i==start_x and j==start_y)or (i==start_x+1 and j==start_y)):#蛇的初始移动向右 canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill="yellow") snake.append([i,j])if i==ci and j==cj: canvas.create_rectangle(i*side,j*side,(i+1)*side-margin,(j+1)*side-margin,fill="blue")t.append(time.time())#初始时间update()#生成cookiedef set_cookie():ci=random.randint(1,18)#随机生成cookie的横纵坐标cj=random.randint(1,18)#保证生成的cookie不在蛇身里while [ci,cj] in snake:ci=random.randint(1,18)#随机生成cookiecj=random.randint(1,18)return [ci,cj]#蛇移动def snake_move():del(snake[0])snake.append([snake[len(snake)-1][0]+move[0],snake[len(snake)-1][1]+move[1]])#更新窗口def update():win.update()if check():eat()canvas.create_rectangle(snake[0][0]*side,snake[0][1]*side,(snake[0][0]+1)*side-margin,(snake[0][1]+1)*side-margin,fill="grey")snake_move()canvas.create_rectangle((snake[len(snake)-1][0])*side,(snake[len(snake)-1][1])*side,(snake[len(snake)-1][0]+1)*side-margin,(snake[len(snake)-1][1]+1)*side-margin,fill="yellow")if check_lose():t.append(time.time())result="Your Score is "+str(score[0])+", time is "+str(int(t[1]-t[0]))+" second"messagebox.showinfo("Game Over!",result)#弹窗显示分数和时间time.sleep(2000)win.destroy()return win.after(500,update)#蛇的转向def rotage(event):if move[1] and event.keysym=='Left':move[0]=-1move[1]=0elif move[1] and event.keysym=='Right':move[0]=1move[1]=0elif move[0] and event.keysym=='Up':move[0]=0move[1]=-1elifmove[0] and event.keysym=='Down':move[0]=0move[1]=1#检查是否吃到cookiedef check():if snake[len(snake)-1] == cookie[0]:return Truereturn False#蛇吃了cookie会发生什么def eat():score[0]+=10#得分加10分cookie[0][0],cookie[0][1]=set_cookie()canvas.create_rectangle(cookie[0][0]*side,cookie[0][1]*side,(cookie[0][0]+1)*side-margin,(cookie[0][1]+1)*side-margin,fill="blue")snake.insert(0,[snake[0][0]-move[0],snake[0][1]-move[1]])if snake[0][0]>=19 or snake[0][0]=19 or snake[0][1]<=0:canvas.create_rectangle(snake[0][0]*side,snake[0][1]*side,(snake[0][0]+1)*side-margin,(snake[0][1]+1)*side-margin,fill="black")#游戏结束def check_lose():#蛇头的坐标x=snake[len(snake)-1][0]y=snake[len(snake)-1][1]#蛇身check=[]for i in range(len(snake)):check.append([snake[i][0],snake[i][1]])del(check[len(check)-1])if [x,y] in check:return Trueif x=19 or y=19:return Truereturn False#主函数win=tk.Tk()#创建窗口win.title("AC Snake")#标题s=str(width)+"x"+str(height)win.geometry(s)canvas=tk.Canvas(win,height=height,width=width)#新建画布工具canvas.pack()#放置在指定地方canvas.focus_set()#聚焦canvas.bind("",rotage)canvas.bind("",rotage)canvas.bind("",rotage)canvas.bind("",rotage)init()win.mainloop()