Python implementation of Snake game instance code

Source: Internet
Author: User
This article mainly introduces the use of Python to write a snake game instance code, very good, with reference value, need to refer to a friend

I added a score display in the program, three kinds of special food, the game logic of the snake is written into the Snakegame class, rather than in the snake class.

Special foods:

1. Green: normal, eat to increase body size

2. Red: Eat to reduce body size

3. Gold: Eat back to the original body

4. Changing food: Eating will change the color of the snake depending on the color of the food.


#coding =utf-8from Tkinter Import *from random import Randintimport tkmessageboxclass Grid (object): Def __init__ (self, MAS Ter=none,height=16, width=24, offset=10, grid_width=50, bg= "#808080"): self.height = height self.width = width se Lf.offset = Offset Self.grid_width = grid_width self.bg = BG Self.canvas = Canvas (Master, WIDTH=SELF.WIDTH*SELF.G Rid_width+2*self.offset, height=self.height*self.grid_width+ 2*self.offset, b g=self.bg) Self.canvas.pack (Side=right, fill=y) def draw (self, POS, color,): x = pos[0] * self.grid_width + SELF.O Ffset y = pos[1] * self.grid_width + self.offset #outline属性要与网格的背景色 (self.bg) is the same, otherwise it will be ugly self.canvas.create_rectangl E (x, y, x + self.grid_width, y + self.grid_width, Fill=color, outline=self.bg) class food (object): Def __init__ (self, grid    , color = "#23D978"): Self.grid = Grid Self.color = Color Self.set_pos () Self.type = 1 def set_pos (self): x = Randint (0, Self.grid. width-1) y = randint (0, self.grid.height-1) Self.pos = (x, y) def display (self): Self.grid.draw (Self.pos, S    Elf.color) class Snake (object): Def __init__ (self, grid, color = "#000000"): Self.grid = Grid Self.color = Color   Self.body = [(8, one), (8, 8)] self.direction = "Up" For I in Self.body:self.grid.draw (i, Self.color) #这个方法用于游戏重新开始时初始化贪吃蛇的位置 def initial (self): When not len (self.body) = = 0:pop = Self.body.pop () Self.grid. Draw (pop, self.grid.bg) self.body = [(8, one), (8, 8)] self.direction = "up" Self.color = "#000000" F  Or I in Self.body:self.grid.draw (i, Self.color) #蛇像一个指定点移动 def move (self, new): Self.body.insert (0, new) pop  = Self.body.pop () self.grid.draw (pop, self.grid.bg) self.grid.draw (new, Self.color) #蛇像一个指定点移动, and add length def add (self , new): Self.body.insert (0, new) Self.grid.draw (new, Self.color) #蛇吃到了特殊食物1, cut the length of its own def Cut_down (self,new): Sel   F.body.insert (0, new) Self.grid.draw (new, Self.color) for I in Range (0,3): pop = Self.body.pop () self.grid.draw (pop, self.grid.bg) #蛇吃到了特殊食物2, back to the original length def init (self, New): Self.body.insert (0, new) Self.grid.draw (new, Self.color) while Len (self . body) > 3:pop = Self.body.pop () self.grid.draw (pop, self.grid.bg) #蛇吃到了特殊食物3, changed its own color, pure fun def change (SE LF, new, color): Self.color = Color Self.body.insert (0, new) for item in Self.body:self.grid.draw (item, SEL    F.color) class Snakegame (Frame): Def __init__ (self, Master): frame.__init__ (self, master) Self.grid = Grid (Master)  Self.snake = Snake (self.grid) Self.food = food (self.grid) Self.gameover = False Self.score = 0 Self.status = [' Run ', ' stop '] self.speed = Self.grid.canvas.bind_all ("<KeyRelease>", Self.key_release) Self.display_ Food () #用于设置变色食物 self.color_c = ("#FFB6C1", "#6A5ACD", "#0000FF", "#F0FFF0", "#FFFFE0", "#F0F8FF", "#EE82EE", "#000000", " #5FA8D9 "," #32CD32 ") selF.I = 0 #界面左侧显示分数 self.m = stringvar () self.ft1 = (' Fixdsys ', ' max ', ' bold ') Self.m1 = Message (Master, Textvariab LE=SELF.M, aspect=5000, Font=self.ft1, bg= "#696969") Self.m1.pack (Side=left, fill=y) Self.m.set ("Score:" +str (Self.sc Ore)) #这个方法用于游戏重新开始时初始化游戏 def initial (self): Self.gameover = False self.score = 0 self.m.set ("Score:" +str (self). Score) self.snake.initial () #type1: normal food type2: reduced by 2 Type3: Lotto, back to the original state type4: Eat will change color def display_food (self): Self.food. color = "#23D978" Self.food.type = 1 if randint (0, +) = = 5:self.food.color = "#FFD700" Self.food.type =  3 while (Self.food.pos in self.snake.body): Self.food.set_pos () self.food.display () Elif randint (0, 4) = = 2:self.food.color = "#EE82EE" Self.food.type = 4 while (Self.food.pos in self.snake.body): Self . Food.set_pos () self.food.display () Elif len (self.snake.body) > Ten and Randint (0, +) = = 5:self.food.colo r = "#BC8F8F" self.Food.type = 2 while (Self.food.pos in self.snake.body): Self.food.set_pos () Self.food.display () Else: while (Self.food.pos-self.snake.body): Self.food.set_pos () Self.food.display () def key_release (self, Event): key = Event.keysym key_dict = {' Up ': ' Down ', ' Down ': ' Up ', ' left ': ' Right ', ' right ': ' Left '} #蛇不可以像自己的反方向 Go if Key_dict.has_key (key) and not key = = Key_dict[self.snake.direction]: self.snake.direction = key Self.mov      E () elif key = = ' P ': Self.status.reverse () def run: #首先判断游戏是否暂停 if not self.status[0] = = ' Stop ': #判断游戏是否结束 if Self.gameover = = True:message = Tkmessagebox.showinfo ("Game over", "Your score:%d"% Self.scor        e) If message = = ' OK ': self.initial () if Self.food.type = = 4:color = self.color_c[self.i]        SELF.I = (self.i+1)%10 self.food.color = Color Self.food.display () self.move (color) Else: Self.move () Self. After (Self.speed, Self.run) def move (self, color= "#EE82EE"): # Calculates the next moving point of the snake head = self.snake.body[0] If Self.sna Ke.direction = = ' up ': if HEAD[1]-1 < 0:new = (Head[0], +) Else:new = (Head[0], head[1]-1       ) elif self.snake.direction = = ' down ': New = (Head[0], (head[1] + 1)% of elif self.snake.direction = = ' Left ':  If head[0]-1 < 0:new = ((, head[1]) Else:new = (Head[0]-1, head[1]) else:new =     ((Head[0] + 1)%, head[1]) #撞到自己, set the end-of-game flag and wait for the next loop if new in Self.snake.body:self.gameover=true #吃到食物        elif new = self.food.pos:if Self.food.type = = 1:self.snake.add (new) elif Self.food.type = = 2: Self.snake.cut_down (new) elif Self.food.type = = 4:self.snake.change (new, color) Else:self.sna Ke.init (new) Self.display_food () Self.score = Self.score+1 Self.m.set ("Score:" + str (self.score)) #什么都没撞 Come on, move on Else:selF.snake.move (new) if __name__ = = ' __main__ ': root = Tk () Snakegame = Snakegame (root) snakegame.run () Snakegame.mainloop ()

summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.