Pygame It's a group of people who develop game software Python Program modules , be based on SDL Library . Allow you to be in Python Program to create a rich function of the game and multimedia programs ,Pygame Is a highly portable module that can support multiple operating systems . Using it to develop small games is very suitable for .
Today is pygame Write Snake game .
SCREEN_WIDTH = 600 # Screen width
SCREEN_HEIGHT = 480 # Screen height
SIZE = 20 # Small square size
LINE_WIDTH = 1 # Grid line width
# The coordinate range of the game area
SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1)
SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1)
# Score and color of food
FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]
LIGHT = (100, 100, 100)
DARK = (200, 200, 200) # The color of the snake
BLACK = (0, 0, 0) # Grid line color
RED = (200, 30, 30) # Red ,GAME OVER Font color for
BGCOLOR = (40, 40, 60) # Background color
Copy code
Start writing code first , We need to define some variables , This includes screen size , The color of the snake , The color of the food , Background color and other important game elements .
# Initialize snake
def init_snake():
snake = deque()
snake.append((2, SCOPE_Y[0]))
snake.append((1, SCOPE_Y[0]))
snake.append((0, SCOPE_Y[0]))
return snake
Copy code
We need to initialize the snake , The data structure we use here is a queue , Snakes are a team , This is easier to understand .
def create_food(snake):
food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
while (food_x, food_y) in snake:
# If food comes to snakes , So let's start over
food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
return food_x, food_y
Copy code
Then we need to write the code to create the food . This food has a premise , That is, the position of food and snake should not overlap , So you need to traverse the snake's body , Make sure the random food position does not overlap with the snake .
if not game_over:
curTime = time.time()
if curTime - last_move_time > speed:
if not pause:
b = True
last_move_time = curTime
next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
if next_s == food:
# Eat the food
snake.appendleft(next_s)
score += food_style[0]
speed = orispeed - 0.03 * (score // 100)
food = create_food(snake)
food_style = get_food_style()
else:
if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \
and next_s not in snake:
snake.appendleft(next_s)
snake.pop()
else:
game_over = True
Copy code
The above paragraph is the core code , When the game is not over , Need to cycle all the time , The above code is in while What happened inside . Then monitor the data regularly , See if you have eaten any food , Refresh the food .
In general, game logic is not too difficult , Interested students can Official account : Poetic code , Come to me to discuss and study .