帮我写一个贪吃蛇的代码并运行
时间: 2024-01-06 14:05:03 浏览: 70
贪吃蛇的代码实现
由于您没有说明具体语言,我将以Python为例,为您提供一个简单的贪吃蛇代码。
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化pygame
pygame.init()
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置字体
font = pygame.font.SysFont(None, 48)
# 设置贪吃蛇初始位置
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 设置食物初始位置
food_position = [random.randrange(1, (SCREEN_WIDTH // 10)) * 10,
random.randrange(1, (SCREEN_HEIGHT // 10)) * 10]
food_spawn = True
# 设置初始方向
direction = "RIGHT"
change_to = direction
# 设置游戏结束标志
game_over = False
# 定义游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
# 确定方向
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 移动贪吃蛇
if direction == "RIGHT":
snake_position[0] += 10
elif direction == "LEFT":
snake_position[0] -= 10
elif direction == "UP":
snake_position[1] -= 10
elif direction == "DOWN":
snake_position[1] += 10
# 更新贪吃蛇
snake_body.insert(0, list(snake_position))
if snake_position == food_position:
food_spawn = False
else:
snake_body.pop()
# 生成食物
if not food_spawn:
food_position = [random.randrange(1, (SCREEN_WIDTH // 10)) * 10,
random.randrange(1, (SCREEN_HEIGHT // 10)) * 10]
food_spawn = True
# 绘制屏幕
screen.fill(BLACK)
for position in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(
position[0], position[1], 10, 10))
pygame.draw.rect(screen, BLUE, pygame.Rect(
food_position[0], food_position[1], 10, 10))
# 判断游戏结束
if snake_position[0] < 0 or snake_position[0] > SCREEN_WIDTH-10:
game_over = True
elif snake_position[1] < 0 or snake_position[1] > SCREEN_HEIGHT-10:
game_over = True
for block in snake_body[1:]:
if snake_position == block:
game_over = True
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
fps = pygame.time.Clock()
fps.tick(15)
# 显示游戏结束信息
text = font.render("Game Over", True, RED)
screen.blit(text, [SCREEN_WIDTH/2-100, SCREEN_HEIGHT/2-50])
pygame.display.update()
# 关闭pygame
pygame.quit()
```
您可以将此代码保存为一个.py文件,然后在命令行中运行。当您运行该代码时,将会看到贪吃蛇游戏窗口。您可以通过键盘上的方向键来控制贪吃蛇的移动方向。当贪吃蛇碰到边界或自己时,游戏将会结束,并显示"Game Over"字样。
阅读全文