1、python贪吃蛇游戏实训报告_Python写的贪吃蛇游戏例from Tkinter import*import tkMessageBox,sysfrom random import randintclass Grid(object):def _init_(self,master=None,window_width=800,window_height=600,grid_width=50,offset=10):self.height=window_heightself.width=window_widthself.grid_width=grid_widthself.offset=offsetse
2、lf.grid_x=self.width/self.grid_widthself.grid_y=self.height/self.grid_widthself.bg=#EBEBEBself.canvas=Canvas(master,width=self.width+2*self.offset,height=self.height+2*self.offset,bg=self.bg)self.canvas.pack()self.grid_list()def draw(self,pos,color,):x=pos0*self.grid_width+self.offsety=pos1*self.gri
3、d_width+self.offsetself.canvas.create_rectangle(x,y,x+self.grid_width,y+self.grid_width,fill=color,outline=self.bg)def grid_list(self):grid_list=for y in range(0,self.grid_y):for x in range(0,self.grid_x):grid_list.append(x,y)self.grid_list=grid_listclass Food(object):def _init_(self,Grid):self.grid
4、=Gridself.color=#23D978self.set_pos()def set_pos(self):x=randint(0,self.grid.grid_x-1)y=randint(0,self.grid.grid_y-1)self.pos=(x,y)def display(self):self.grid.draw(self.pos,self.color)class Snake(object):def _init_(self,Grid):self.grid=Gridself.body=(10,6),(10,7),(10,8)self.direction=Upself.status=r
5、un,stopself.speed=300self.color=#5FA8D9self.food=Food(self.grid)self.display_food()self.gameover=Falseself.score=0def available_grid(self):return i for i in self.grid.grid_list if i not in self.body2:def change_direction(self,direction):self.direction=directiondef display(self):for(x,y)in self.body:
6、self.grid.draw(x,y),self.color)def display_food(self):while(self.food.pos in self.body):self.food.set_pos()self.food.display()def move(self):head=self.body0if self.direction=Up:new=(head0,head1-1)elif self.direction=Down:new=(head0,head1+1)elif self.direction=Left:new=(head0-1,head1)else:new=(head0+
7、1,head1)if not self.food.pos=head:pop=self.body.pop()self.grid.draw(pop,self.grid.bg)else:self.display_food()self.score+=1self.body.insert(0,new)if not new in self.available_grid():self.status.reverse()self.gameover=Trueelse:self.grid.draw(new,color=self.color)class SnakeGame(Frame):def _init_(self,
8、master=None,*args,*kwargs):Frame._init_(self,master)self.master=masterself.grid=Grid(master=master,*args,*kwargs)self.snake=Snake(self.grid)self.bind_all(,self.key_release)self.snake.display()def run(self):if not self.snake.status0=stop:self.snake.move()if self.snake.gameover=True:message=tkMessageB
9、ox.showinfo(Game Over,your score:%d%self.snake.score)if message=ok:sys.exit()self.after(self.snake.speed,self.run)def key_release(self,event):key=event.keysymkey_dict=Up:Down,Down:Up,Left:Right,Right:Leftif key_dict.has_key(key)and not key=key_dictself.snake.direction:self.snake.change_direction(key)self.snake.move()elif key=p:self.snake.status.reverse()if _name_=_main_:root=Tk()snakegame=SnakeGame(root)snakegame.run()snakegame.mainloop()本条技术章来源于互联,如果意侵犯您的权益请点击此处反馈版权投诉本系统来源:php中