python写贪吃蛇游戏代码
时间: 2023-04-04 11:01:36 浏览: 329
你好,我可以回答这个问题。以下是 Python 写贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
# 颜色定义
BLACK = (, , )
WHITE = (255, 255, 255)
GREEN = (, 255, )
RED = (255, , )
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和大小
snake_x = 300
snake_y = 300
snake_width = 10
snake_height = 10
# 定义蛇的移动速度
snake_speed = 10
# 定义蛇的初始移动方向
snake_direction = 'right'
# 定义食物的初始位置和大小
food_x = random.randint(, WINDOW_WIDTH - 10)
food_y = random.randint(, WINDOW_HEIGHT - 10)
food_width = 10
food_height = 10
# 定义游戏循环标志
game_running = True
# 游戏循环
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
# 处理键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_direction = 'left'
elif keys[pygame.K_RIGHT]:
snake_direction = 'right'
elif keys[pygame.K_UP]:
snake_direction = 'up'
elif keys[pygame.K_DOWN]:
snake_direction = 'down'
# 移动蛇
if snake_direction == 'left':
snake_x -= snake_speed
elif snake_direction == 'right':
snake_x += snake_speed
elif snake_direction == 'up':
snake_y -= snake_speed
elif snake_direction == 'down':
snake_y += snake_speed
# 检测蛇是否碰到边界
if snake_x < or snake_x > WINDOW_WIDTH - snake_width or snake_y < or snake_y > WINDOW_HEIGHT - snake_height:
game_running = False
# 检测蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randint(, WINDOW_WIDTH - 10)
food_y = random.randint(, WINDOW_HEIGHT - 10)
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.rect(window, GREEN, (food_x, food_y, food_width, food_height))
pygame.draw.rect(window, WHITE, (snake_x, snake_y, snake_width, snake_height))
pygame.display.update()
# 退出 Pygame
pygame.quit()
```
希望能对你有所帮助!
阅读全文