python 贪吃蛇小游戏
时间: 2024-01-31 09:11:00 浏览: 96
100行Python代码的贪吃蛇小游戏源码.zip
5星 · 资源好评率100%
以下是使用Python编写的贪吃蛇小游戏的示例代码:
```python
import pygame
import time
# 初始化pygame
pygame.init()
# 设置游戏窗口的宽度和高度
window_width = 800
window_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇小游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的初始位置和大小
snake_x = 50
snake_y = 50
snake_size = 10
# 定义蛇的移动速度
snake_speed = 15
# 定义蛇的移动方向
snake_direction = "right"
# 游戏主循环
game_over = False
while not game_over 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:
snake_direction = "left"
elif event.key == pygame.K_RIGHT:
snake_direction = "right"
elif event.key == pygame.K_UP:
snake_direction = "up"
elif event.key == 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
# 清空屏幕
screen.fill(black)
# 绘制蛇的身体
pygame.draw.rect(screen, green, [snake_x, snake_y, snake_size, snake_size])
# 更新屏幕显示
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(30)
# 退出游戏
pygame.quit()
```
阅读全文