回答于 2025-05-23
以下是一些常用的 Python小游戏代码资源(可复制、免费),适合新手学习和实践:
一、经典小游戏代码示例
1. 猜数字游戏
python import random
number = random.randint(1, 100) guess = 0 count = 0
print("猜一个1到100之间的数字!") while guess != number: guess = int(input("请输入你的猜测:")) count += 1 if guess < number: print("猜小了!") elif guess > number: print("猜大了!") print(f"恭喜!你用了{count}次猜对了!")
2. 贪吃蛇(需安装pygame库)
python
先安装依赖库:pip install pygame
import pygame import random
初始化游戏
pygame.init() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock()
蛇和食物初始化
snake = [(100, 100), (90, 100), (80, 100)] direction = "RIGHT" food = (random.randint(0, width//10)*10, random.randint(0, height//10)*10)
游戏循环
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"
# 移动蛇头
head = snake[0]
if direction == "UP":
new_head = (head[0], head[1] - 10)
elif direction == "DOWN":
new_head = (head[0], head[1] + 10)
elif direction == "LEFT":
new_head = (head[0] - 10, head[1])
elif direction == "RIGHT":
new_head = (head[0] + 10, head[1])
snake.insert(0, new_head)
# 判断是否吃到食物
if snake[0] == food:
food = (random.randint(0, width//10)*10, random.randint(0, height//10)*10)
else:
snake.pop()
# 绘制画面
screen.fill((0, 0, 0))
for pos in snake:
pygame.draw.rect(screen, (0, 255, 0), (pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, (255, 0, 0), (food[0], food[1], 10, 10))
pygame.display.update()
clock.tick(15)
pygame.quit()
二、免费资源推荐
-
GitHub 开源项目
- Python小游戏合集
- 直接搜索关键词如
python games,按Stars排序找高赞项目。
-
编程学习网站
-
国内教程网站
三、注意事项
- 复制代码时注意缩进(Python依赖缩进语法)。
- 安装必要依赖库(如
pygame、turtle)。 - 调试时可通过
print()或断点工具排查逻辑错误。
希望这些资源能帮到你! 🎮