Python做一个贪吃蛇的游戏
时间: 2023-11-22 15:56:31 浏览: 72
好的,以下是一个简单的 Python 贪吃蛇游戏代码,使用 Pygame 模块:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义游戏窗口大小
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
# 定义贪吃蛇和食物方块大小
BLOCK_SIZE = 20
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 创建游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Snake Game')
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 30)
def draw_snake(snake_body):
for block in snake_body:
pygame.draw.rect(game_window, GREEN, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
def draw_food(food_position):
pygame.draw.rect(game_window, RED, [food_position[0], food_position[1], BLOCK_SIZE, BLOCK_SIZE])
def game_loop():
# 定义贪吃蛇初始位置和方向
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2
snake_x_change = 0
snake_y_change = 0
snake_body = []
snake_length = 1
# 定义食物初始位置
food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_position = [food_x, food_y]
# 游戏结束标志
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -BLOCK_SIZE
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = BLOCK_SIZE
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -BLOCK_SIZE
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = BLOCK_SIZE
snake_x_change = 0
# 更新贪吃蛇位置
snake_x += snake_x_change
snake_y += snake_y_change
# 判断贪吃蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
food_position = [food_x, food_y]
snake_length += 1
# 更新贪吃蛇身体
snake_head = [snake_x, snake_y]
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# 判断贪吃蛇是否撞墙或撞到自己
if snake_x < 0 or snake_x >= WINDOW_WIDTH or snake_y < 0 or snake_y >= WINDOW_HEIGHT:
game_over = True
for block in snake_body[:-1]:
if block == snake_head:
game_over = True
# 绘制游戏窗口
game_window.fill(WHITE)
draw_snake(snake_body)
draw_food(food_position)
score_text = font.render("Score: {}".format(snake_length - 1), True, BLACK)
game_window.blit(score_text, [0, 0])
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 退出 Pygame
pygame.quit()
quit()
game_loop()
```
你可以将以上代码保存为 `snake.py` 文件并运行,即可开始游戏。
阅读全文