Did you play snake when you were young ? Xiaobian loved playing with his parents' mobile phones when he was a child , It's amazing ! today , Xiaobian will use it 100 Line of code to achieve a simple version of the snake . on the internet , There are a lot of snake lessons , But there are many libraries to install , And it's not clear enough , Today's code is short , And it's easier to understand or change . The final results are as follows :
image
Basic preparation
first , We need to install it pygame library , Xiaobian passed pip install pygame, It was soon installed . When finishing the snake game , We need to know that the whole game is divided into four parts :
* Game display : Game interface , End interface
* Snake eating : head , body , Food judgment , Death judgment
* raspberry : Random generation
* Key control : upper , lower , Left , right
Game display
first , Let's initialize pygame, define color , Window size of game interface , Titles and icons, etc .
1# initialization pygame 2pygame.init() 3fpsClock = pygame.time.Clock() 4# establish pygame Display layer
5playSurface = pygame.display.set_mode((600,460))# Window size
6pygame.display.set_caption('Snake Game')# Window name 7# Define color variables 8redColour =
pygame.Color(255,0,0) 9blackColour = pygame.Color(0,0,0) 10whiteColour =
pygame.Color(255,255,255) 11greyColour = pygame.Color(150,150,150)
Game end interface , We'll show you “Game Over!” And the game score , The relevant codes are as follows :
1# definition gameOver function 2def gameOver(playSurface,score): 3 gameOverFont =
pygame.font.SysFont('arial.ttf',54) # End of game font and size 4 gameOverSurf =
gameOverFont.render('Game Over!', True, greyColour) # Game end content display 5 gameOverRect =
gameOverSurf.get_rect() 6 gameOverRect.midtop = (300, 10) # Display location 7
playSurface.blit(gameOverSurf, gameOverRect) 8 scoreFont =
pygame.font.SysFont('arial.ttf',54) # Score display 9 scoreSurf =
scoreFont.render('Score:'+str(score), True, greyColour) 10 scoreRect =
scoreSurf.get_rect() 11 scoreRect.midtop = (300, 50) 12
playSurface.blit(scoreSurf, scoreRect) 13 pygame.display.flip() # Refresh the display interface 14
time.sleep(5) # Sleep for five seconds to exit the interface automatically 15 pygame.quit() 16 sys.exit()
Snake and raspberry
We need to think of the whole interface as many 20*20 Small square of , Each square represents a unit , The length of a snake is expressed in units , At the same time, we store the snake's body in the form of a list . meanwhile ,
We all know that , The location of raspberries is random . therefore , We need raspberries in random places in the game interface , meanwhile , Every time I eat a raspberry , You need to regenerate a new raspberry , And score plus 1. The relevant initialization settings are as follows :
1snakePosition = [100,100] # Snake eating The position of the snake's head 2snakeSegments = [[100,100]] # Snake eating
Snake's body , The initial value is one unit 3raspberryPosition = [300,300] # Initial position of raspberry 4raspberrySpawned = 1
# The number of raspberries is 1 5direction = 'right' # The initial direction is right 6changeDirection = direction 7score = 0
# Initial score
How to control the snake's trajectory , Then you need to press the key to control it . We use the keyboard ↑↓←→ and WSAD To control , If you want to quit the game directly , You can go through the Esc key . What needs to be emphasized here is that , The snake can't move in the opposite direction , therefore , We need further restrictions :
1# Detection, such as keys, etc pygame event 2for event in pygame.event.get(): 3 if event.type == QUIT:
4 pygame.quit() 5 sys.exit() 6 elif event.type == KEYDOWN: 7 # Judge keyboard events 8 if
event.key == K_RIGHT or event.key == ord('d'): 9 changeDirection = 'right' 10
if event.key == K_LEFT or event.key == ord('a'): 11 changeDirection = 'left' 12
if event.key == K_UP or event.key == ord('w'): 13 changeDirection = 'up' 14 if
event.key == K_DOWN or event.key == ord('s'): 15 changeDirection = 'down' 16 if
event.key == K_ESCAPE: 17 pygame.event.post(pygame.event.Event(QUIT)) 18#
Judge whether the opposite direction is input 19if changeDirection == 'right' and not direction == 'left': 20
direction = changeDirection 21if changeDirection == 'left' and not direction ==
'right': 22 direction = changeDirection 23if changeDirection == 'up' and not
direction == 'down': 24 direction = changeDirection 25if changeDirection ==
'down' and not direction == 'up': 26 direction = changeDirection
The direction is set , So how to change the snake body ? It's simple , We just need to change the coordinates according to the direction .
1# Move the coordinates of the snake's head according to the direction 2if direction == 'right': 3 snakePosition[0] += 20 4if
direction == 'left': 5 snakePosition[0] -= 20 6if direction == 'up': 7
snakePosition[1] -= 20 8if direction == 'down': 9 snakePosition[1] += 20 10#
Increase the length of the snake 11snakeSegments.insert(0,list(snakePosition))
The most important things in Snake game are food judgment and death judgment . The first is food judgment , We use the keyboard to decide the direction of the snake , So that it can eat raspberries . How to judge whether a snake has eaten raspberries ? It's simple , If the position of the snake's head coincides with that of the raspberry , That's the same , Then snake will eat raspberry , Otherwise, No . meanwhile , Once the raspberry is eaten , Immediately regenerate a new raspberry randomly . The relevant codes are as follows :
1# Determine if the raspberry was eaten 2if snakePosition[0] == raspberryPosition[0] and snakePosition[1]
== raspberryPosition[1]: 3 raspberrySpawned = 0 4 else: 5 snakeSegments.pop()
# If you don't eat raspberries , You need to put the snake body of the last unit out of the list , This is related to the position change of the snake when it moves 6# If you eat raspberries , The raspberry is regenerated 7if raspberrySpawned
== 0: 8 x = random.randrange(1,30) # It's related to the size of the game interface 9 y = random.randrange(1,23) 10
raspberryPosition = [int(x*20),int(y*20)] 11 raspberrySpawned = 1 12 score += 1
Death judgment is divided into two categories , One is to touch the boundary of the game interface , Second, the snake touched his body . In the event of death , Then trigger gameover.
1# Judge whether death or not 2if snakePosition[0] > 600 or snakePosition[0] < 0:
# If it exceeds the left and right boundaries , trigger gameover 3 gameOver(playSurface,score) 4if snakePosition[1] > 460 or
snakePosition[1] < 0: # If it exceeds the upper and lower boundaries , trigger gameover 5 gameOver(playSurface,score) 6for
snakeBody in snakeSegments[1:]: # If you touch your body , trigger gameover 7 if snakePosition[0] ==
snakeBody[0] and snakePosition[1] == snakeBody[1]: 8 gameOver(playSurface,score)
Snake eating and raspberry eating , The game interface needs to be constantly updated . meanwhile , We set the speed of the game .
1# draw pygame Display layer 2playSurface.fill(blackColour) # The snake is white 3for position in
snakeSegments: 4
pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20)) 5
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0],
raspberryPosition[1],20,20)) 6 7# Refresh pygame Display layer 8pygame.display.flip() 9# Control game speed
10fpsClock.tick(5)
thus , We can finish a snake game . Let's have an experiment !
The complete code is as follows :
1import pygame,sys,time,random 2from pygame.locals import * 3# Define color variables
4redColour = pygame.Color(255,0,0) 5blackColour = pygame.Color(0,0,0)
6whiteColour = pygame.Color(255,255,255) 7greyColour =
pygame.Color(150,150,150) 8def gameOver(playSurface,score): 9 gameOverFont =
pygame.font.SysFont('arial.ttf',54) 10 gameOverSurf = gameOverFont.render('Game
Over!', True, greyColour) 11 gameOverRect = gameOverSurf.get_rect() 12
gameOverRect.midtop = (300, 10) 13 playSurface.blit(gameOverSurf, gameOverRect)
14 scoreFont = pygame.font.SysFont('arial.ttf',54) 15 scoreSurf =
scoreFont.render('Score:'+str(score), True, greyColour) 16 scoreRect =
scoreSurf.get_rect() 17 scoreRect.midtop = (300, 50) 18
playSurface.blit(scoreSurf, scoreRect) 19 pygame.display.flip() 20
time.sleep(5) 21 pygame.quit() 22 sys.exit() 23def main(): 24 # initialization pygame 25
pygame.init() 26 fpsClock = pygame.time.Clock() 27 # establish pygame Display layer 28 playSurface
= pygame.display.set_mode((600,460)) 29 pygame.display.set_caption('Snake
Game') 30 # initialize variable 31 snakePosition = [100,100] # Snake eating The position of the snake's head 32 snakeSegments =
[[100,100]] # Snake eating Snake's body , The initial value is one unit 33 raspberryPosition = [300,300] # Initial position of raspberry 34
raspberrySpawned = 1 # The number of raspberries is 1 35 direction = 'right' # The initial direction is right 36 changeDirection
= direction 37 score = 0 # Initial score 38 while True: 39 # Detection, such as keys, etc pygame event 40 for event
in pygame.event.get(): 41 if event.type == QUIT: 42 pygame.quit() 43 sys.exit()
44 elif event.type == KEYDOWN: 45 # Judge keyboard events 46 if event.key == K_RIGHT or
event.key == ord('d'): 47 changeDirection = 'right' 48 if event.key == K_LEFT
or event.key == ord('a'): 49 changeDirection = 'left' 50 if event.key == K_UP
or event.key == ord('w'): 51 changeDirection = 'up' 52 if event.key == K_DOWN
or event.key == ord('s'): 53 changeDirection = 'down' 54 if event.key ==
K_ESCAPE: 55 pygame.event.post(pygame.event.Event(QUIT)) 56 # Judge whether the opposite direction is input 57 if
changeDirection == 'right' and not direction == 'left': 58 direction =
changeDirection 59 if changeDirection == 'left' and not direction == 'right':
60 direction = changeDirection 61 if changeDirection == 'up' and not direction
== 'down': 62 direction = changeDirection 63 if changeDirection == 'down' and
not direction == 'up': 64 direction = changeDirection 65 # Move the coordinates of the snake's head according to the direction 66 if
direction == 'right': 67 snakePosition[0] += 20 68 if direction == 'left': 69
snakePosition[0] -= 20 70 if direction == 'up': 71 snakePosition[1] -= 20 72 if
direction == 'down': 73 snakePosition[1] += 20 74 # Increase the length of the snake 75
snakeSegments.insert(0,list(snakePosition)) 76 # Determine if the raspberry was eaten 77 if
snakePosition[0] == raspberryPosition[0] and snakePosition[1] ==
raspberryPosition[1]: 78 raspberrySpawned = 0 79 else: 80 snakeSegments.pop()
81 # If you eat raspberries , The raspberry is regenerated 82 if raspberrySpawned == 0: 83 x = random.randrange(1,30)
84 y = random.randrange(1,23) 85 raspberryPosition = [int(x*20),int(y*20)] 86
raspberrySpawned = 1 87 score += 1 88 # draw pygame Display layer 89
playSurface.fill(blackColour) 90 for position in snakeSegments: 91
pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
92 pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0],
raspberryPosition[1],20,20)) 93 # Refresh pygame Display layer 94 pygame.display.flip() 95 #
Judge whether death or not 96 if snakePosition[0] > 600 or snakePosition[0] < 0: 97
gameOver(playSurface,score) 98 if snakePosition[1] > 460 or snakePosition[1] <
0: 99 gameOver(playSurface,score) 100 for snakeBody in snakeSegments[1:]: 101
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]: 102
gameOver(playSurface,score) 103 # Control game speed 104 fpsClock.tick(5) 105 106if
__name__ == "__main__": 107 main()
Technology