python实现贪吃蛇.docx

上传人:牧羊曲112 文档编号:3164828 上传时间:2023-03-11 格式:DOCX 页数:3 大小:36.81KB
返回 下载 相关 举报
python实现贪吃蛇.docx_第1页
第1页 / 共3页
python实现贪吃蛇.docx_第2页
第2页 / 共3页
python实现贪吃蛇.docx_第3页
第3页 / 共3页
亲,该文档总共3页,全部预览完了,如果喜欢就下载吧!
资源描述

《python实现贪吃蛇.docx》由会员分享,可在线阅读,更多相关《python实现贪吃蛇.docx(3页珍藏版)》请在三一办公上搜索。

1、python实现贪吃蛇Python版贪吃蛇.py #!/usr/bin/python from Tkinter import * import random class snake(Frame): def _init_(self, master=None): Frame._init_(self, master) self.body = (0,0) self.bodyid = self.food = -1, -1 self.foodid = -1 self.gridcount = 10 self.size = 500 self.di = 3 self.speed = 500 self.top =

2、 self.winfo_toplevel self.top.resizable(False, False) self.grid self.canvas = Canvas(self) self.canvas.grid self.canvas.config(width=self.size, height=self.size,relief=RIDGE) self.drawgrid s = self.size/self.gridcount id = self.canvas.create_rectangle(self.body00*s,self.body01*s, (self.body00+1)*s,

3、(self.body01+1)*s, fill=yellow) self.bodyid.insert(0, id) self.bind_all(, self.keyrelease) self.drawfood self.after(self.speed, self.drawsnake) defdrawgrid(self): s = self.size/self.gridcount for i in range(0, self.gridcount+1): self.canvas.create_line(i*s, 0, i*s, self.size) self.canvas.create_line

4、(0, i*s, self.size, i*s) defdrawsnake(self): s = self.size/self.gridcount head = self.body0 new = head0, head1 if self.di = 1: new1 = (head1-1) % self.gridcount elifself.di = 2: new0 = (head0+1) % self.gridcount elifself.di = 3: new1 = (head1+1) % self.gridcount else: new0 = (head0-1) % self.gridcou

5、nt next = ( new0, new1 ) if next in self.body: exit elif next = (self.food0, self.food1): self.body.insert(0, next) self.bodyid.insert(0, self.foodid) self.drawfood else: tail = self.body.pop id = self.bodyid.pop self.canvas.move(id, (next0-tail0)*s, (next1-tail1)*s) self.body.insert(0, next) self.b

6、odyid.insert(0, id) self.after(self.speed, self.drawsnake) defdrawfood(self): s = self.size/self.gridcount x = random.randrange(0, self.gridcount) y = random.randrange(0, self.gridcount) while (x, y) in self.body: x = random.randrange(0, self.gridcount) y = random.randrange(0, self.gridcount) id = s

7、elf.canvas.create_rectangle(x*s,y*s, (x+1)*s, (y+1)*s, fill=yellow) self.food0 = x self.food1 = y self.foodid = id defkeyrelease(self, event): if event.keysym = Up and self.di != 3: self.di = 1 elifevent.keysym = Right and self.di !=4: self.di = 2 elifevent.keysym = Down and self.di != 1: self.di = 3 elifevent.keysym = Left and self.di != 2: self.di = 4 app = snake app.master.title(Greedy Snake) app.mainloop

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号