用 Python 实现经典贪吃蛇游戏
实现经典贪吃蛇游戏可以使用 Python 的 pygame
库来进行。下面是一个简单的贪吃蛇游戏的实现示例:
import pygame
import time
import random
pygame.init()
# 定义一些常量
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
SNAKE_BLOCK = 10
SNAKE_SPEED = 15
# 初始化显示窗口
display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('贪吃蛇')
clock = pygame.time.Clock()
snake_font = pygame.font.SysFont(None, 50)
def display_score(score):
value = snake_font.render("Your Score: " + str(score), True, BLACK)
display.blit(value, [0, 0])
def draw_snake(snake_block, snake_list):
for block in snake_list:
pygame.draw.rect(display, BLACK, [block[0], block[1], snake_block, snake_block])
def game_loop():
game_over = False
game_close = False
x = DISPLAY_WIDTH / 2
y = DISPLAY_HEIGHT / 2
x_change = 0
y_change = 0
snake_list = []
length_of_snake = 1
food_x = round(random.randrange(0, DISPLAY_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
food_y = round(random.randrange(0, DISPLAY_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
while not game_over:
while game_close:
display.fill(BLUE)
display_score(length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -SNAKE_BLOCK
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = SNAKE_BLOCK
y_change = 0
elif event.key == pygame.K_UP:
y_change = -SNAKE_BLOCK
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = SNAKE_BLOCK
x_change = 0
if x >= DISPLAY_WIDTH or x < 0 or y >= DISPLAY_HEIGHT or y < 0:
game_close = True
x += x_change
y += y_change
display.fill(BLUE)
pygame.draw.rect(display, GREEN, [food_x, food_y, SNAKE_BLOCK, SNAKE_BLOCK])
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
for block in snake_list[:-1]:
if block == snake_head:
game_close = True
draw_snake(SNAKE_BLOCK, snake_list)
display_score(length_of_snake - 1)
pygame.display.update()
if x == food_x and y == food_y:
food_x = round(random.randrange(0, DISPLAY_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
food_y = round(random.randrange(0, DISPLAY_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
length_of_snake += 1
clock.tick(SNAKE_SPEED)
pygame.quit()
quit()
game_loop()
运行游戏步骤:
- 确保安装了
pygame
库,可以通过pip install pygame
安装。 - 复制上述代码到一个 Python 文件中,比如
snake_game.py
。 - 运行脚本:
python snake_game.py
。 - 使用方向键(上下左右)来控制蛇的移动。
- 按
Q
结束游戏,按C
重启游戏。
此实现可以用作理解 pygame 的基础,随后可以在此基础上加上更多的功能和改进,比如不同难度级别、音效、不同的画面等。