Example of a snake game written in Python

Source: Internet
Author: User

For the first time, use Python to write this practical and fun thing.

Game Description:

* P key control "Pause/start"
* The direction key controls the direction of the snake

The source code is as follows:
Copy codeThe Code is as follows:
From Tkinter import *
Import tkMessageBox, sys
From random import randint

Class Grid (object ):
Def _ init _ (self, master = None, window_width = 800, window_height = 600, grid_width = 50, offset = 10 ):
Self. height = window_height
Self. width = window_width
Self. grid_width = grid_width
Self. offset = offset
Self. grid_x = self. width/self. grid_width
Self. grid_y = self. height/self. grid_width
Self. bg = "# EBEBEB"
Self. 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 = pos [0] * self. grid_width + self. offset
Y = pos [1] * self. grid_width + self. offset
Self. 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_list

Class Food (object ):
Def _ init _ (self, Grid ):
Self. grid = Grid
Self. color = "#23D978"
Self. 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 = Grid
Self. body = [(10, 6), (10, 7), (10, 8)]
Self. direction = "Up"
Self. status = ['run', 'stop']
Self. speed = 300
Self. color = "#5FA8D9"
Self. food = Food (self. grid)
Self. display_food ()
Self. gameover = False
Self. score = 0
Def available_grid (self ):
Return [I for I in self. grid. grid_list if I not in self. body [2:]
Def change_direction (self, direction ):
Self. direction = direction
Def display (self ):
For (x, y) in self. body:
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. body [0]
If self. direction = 'up ':
New = (head [0], head [1]-1)
Elif self. direction = 'low ':
New = (head [0], head [1] + 1)
Elif self. direction = 'left ':
New = (head [0]-1, head [1])
Else:
New = (head [0] + 1, head [1])
If not self. food. pos = head:
Pop = self. body. pop ()
Self. grid. draw (pop, self. grid. bg)
Else:
Self. display_food ()
Self. score + = 1
Self. body. insert (0, new)
If not new in self. available_grid ():
Self. status. reverse ()
Self. gameover = True
Else:
Self. grid. draw (new, color = self. color)

Class snail keame (Frame ):
Def _ init _ (self, master = None, * args, ** kwargs ):
Frame. _ init _ (self, master)
Self. master = master
Self. 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. status [0] = 'stop ':
Self. snake. move ()
If self. snake. gameover = True:
Message = tkMessageBox. 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. 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. change_direction (key)
Self. snake. move ()
Elif key = 'P ':
Self. snake. status. reverse ()

If _ name _ = '_ main __':
Root = Tk ()
Snail keame = snail keame (root)
Snkegame. run ()
Snkegame. mainloop ()

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.