用python语言运行的贪吃蛇游戏
时间: 2024-05-03 13:21:33 浏览: 32
抱歉,作为AI语言模型,我无法提供代码运行功能,但我可以为您提供一个基础的贪吃蛇游戏的Python代码,您可以在本地运行它:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
BLOCK_SIZE = 20
SNAKE_SIZE = 3
FOOD_COLOR = (255, 0, 0)
SNAKE_COLOR = (0, 255, 0)
BG_COLOR = (0, 0, 0)
UP = 1
RIGHT = 2
DOWN = 3
LEFT = 4
# 定义游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 创建一个蛇
snake = []
for i in range(SNAKE_SIZE):
snake.append((int(SCREEN_WIDTH / 2 / BLOCK_SIZE) * BLOCK_SIZE + i * BLOCK_SIZE, int(SCREEN_HEIGHT / 2 / BLOCK_SIZE) * BLOCK_SIZE))
# 创建食物
food_x = random.randint(0, SCREEN_WIDTH / BLOCK_SIZE - 1) * BLOCK_SIZE
food_y = random.randint(0, SCREEN_HEIGHT / BLOCK_SIZE - 1) * BLOCK_SIZE
# 初始方向向右
direction = RIGHT
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != DOWN:
direction = UP
elif event.key == pygame.K_RIGHT and direction != LEFT:
direction = RIGHT
elif event.key == pygame.K_DOWN and direction != UP:
direction = DOWN
elif event.key == pygame.K_LEFT and direction != RIGHT:
direction = LEFT
# 移动蛇
head_x, head_y = snake[-1]
if direction == UP:
new_head = (head_x, head_y - BLOCK_SIZE)
elif direction == RIGHT:
new_head = (head_x + BLOCK_SIZE, head_y)
elif direction == DOWN:
new_head = (head_x, head_y + BLOCK_SIZE)
elif direction == LEFT:
new_head = (head_x - BLOCK_SIZE, head_y)
if new_head[0] < 0 or new_head[0] >= SCREEN_WIDTH or new_head[1] < 0 or new_head[1] >= SCREEN_HEIGHT or new_head in snake:
# 如果蛇撞墙或者撞自己,游戏结束
print("游戏结束")
pygame.quit()
exit()
snake.append(new_head)
if new_head == (food_x, food_y):
# 如果吃到食物,重新生成食物
food_x = random.randint(0, SCREEN_WIDTH / BLOCK_SIZE - 1) * BLOCK_SIZE
food_y = random.randint(0, SCREEN_HEIGHT / BLOCK_SIZE - 1) * BLOCK_SIZE
else:
# 如果没有吃到食物,去掉尾巴
snake.pop(0)
# 绘制背景
screen.fill(BG_COLOR)
# 绘制蛇
for i in range(len(snake)):
pygame.draw.rect(screen, SNAKE_COLOR, (snake[i][0], snake[i][1], BLOCK_SIZE, BLOCK_SIZE))
# 绘制食物
pygame.draw.rect(screen, FOOD_COLOR, (food_x, food_y, BLOCK_SIZE, BLOCK_SIZE))
# 更新屏幕
pygame.display.update()
# 控制游戏帧率
pygame.time.Clock().tick(10)
```
阅读全文