grok-3-mini-beta· xAI
LMArena Human Preference 140K
写一个贪食蛇游戏
- User
写一个贪食蛇游戏
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
写一个贪食蛇游戏
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
下面是一个简单的贪食蛇游戏的实现,使用 Python 和 Pygame 库。Pygame 是一个流行的 Python 游戏开发库,如果你还没有安装它,可以通过命令行运行 pip install pygame 来安装。
snake_game.py。python snake_game.py。以下是完整的代码:
import pygame
import random
import time
# 初始化常量
WIDTH = 640 # 窗口宽度
HEIGHT = 480 # 窗口高度
SNAKE_SIZE = 20 # 蛇块大小
FOOD_SIZE = 20 # 食物大小
SPEED = 15 # 蛇移动速度(帧率)
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 初始化 Pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪食蛇游戏")
clock = pygame.time.Clock()
# 蛇的初始位置和方向
snake_pos = [[100, 100], [90, 100], [80, 100]] # 蛇的身体列表,列表中的每个元素是 [x, y] 坐标
direction = 'RIGHT' # 初始方向
score = 0 # 初始得分
# 生成食物的函数
def generate_food():
food_x = round(random.randrange(0, WIDTH - FOOD_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, HEIGHT - FOOD_SIZE) / 20.0) * 20.0
return [food_x, food_y]
food_pos = generate_food() # 生成第一个食物
# 游戏主循环
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_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == pygame.K_DOWN and direction != 'UP':
direction = 'DOWN'
elif event.key == pygame.K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == pygame.K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
# 更新蛇头位置
if direction == 'UP':
new_head = [snake_pos[0][0], snake_pos[0][1] - SNAKE_SIZE]
elif direction == 'DOWN':
new_head = [snake_pos[0][0], snake_pos[0][1] + SNAKE_SIZE]
elif direction == 'LEFT':
new_head = [snake_pos[0][0] - SNAKE_SIZE, snake_pos[0][1]]
elif direction == 'RIGHT':
new_head = [snake_pos[0][0] + SNAKE_SIZE, snake_pos[0][1]]
# 插入新头
snake_pos.insert(0, new_head)
# 检查蛇是否吃到食物
if snake_pos[0] == food_pos:
score += 1
food_pos = generate_food() # 生成新食物
else:
snake_pos.pop() # 移除蛇尾巴
# 检查碰撞
if (snake_pos[0][0] < 0 or snake_pos[0][0] >= WIDTH or
snake_pos[0][1] < 0 or snake_pos[0][1] >= HEIGHT):
game_over = True # 撞墙
for pos in snake_pos[1:]:
if snake_pos[0] == pos:
game_over = True # 撞到自己
# 绘制游戏画面
screen.fill(BLACK) # 填充背景色
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], SNAKE_SIZE, SNAKE_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], FOOD_SIZE, FOOD_SIZE))
# 显示得分
font = pygame.font.SysFont(None, 35)
text = font.render("得分: " + str(score), True, WHITE)
screen.blit(text, [0, 0])
pygame.display.update() # 更新显示
clock.tick(SPEED) # 控制帧率
pygame.quit() # 退出 Pygame
这个代码是基础版本,如果你有任何问题或想添加功能,可以告诉我,我可以帮忙修改! 😊