您好,欢迎访问三七文档
#五子棋#!/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()
本文标题:Python五子棋
链接地址:https://www.777doc.com/doc-4958757 .html