python贪吃蛇
时间: 2023-06-21 10:06:59 浏览: 46
好的,下面是一个简单的 Python 贪吃蛇游戏示例代码:
```python
import pygame
import random
# 游戏界面大小
WIDTH = 800
HEIGHT = 600
# 蛇的大小
SNAKE_SIZE = 20
# 初始化 pygame
pygame.init()
# 创建游戏界面
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.SysFont(None, 48)
# 定义蛇
snake = [(WIDTH // 2, HEIGHT // 2)]
snake_direction = "right"
# 定义食物
food = (random.randint(0, (WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE,
random.randint(0, (HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE)
# 定义计分
score = 0
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != "down":
snake_direction = "up"
elif event.key == pygame.K_DOWN and snake_direction != "up":
snake_direction = "down"
elif event.key == pygame.K_LEFT and snake_direction != "right":
snake_direction = "left"
elif event.key == pygame.K_RIGHT and snake_direction != "left":
snake_direction = "right"
# 移动蛇
x, y = snake[-1]
if snake_direction == "up":
y -= SNAKE_SIZE
elif snake_direction == "down":
y += SNAKE_SIZE
elif snake_direction == "left":
x -= SNAKE_SIZE
elif snake_direction == "right":
x += SNAKE_SIZE
snake.append((x, y))
# 判断是否吃到食物
if (x, y) == food:
food = (random.randint(0, (WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE,
random.randint(0, (HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE)
score += 10
else:
snake.pop(0)
# 判断是否撞到墙壁或自身
if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT or (x, y) in snake[:-1]:
game_over_text = font.render("Game Over!", True, RED)
screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2,
HEIGHT // 2 - game_over_text.get_height() // 2))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
quit()
# 绘制游戏界面
screen.fill(WHITE)
for x, y in snake:
pygame.draw.rect(screen, BLACK, (x, y, SNAKE_SIZE, SNAKE_SIZE))
pygame.draw.rect(screen, GREEN, (food[0], food[1], SNAKE_SIZE, SNAKE_SIZE))
score_text = font.render("Score: " + str(score), True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(10)
```
你可以将以上代码复制到 Python 编辑器中运行,即可体验贪吃蛇游戏。