Use Python to write a snake

Source: Internet
Author: User

Reference Code http://blog.csdn.net/leepwang/article/details/7640880

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-8
From Tkinter Import *
From random import Randint
Import Tkmessagebox

Class Grid (object):
def __init__ (self, master=none,height=16, width=24, offset=10, grid_width=50, bg= "#808080"):
Self.height = height
Self.width = width
Self.offset = Offset
Self.grid_width = Grid_width
self.bg = BG
Self.canvas = Canvas (Master, Width=self.width*self.grid_width+2*self.offset, height=self.height*self.grid_width+
2*self.offset, bg=self.bg)
Self.canvas.pack (Side=right, fill=y)

def draw (self, POS, color,):
x = pos[0] * self.grid_width + self.offset
y = pos[1] * self.grid_width + self.offset
#outline属性要与网格的背景色 (self.bg) is the same, otherwise it will be ugly
Self.canvas.create_rectangle (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, Self.color)


Class Snake (object):
def __init__ (self, grid, color = "#000000"):
Self.grid = Grid
Self.color = Color
Self.body = [(8, 11), (8, 12), (8, 13)]
Self.direction = "Up"
For I in Self.body:
Self.grid.draw (i, Self.color)

#这个方法用于游戏重新开始时初始化贪吃蛇的位置
def initial (self):
While not len (self.body) = = 0:
Pop = Self.body.pop ()
Self.grid.draw (pop, self.grid.bg)
Self.body = [(8, 11), (8, 12), (8, 13)]
Self.direction = "Up"
Self.color = "#000000"
For 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 increase the length
def add (self, new):
Self.body.insert (0, new)
Self.grid.draw (new, Self.color)

#蛇吃到了特殊食物1, cut its length.
def cut_down (self,new):
Self.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, changing the color of their own, is purely fun
def change (self, new, color):
Self.color = Color
Self.body.insert (0, new)
For item in Self.body:
Self.grid.draw (item, Self.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 = 300
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, TEXTVARIABLE=SELF.M, aspect=5000, Font=self.ft1, bg= "#696969")
Self.m1.pack (Side=left, fill=y)
Self.m.set ("Score:" +str (Self.score))

#这个方法用于游戏重新开始时初始化游戏
def initial (self):
Self.gameover = False
Self.score = 0
Self.m.set ("Score:" +str (Self.score))
Self.snake.initial ()

#type1: General food type2: reduced by 2 Type3: Lotto, back to the original state type4: Eating will change color
def display_food (self):
Self.food.color = "#23D978"
Self.food.type = 1
If Randint (0, 40) = = 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) > Randint (0, 16) = = 5:
Self.food.color = "#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 in 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 '}
#蛇不可以像自己的反方向走
If Key_dict.has_key (key) and not key = = Key_dict[self.snake.direction]:
Self.snake.direction = key
Self.move ()
elif key = = ' P ':
Self.status.reverse ()

def run (self):
#首先判断游戏是否暂停
If not self.status[0] = = ' Stop ':
#判断游戏是否结束
if Self.gameover = = True:
Message = Tkmessagebox.showinfo ("Game over", "Your score:%d"% self.score)
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"):
# Calculate the next point the snake moves
Head = self.snake.body[0]
if self.snake.direction = = ' Up ':
If HEAD[1]-1 < 0:
New = (Head[0], 16)
Else
New = (Head[0], head[1]-1)
elif self.snake.direction = = ' Down ':
New = (Head[0], (head[1] + 1)% 16)
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 game to the end of the flag bit, waiting 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.snake.init (New)
Self.display_food ()
Self.score = self.score+1
Self.m.set ("Score:" + str (self.score))
#什么都没撞到, move on.
Else
Self.snake.move (New)

if __name__ = = ' __main__ ':
root = Tk ()
Snakegame = Snakegame (Root)
Snakegame.run ()
Snakegame.mainloop ()

Use Python to write a snake

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.