🐍 贪吃蛇 - 在线试玩

分数: 0 速度: 1

使用方向键 ↑↓←→ 控制移动

# -*- coding: utf-8 -*-
import pygame
import random

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("贪吃蛇")

# 初始化蛇和食物
snake = [(300, 200), (290, 200), (280, 200)]
direction = 'RIGHT'
food = (random.randint(0, 58)*10, random.randint(0, 38)*10)
score = 0

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != 'DOWN':
                direction = 'UP'
            # ... 其他方向键处理
    
    # 移动蛇
    head = snake[0]
    if direction == 'RIGHT': new_head = (head[0]+10, head[1])
    elif direction == 'LEFT': new_head = (head[0]-10, head[1])
    # ... 上下移动
    
    snake.insert(0, new_head)
    
    # 吃食物
    if new_head == food:
        score += 1
        food = (random.randint(0, 58)*10, random.randint(0, 38)*10)
    else:
        snake.pop()
    
    # 碰撞检测
    if (new_head[0] < 0 or new_head[0] >= 600 or
        new_head[1] < 0 or new_head[1] >= 400 or
        new_head in snake[1:]):
        print(f"游戏结束! 最终得分: {score}")
        break
    
    pygame.display.update()
    pygame.time.delay(100)

pygame.quit()
本地运行方法:
  1. 安装 Python 3.x
  2. 安装 pygame: pip install pygame
  3. 保存代码为 snake.py
  4. 运行: python snake.py
操作说明:
  • ↑ 上
  • ↓ 下
  • ← 左
  • → 右