python制作贪吃蛇小游戏
时间: 2023-08-28 11:06:13 浏览: 96
python实现的贪吃蛇小游戏
好的,下面是一个简单的贪吃蛇小游戏的 Python 代码,你可以在 Python 环境中运行它:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口尺寸
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 400
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇小游戏")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇的初始位置和大小
SNAKE_SIZE = 10
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2
snake_dx = SNAKE_SIZE
snake_dy = 0
# 定义食物的初始位置
food_x = random.randint(0, WINDOW_WIDTH - SNAKE_SIZE)
food_y = random.randint(0, WINDOW_HEIGHT - SNAKE_SIZE)
# 定义贪吃蛇和食物的大小
SNAKE_SIZE = 10
FOOD_SIZE = 10
# 定义游戏循环标志
running = True
# 定义计分
score = 0
# 定义字体
font = pygame.font.Font(None, 30)
# 游戏循环
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_dx = -SNAKE_SIZE
snake_dy = 0
elif event.key == pygame.K_RIGHT:
snake_dx = SNAKE_SIZE
snake_dy = 0
elif event.key == pygame.K_UP:
snake_dx = 0
snake_dy = -SNAKE_SIZE
elif event.key == pygame.K_DOWN:
snake_dx = 0
snake_dy = SNAKE_SIZE
# 更新贪吃蛇的位置
snake_x += snake_dx
snake_y += snake_dy
# 判断是否吃到食物
if snake_x < food_x + FOOD_SIZE and snake_x + SNAKE_SIZE > food_x and snake_y < food_y + FOOD_SIZE and snake_y + SNAKE_SIZE > food_y:
food_x = random.randint(0, WINDOW_WIDTH - SNAKE_SIZE)
food_y = random.randint(0, WINDOW_HEIGHT - SNAKE_SIZE)
score += 1
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.rect(window, GREEN, [food_x, food_y, FOOD_SIZE, FOOD_SIZE])
snake_rect = pygame.draw.rect(window, WHITE, [snake_x, snake_y, SNAKE_SIZE, SNAKE_SIZE])
# 判断游戏是否结束
if snake_x < 0 or snake_x > WINDOW_WIDTH - SNAKE_SIZE or snake_y < 0 or snake_y > WINDOW_HEIGHT - SNAKE_SIZE:
running = False
# 显示分数
score_text = font.render("Score: " + str(score), True, RED)
window.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
pygame.time.Clock().tick(20)
# 退出 Pygame
pygame.quit()
```
在这个游戏中,你可以使用方向键来控制贪吃蛇的移动方向,吃到食物会加分,碰到边界或自己的身体游戏就结束了。你可以根据自己的需求对代码进行修改和扩展,让它变得更加有趣和有挑战性。
阅读全文