以下是一些常用的 **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() --- ### 二、免费资源推荐 1. **GitHub 开源项目** - [Python小游戏合集](https://github.com/search?q=python+games) - 直接搜索关键词如 `python games`,按 `Stars` 排序找高赞项目。 2. **编程学习网站** - [GeeksforGeeks - Python游戏开发](https://www.geeksforgeeks.org/python-game-development/) - [Codecademy 免费课程](https://www.codecademy.com/catalog/language/python) 3. **国内教程网站** - [菜鸟教程 - Python游戏开发](https://www.runoob.com/python/python-examples.html) - [CSDN Python小游戏专栏](https://blog.csdn.net/nav/python) --- ### 三、注意事项 1. 复制代码时注意**缩进**(Python依赖缩进语法)。 2. 安装必要依赖库(如 `pygame`、`turtle`)。 3. 调试时可通过 `print()` 或断点工具排查逻辑错误。 希望这些资源能帮到你! 🎮