Python新手入门:5个经典小游戏源码(贪吃蛇/猜数字)
专为Python初学者设计的5个经典小游戏完整源码与核心逻辑拆解,涵盖猜数字、石头剪刀布、单词消消乐、井字棋与经典贪吃蛇。不依赖复杂第三方库,深入讲解控制流、数据结构、坐标系及事件循环。
对于刚接触编程的新手来说,脱离枯燥的语法练习题、直接编写能够即时交互的小游戏,是建立编程直觉和巩固基础知识最高效的途径。本文精选了 5 个梯度递进的经典 Python 小游戏:从最基础的猜数字与石头剪刀布,到涉及容器与字符运算的单词消消乐,再到具备状态判定矩阵的井字棋,最后到依赖标准库图形渲染与事件循环的经典贪吃蛇。所有示例均基于 Python 官方标准库编写,无需额外安装繁琐的第三方依赖,开箱即用,代码规范且配有详尽的逻辑拆解与避坑提醒。
一、游戏 1:猜数字游戏(循环、分支与输入防御)
猜数字游戏是编程入门的“试金石”。游戏规则非常直观:程序随机生成一个 1 到 100 之间的整数,玩家有 7 次机会猜测;每次输入后,程序会提示“猜大了”或“猜小了”,直到猜中或次数耗尽。
这个小项目看似简单,但它涵盖了每一个 Python 程序都会用到的四大核心要素:模块导入、标准输入输出、条件分支结构(if-elif-else)以及循环终止条件。
1. 完整游戏源码
import random
def guess_number_game():
target = random.randint(1, 100)
max_attempts = 7
attempts = 0
print("=== 猜数字小游戏 (1-100) ===")
print(f"目标数字已生成,你一共有 {max_attempts} 次机会。\n")
while attempts < max_attempts:
user_input = input(f"第 {attempts + 1} 次尝试,请输入你猜的数字: ").strip()
# 防御性校验:避免非数字输入导致程序直接抛错崩溃
try:
guess = int(user_input)
except ValueError:
print("输入无效!请输入纯正整数。\n")
continue
attempts += 1
if guess < target:
print("太小了!往大一点猜。\n")
elif guess > target:
print("太大了!往小一点猜。\n")
else:
print(f"恭喜你!在第 {attempts} 次成功猜中数字 {target}!")
return
print(f"很遗憾,7 次机会已用尽。正确的数字是: {target}")
if __name__ == "__main__":
guess_number_game()
2. 新手容易踩的两个坑
- 误区一:直接对
input()进行比较。新手最常犯的错误是写出if input() > target:。必须牢记,Python 3 中input()始终返回字符串(str),字符串与整数(int)直接比较在 Python 3 中会触发TypeError。必须通过int()显式转换。 - 误区二:计数器递增位置放错。如果把
attempts += 1放在try-except之前,当用户输入字母时,不仅无法猜测,还会平白浪费一次宝贵的机会。只有在验证用户输入为合法整数后递增计数,交互才符合常理。
二、游戏 2:石头剪刀布(规则映射与状态消除)
很多初学者在实现石头剪刀布时,会机械地写出多达 9 层的嵌套 if-elif,导致代码臃肿脆弱。优秀的代码组织方式应当是“数据驱动”:利用 Python 字典(dict)定义克制关系,通过一行查表逻辑直接判定胜负。
1. 完整游戏源码
import random
def rps_game():
choices = ["石头", "剪刀", "布"]
# 字典明确定义克制关系:Key 战胜 Value
win_rules = {
"石头": "剪刀",
"剪刀": "布",
"布": "石头"
}
user_score = 0
bot_score = 0
print("=== 石头剪刀布人机对决 ===")
print("输入 '石头'、'剪刀'、'布' 出拳,输入 'q' 可退出对局。\n")
while True:
user_choice = input("请出拳: ").strip()
if user_choice.lower() == 'q':
print(f"\n对局结束!最终总战绩: 玩家 {user_score} 胜 | 电脑 {bot_score} 胜")
break
if user_choice not in choices:
print("输入无效!只能输入 石头、剪刀 或 布。\n")
continue
bot_choice = random.choice(choices)
print(f"电脑出: {bot_choice}")
if user_choice == bot_choice:
print("平局!双方旗鼓相当。\n")
elif win_rules[user_choice] == bot_choice:
user_score += 1
print(f"你赢了这一局!当前比分 -> 玩家 {user_score} : {bot_score} 电脑\n")
else:
bot_score += 1
print(f"电脑赢了这一局!当前比分 -> 玩家 {user_score} : {bot_score} 电脑\n")
if __name__ == "__main__":
rps_game()
代码设计亮点:通过 win_rules[user_choice] == bot_choice 这一行表达式,瞬间替代了 (user == '石头' and bot == '剪刀') or ... 冗长且极易写错的复合布尔判断。这是初学者由“语法拼凑”迈向“优雅设计”的关键一步。
三、游戏 3:单词猜谜 Hangman(字符串掩码与集合操作)
单词猜谜考验玩家在有限步数内猜出由英文字母组成的神秘单词。程序在终端展示与单词等长的下划线 _ _ _ _,玩家每次猜一个字母,若命中则替换对应位置的下划线,否则扣除一点生命值。
该项目核心训练的是字符串与列表之间的转换、列表推导式以及 set 集合的高性能去重。
1. 完整游戏源码
import random
def hangman_game():
word_bank = ["python", "variable", "function", "condition", "loop"]
target_word = random.choice(word_bank)
guessed_letters = set()
lives = 6
print("=== 猜单词小游戏 (Hangman) ===")
print(f"单词已选定,初始拥有 {lives} 次生命值。")
while lives > 0:
# 列表推导式:若字母已被猜出则显示明文,否则显示占位下划线
display_board = [char if char in guessed_letters else "_" for char in target_word]
current_view = " ".join(display_board)
print(f"\n当前进度: {current_view}")
print(f"剩余生命: {lives} | 历史猜测: {', '.join(sorted(guessed_letters)) if guessed_letters else '无'}")
# 胜负判定:若无下划线,说明所有字母已拼出
if "_" not in display_board:
print(f"恭喜胜利!你成功解出了完整单词: {target_word}")
return
guess = input("请输入猜测的单个字母: ").strip().lower()
# 合法性校验
if len(guess) != 1 or not guess.isalpha():
print("格式有误!每次只能输入 1 个英文字母。")
continue
if guess in guessed_letters:
print(f"字母 '{guess}' 已经猜过了,请输入新字母。")
continue
guessed_letters.add(guess)
if guess in target_word:
print(f"命中!单词中包含字母 '{guess}'。")
else:
lives -= 1
print(f"遗憾!单词中没有字母 '{guess}'。扣除 1 点生命值!")
print(f"\n挑战失败!生命值耗尽,正确的单词是: {target_word}")
if __name__ == "__main__":
hangman_game()
四、游戏 4:井字棋对战(二维列表与矩阵胜负检测)
井字棋(Tic-Tac-Toe)是初学者从一维线性逻辑迈向二维平面几何算法的最佳实践。通过一个 3x3 的嵌套列表构建棋盘,两名玩家轮流输入行列坐标落子。
该程序的核心是矩阵坐标映射与8 种连线获胜情况的判定算法(3 行、3 列、2 条对角线)。
1. 完整游戏源码
def print_board(board):
print("\n 0 1 2")
for r_idx, row in enumerate(board):
print(f"{r_idx} " + " | ".join(row))
if r_idx < 2:
print(" ---+---+---")
print()
def check_win(board, player):
# 1. 检查行
for row in board:
if all(cell == player for cell in row):
return True
# 2. 检查列
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
# 3. 检查主副两条对角线
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
def tictactoe_game():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
total_moves = 0
print("=== 井字棋双人对弈 (3x3) ===")
print("玩家 X 先手,玩家 O 后手。输入格式为: 行 列 (例如: 1 2)")
while total_moves < 9:
print_board(board)
user_input = input(f"轮到玩家 [{current_player}] 落子 (行 列): ").strip()
parts = user_input.split()
if len(parts) != 2:
print("输入格式错误!请用空格隔开行坐标与列坐标。")
continue
try:
r, c = int(parts[0]), int(parts[1])
except ValueError:
print("坐标必须是 0 到 2 之间的纯数字!")
continue
if not (0 <= r <= 2 and 0 <= c <= 2):
print("坐标越界!行列范围只能在 0、1、2 之中。")
continue
if board[r][c] != " ":
print("该位置已有棋子,无法重复落子!")
continue
board[r][c] = current_player
total_moves += 1
if check_win(board, current_player):
print_board(board)
print(f"恭喜!玩家 [{current_player}] 达成连线,赢得本局胜利!")
return
# 轮换玩家
current_player = "O" if current_player == "X" else "X"
print_board(board)
print("棋盘已下满,平局收场!")
if __name__ == "__main__":
tictactoe_game()
五、游戏 5:经典贪吃蛇(Turtle 图形渲染与帧循环)
很多新手以为写带窗口的图形游戏必须安装庞大的 Pygame。其实,Python 内置的 turtle(海龟绘图)模块已经足以构建一个流畅、轻巧且具备完整事件响应的经典贪吃蛇!
编写贪吃蛇小游戏的核心难点不在于画图,而在于运动拓扑:蛇身是由多个方块构成的链条。每次向前移动时,第 n 节身体移动到第 n-1 节原来的位置,只有蛇头才根据方向移动。通过反向遍历身体列表,可以极其优雅地实现贪吃蛇的蜿蜒爬行。
1. 完整游戏源码
import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
# 1. 窗口初始化
wn = turtle.Screen()
wn.title("经典贪吃蛇 - Python标准库实战")
wn.bgcolor("#F7F4ED")
wn.setup(width=600, height=600)
wn.tracer(0) # 关闭自动刷新,改由主循环手动 update() 以保持平滑帧率
# 2. 蛇头创建
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("#464B48")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 3. 随机食物创建
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("#8A9478")
food.penup()
food.goto(0, 100)
segments = []
# 4. 记分板文本
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.shape("square")
score_pen.color("#464B48")
score_pen.penup()
score_pen.hideturtle()
score_pen.goto(0, 260)
score_pen.write("得分: 0 最高分: 0", align="center", font=("PingFang SC", 15, "normal"))
# 5. 键盘转向回调函数 (禁止180度直接掉头自撞)
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
step = 20
if head.direction == "up":
head.sety(head.ycor() + step)
elif head.direction == "down":
head.sety(head.ycor() - step)
elif head.direction == "left":
head.setx(head.xcor() - step)
elif head.direction == "right":
head.setx(head.xcor() + step)
# 6. 按键监听注册
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
# 7. 游戏主循环
while True:
wn.update()
# 边界撞墙检测 (窗口大小为 600x600,边界为 ±290)
if abs(head.xcor()) > 290 or abs(head.ycor()) > 290:
time.sleep(0.8)
head.goto(0, 0)
head.direction = "stop"
# 隐藏并清空现存蛇身
for seg in segments:
seg.goto(1000, 1000)
segments.clear()
score = 0
score_pen.clear()
score_pen.write(f"得分: {score} 最高分: {high_score}", align="center", font=("PingFang SC", 15, "normal"))
# 吃食物检测
if head.distance(food) < 20:
# 食物重置到网格点上 (步长20对齐)
food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)
# 增加一节新身体
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("#6B705C")
new_segment.penup()
segments.append(new_segment)
score += 10
if score > high_score:
high_score = score
score_pen.clear()
score_pen.write(f"得分: {score} 最高分: {high_score}", align="center", font=("PingFang SC", 15, "normal"))
# 蛇身随动:逆序向前一节坐标迭代
for i in range(len(segments) - 1, 0, -1):
prev_x = segments[i - 1].xcor()
prev_y = segments[i - 1].ycor()
segments[i].goto(prev_x, prev_y)
# 第一节跟随蛇头
if len(segments) > 0:
segments[0].goto(head.xcor(), head.ycor())
# 蛇头推进
move()
# 自身碰撞检测
for segment in segments:
if segment.distance(head) < 20:
time.sleep(0.8)
head.goto(0, 0)
head.direction = "stop"
for seg in segments:
seg.goto(1000, 1000)
segments.clear()
score = 0
score_pen.clear()
score_pen.write(f"得分: {score} 最高分: {high_score}", align="center", font=("PingFang SC", 15, "normal"))
time.sleep(delay)
六、5 款小游戏掌握要点与常见问题排查
完成上述 5 个小游戏的编写后,建议读者回顾和对照下表,检验自己是否对每种技术结构有了坚实的理解:
建议新手在完整运行一遍上述 5 个游戏源码后,尝试做一些小改造来巩固知识,例如:给猜数字增加双人轮流猜测模式;给井字棋增加简单的电脑随机落子逻辑;或者给贪吃蛇增加吃到特定金苹果加速的效果。通过对真实可玩的游戏代码不断调试与演进,你会发现自己对 Python 语法的理解将上升到一个全新的高度。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









