|
发表于 2025-4-8 17:28:29
|
显示全部楼层
以下是一个使用pygame实现的简单贪吃蛇游戏代码:
[code=python]
import pygame
import random
# 初始化
pygame.init()
WIDTH, HEIGHT = 600, 400
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("FishC贪吃蛇")
# 颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 游戏参数
CELL_SIZE = 20
SPEED = 10
# 方向控制
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def main():
snake = [(WIDTH//2, HEIGHT//2)]
direction = RIGHT
food = (random.randrange(0, WIDTH, CELL_SIZE),
random.randrange(0, HEIGHT, CELL_SIZE))
score = 0
clock = pygame.time.Clock()
running = True
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_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
# 移动蛇头
new_head = (snake[0][0] + direction[0]*CELL_SIZE,
snake[0][1] + direction[1]*CELL_SIZE)
# 碰撞检测
if (new_head[0] < 0 or new_head[0] >= WIDTH or
new_head[1] < 0 or new_head[1] >= HEIGHT or
new_head in snake):
running = False
snake.insert(0, new_head)
# 吃食物检测
if new_head == food:
score += 1
food = (random.randrange(0, WIDTH, CELL_SIZE),
random.randrange(0, HEIGHT, CELL_SIZE))
else:
snake.pop()
# 绘制画面
WIN.fill(BLACK)
for pos in snake:
pygame.draw.rect(WIN, GREEN, (pos[0], pos[1], CELL_SIZE, CELL_SIZE))
pygame.draw.rect(WIN, RED, (food[0], food[1], CELL_SIZE, CELL_SIZE))
# 显示分数
font = pygame.font.SysFont(None, 30)
text = font.render(f"分数: {score}", True, WHITE)
WIN.blit(text, (10, 10))
pygame.display.update()
clock.tick(SPEED)
pygame.quit()
if __name__ == "__main__":
main()
[/code]
- 使用方法:
- 1. 需要安装pygame库:pip install pygame
- 2. 使用方向键控制蛇的移动
- 3. 吃到红色食物增长,碰撞边界或自身游戏结束
注意:如果窗口无法关闭,可以按Alt+F4强制退出。可以通过修改CELL_SIZE调整格子大小,修改SPEED调整游戏速度。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|