Python五子棋

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

#五子棋#!/usr/bin/pythonfromTkinterimport*importrandomclasssnake(Frame):def__init__(self,master=None):Frame.__init__(self,master)self.body=[(0,0)]self.bodyid=[]self.food=[-1,-1]self.foodid=-1self.gridcount=10self.size=500self.di=3self.speed=500self.top=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.gridcountid=self.canvas.create_rectangle(self.body[0][0]*s,self.body[0][1]*s,(self.body[0][0]+1)*s,(self.body[0][1]+1)*s,fill=yellow)self.bodyid.insert(0,id)self.bind_all(KeyRelease,self.keyrelease)self.drawfood()self.after(self.speed,self.drawsnake)defdrawgrid(self):s=self.size/self.gridcountforiinrange(0,self.gridcount+1):self.canvas.create_line(i*s,0,i*s,self.size)self.canvas.create_line(0,i*s,self.size,i*s)defdrawsnake(self):s=self.size/self.gridcounthead=self.body[0]new=[head[0],head[1]]ifself.di==1:new[1]=(head[1]-1)%self.gridcountelifself.di==2:new[0]=(head[0]+1)%self.gridcountelifself.di==3:new[1]=(head[1]+1)%self.gridcountelse:new[0]=(head[0]-1)%self.gridcountnext=(new[0],new[1])ifnextinself.body:exit()elifnext==(self.food[0],self.food[1]):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,(next[0]-tail[0])*s,(next[1]-tail[1])*s)self.body.insert(0,next)self.bodyid.insert(0,id)self.after(self.speed,self.drawsnake)defdrawfood(self):s=self.size/self.gridcountx=random.randrange(0,self.gridcount)y=random.randrange(0,self.gridcount)while(x,y)inself.body:x=random.randrange(0,self.gridcount)y=random.randrange(0,self.gridcount)id=self.canvas.create_rectangle(x*s,y*s,(x+1)*s,(y+1)*s,fill=yellow)self.food[0]=xself.food[1]=yself.foodid=iddefkeyrelease(self,event):ifevent.keysym==Upandself.di!=3:self.di=1elifevent.keysym==Rightandself.di!=4:self.di=2elifevent.keysym==Downandself.di!=1:self.di=3elifevent.keysym==Leftandself.di!=2:self.di=4app=snake()app.master.title(GreedySnake)app.mainloop()

1 / 2
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功