T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 11 天:综合实战:21 点 Blackjack

这是「Python 100 天」系列第 11 天的学习笔记:综合实战:21 点 Blackjack。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

第一个 Capstone(综合项目):21 点。README 只写了一条——重构与调用过程(procedures)。也就是说,今天不学新语法,练的是"把 Day 1–10 的零件组装成一个完整程序"。

一、规则先写清楚

  • 牌面:A 记 11 分(可降为 1),J/Q/K 记 10 分;
  • 开局各发两张,玩家可以看到电脑的第一张;
  • 玩家可以一直要牌(hit),超过 21 点即爆牌输;
  • 玩家停牌(pass)后比大小,点数高者胜,相同为平局;
  • 黑杰克(开局 21 点)大于普通 21 点——这份代码把两者都当 21 处理,属于简化。

先写规则再写代码,是这类项目的正确顺序。规则没想清楚,代码一定返工。

二、嵌套函数与闭包

1
2
3
def blackjack_game():
def start_deal(cards):
return random.choice(cards)

start_deal 定义在 blackjack_game 内部,只有外层能调用。它还能直接读到外层的 player_cards、cpu_cards——这种"内层函数引用外层变量"的结构叫闭包。好处是把一个项目的所有逻辑收在一个作用域里;坏处是外层变量变成隐式的全局状态,调试时很难追踪(Day 12 就专门讲作用域)。

三、sum() 与列表求和

sum([11, 10, 8]) → 29。求点数是本项目最高频的操作。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# ============================================================
# day11/main.py —— 21 点(Blackjack)
# 作用:你和电脑各发两张牌,你可以选择继续要牌(hit)或停手(pass),
# 比谁的点数更接近 21 且不超过 21。
# 知识点:嵌套函数、闭包(内层函数直接用外层变量)、sum()、list.index()、
# append()、递归重开一局
# 运行:python main.py(clear 来自 Replit,本地运行见 Day07 说明)
# ============================================================

from replit import clear
from art import logo
import random


# 外层函数:一局游戏的“容器”。里面定义的 player_cards、cpu_cards、cards
# 都是它的局部变量;内层函数不需要参数就能读到它们,这叫闭包。
def blackjack_game():

# 发一张牌。
# 参数 cards:牌堆列表,例如 [11, 2, 3, …, 10]
# 返回值:随机抽出的那一张牌(int,11 代表 A,10 代表 J/Q/K)
# random.choice(seq) 返回序列里随机一个元素,可能重复抽到同一张——
# 这里没做“抽过就移除”,所以是“有放回抽取”,严格说不算真实牌堆。
def start_deal(cards):
shuffled = random.choice(cards)
return shuffled

# 判断“玩家输”的两种情况。
# 参数 player、cpu:两边的牌列表
# 返回值:True 表示玩家输;没有 else 分支,所以其余情况返回 None(假值)
def player_loss(player, cpu):
# sum(iterable):内置函数,参数是数字序列,返回元素之和。
if sum(player) != 21 and sum(cpu) == 21:
return True
elif sum(player) == 21 and sum(cpu) == 21:
return True

# 摊牌、结算、问要不要再来一局。
# 无参数(直接读外层的 player_cards / cpu_cards),无返回值。
def done_playing():
player_sum = sum(player_cards)
cpu_sum = sum(cpu_cards)
print(f"Your hand is: {player_cards}, a total of {player_sum}.")
print(f"The computer's hand is {cpu_cards}, a total of {cpu_sum}.")
# 判断顺序很关键:先判“爆牌”,再判 21 点,最后比大小。
# 顺序错了就会出现“电脑 25 点却因为比你大而赢”这种荒唐结果。
if sum(cpu_cards) > 21:
print("The computer got a bust, you win!")
elif player_loss(player_cards, cpu_cards):
print("You lose.")
elif sum(player_cards) == 21 and sum(cpu_cards) != 21:
print("You win!")
elif sum(player_cards) > 21:
print("It's a bust, you lose.")
elif player_sum == cpu_sum:
print("It's a draw.")
elif player_sum > cpu_sum:
print("You win!")
else:
print("You lose.")
play_again = input("Do you want to play again? Type 'y' or 'n': ")
if play_again == 'y':
clear()
# 递归:再调用一次自己,等于“重开一局”。
# 缺点和 Day10 一样——旧的一局还压在调用栈上,玩久了栈会越来越深。
blackjack_game()
else:
if play_again == 'n':
print("Goodbye.")

# “继续要牌”的主流程:发一张给玩家、一张给电脑,算点数,再问要不要接着要。
def keep_playing():
shuffled = start_deal(cards)
player_cards.append(shuffled)
# append(x):列表方法,把 x 加到末尾,原地修改,返回 None。
cpu_cards.append(start_deal(cards))
player_sum = sum(player_cards)
cpu_sum = sum(cpu_cards)
# A 的特殊规则:11 点如果让总数超过 21,就自动当 1 点用。
# 11 in player_cards 判断列表里有没有 11;
# list.index(x):列表方法,返回 x 第一次出现的下标(找不到抛 ValueError)。
if 11 in player_cards and player_sum >= 21:
ace = player_cards.index(11)
player_cards[ace] = 1
player_sum = sum(player_cards)
print(f"Your hand is: {player_cards}, a total of {player_sum}.")
print(f"The computer's hand is {cpu_cards}, a total of {cpu_sum}.")
if player_sum > 21:
print("It's a bust, you lose.")
play_again = input("Do you want to play again? Type 'y' or 'n': ")
if play_again == 'y':
clear()
blackjack_game()
elif play_again == 'n':
print("Thanks for playing. Goodbye.")
if player_sum <= 21:
hit = input("Type 'y' to get another card, type 'n' to pass: ")
if hit == 'y':
# 递归:再要一张,就是再走一遍 keep_playing。
keep_playing()
elif hit == 'n':
done_playing()

print(logo)
# 牌堆:A 记 11,J/Q/K 都记 10,2–10 按面值。
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# 两边的牌面列表,一开始都是空的。
player_cards = []
cpu_cards = []
# 开局各发两张(电脑只发一张,另一张“暗着”)。
player_cards.append(start_deal(cards))
player_cards.append(start_deal(cards))
cpu_cards.append(start_deal(cards))
print(f"Your cards: {player_cards}")
print(f"The computer's first card: {cpu_cards}")
hit = input("Type 'y' to get another card, type 'n' to pass: ")
if hit == 'n':
done_playing()
elif hit == 'y':
keep_playing()

# 入口:定义完直接跑一局。
blackjack_game()

代码走读

  1. cards = [11, 2, 3, ..., 10, 10, 10, 10]:13 张"牌面值",四张 10 代表 10/J/Q/K。注意这里没有花色,也没有"牌堆耗尽"的概念,random.choice 每次都从完整列表取,等于有放回抽样(同一张牌可能重复出现)。
  2. player_cards、cpu_cards:两个列表就是两方的牌。
  3. start_deal(cards) 只是 random.choice(cards) 的包装——抽象层次有点多余,但体现了"发牌"这个业务动作。
  4. keep_playing():要一张牌,更新点数;关键的一段是 A 的处理:
1
2
3
if 11 in player_cards and player_sum >= 21:
ace = player_cards.index(11)
player_cards[ace] = 1

手里有 A 且点数达到/超过 21,就把第一个 A 从 11 改成 1(只改一张,逻辑简化)。

  1. done_playing():结算。判断顺序很重要——先看电脑爆牌(玩家直接赢),再看玩家是否 21 点,再看玩家爆牌,最后比大小。
  2. player_loss(player, cpu):专门处理"电脑 21 点"的情况,但两个分支都返回 True,等价于 return sum(cpu) == 21,而且不满足时返回 None(假值)。这是可读性上的坏味道。
  3. 三个函数互相调用,且都用递归实现"再来一局"。

结构上的问题(值得当成重构练习)

  • 递归三处:blackjack_game() 在 done_playing、keep_playing 里各调一次。玩 20 局就嵌 20 层。
  • 重复代码:爆牌后的"是否再来一局"块写了两遍。
  • 隐式全局状态:player_cards 是外层变量,任何内层函数都能改,出 bug 时无法定位是谁改的。

重构方向:把"一局"写成 play_round() 返回结果,外层 while True: 负责重开;把"问是否继续"抽成 ask_play_again();把结算逻辑改成纯函数 judge(player, cpu) -> "win"/"lose"/"draw"。

运行示例

1
2
3
4
5
Your cards: [10, 7]
The computer's first card: [9]
Type 'y' to get another card, type 'n' to pass: y
Your hand is: [10, 7, 5], a total of 22.
It's a bust, you lose.

易错点

  1. A 的处理顺序:先求和再判断,求和后才发现 A 要降级,需要重新求和。
  2. sum() 用在字符串上:牌如果存成 "A",sum 会报错。
  3. 结算顺序:先判"玩家爆牌"再判"电脑爆牌",会把玩家的胜利吞掉。
  4. 递归无出口:play_again 输入 y/n 以外的值,程序直接结束且不提示。

动手改

  • 用真正的 52 张牌(含花色)实现,发过的不再出现。
  • 把 A 的处理改成"自动选最优":sum 超过 21 就把 11 逐个降为 1。
  • 按上面的重构方向改写,让主函数不超过 15 行。

源文件逐个讲解

3 个文件:main.py(87 行)、art.py(11 行)、README.md(6 行)。这是前 14 天里逻辑最绕的一天。

art.py(11 行)

一幅 BLACKJACK 的 ASCII 字,变量名 logo。和前几天一样,纯素材。

main.py(87 行)

结构:一个外层函数 blackjack_game(),里面嵌套 4 个内层函数,最后在模块级调用一次。

1
2
3
4
5
6
7
8
9
from replit import clear
from art import logo
import random

def blackjack_game():

def start_deal(cards):
shuffled = random.choice(cards)
return shuffled

嵌套函数(inner function):start_deal 定义在 blackjack_game 内部,只能在这个函数里用。这样做的目的是「不污染全局命名空间」——start_deal 只服务于这一局游戏。变量名 shuffled 其实是「抽到的一张牌」,名字不准(random.choice 是有放回抽样,不是洗牌)。

1
2
3
4
5
  def player_loss(player, cpu):
if sum(player) != 21 and sum(cpu) == 21:
return True
elif sum(player) == 21 and sum(cpu) == 21:
return True

这个函数只处理「玩家输」的两种情况,其它情况返回 None(隐式)。所以调用处必须写成 elif player_loss(...)——None 是假值,能当 False 用。

但第二种情况判错了:双方都 21 点,标准规则是平局(push),这里返回 True(玩家输)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  def done_playing():
player_sum = sum(player_cards)
cpu_sum = sum(cpu_cards)
print(f"Your hand is: {player_cards}, a total of {player_sum}.")
print(f"The computer's hand is {cpu_cards}, a total of {cpu_sum}.")
if sum(cpu_cards) > 21:
print("The computer got a bust, you win!")
elif player_loss(player_cards, cpu_cards):
print("You lose.")
elif sum(player_cards) == 21 and sum(cpu_cards) != 21:
print("You win!")
elif sum(player_cards) > 21:
print("It's a bust, you lose.")
elif player_sum == cpu_sum:
print("It's a draw.")
elif player_sum > cpu_sum:
print("You win!")
else:
print("You lose.")

结算顺序是有讲究的:

  1. 庄家爆牌 → 玩家赢(这时玩家就算也爆了也算赢,因为先判);
  2. player_loss → 玩家输;
  3. 玩家 21 点且庄家不是 → 赢;
  4. 玩家爆牌 → 输;
  5. 同分 → 平;
  6. 比大小。

问题在顺序 1 和 4:玩家爆牌(22 点)、庄家也爆牌(23 点),会先命中「庄家爆牌,你赢」——双方都爆,实际规则是玩家输。

done_playing 不接收参数,直接读外层的 player_cards、cpu_cards——这是闭包(closure)的用法,见 Day 12 的作用域。

1
2
3
4
5
6
7
8
9
10
  def keep_playing():
shuffled = start_deal(cards)
player_cards.append(shuffled)
cpu_cards.append(start_deal(cards))
player_sum = sum(player_cards)
cpu_sum = sum(cpu_cards)
if 11 in player_cards and player_sum >= 21:
ace = player_cards.index(11)
player_cards[ace] = 1
player_sum = sum(player_cards)

A 的处理只做了一半:

  • 只在 player_cards 里找 11(庄家的 A 永远算 11,庄家超过 21 就爆);
  • player_cards.index(11) 只处理第一张 A,有两张 A 时另一张还是 11;
  • 条件 player_sum >= 21 应该只在爆牌(>21)时才降 A,== 21 时降了反而变小。
1
2
3
4
5
6
7
8
9
10
    if player_sum > 21:
print("It's a bust, you lose.")
play_again = input("Do you want to play again? Type 'y' or 'n': ")
...
if player_sum <= 21:
hit = input("Type 'y' to get another card, type 'n' to pass: ")
if hit == 'y':
keep_playing()
elif hit == 'n':
done_playing()

注意这里是两个独立的 if,不是 if/else。player_sum > 21 时第一个 if 里可能已经递归开了新局,回到这里还会继续执行第二个 if(因为 player_sum 没变),于是又问一次「要不要牌」——这是递归 + 非 else 分支造成的双问。

递归实现「再抽一张」:每抽一张就多一层栈。抽 10 张就 10 层,能跑但不好调试。

开局部分:

1
2
3
4
5
6
7
  print(logo)
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_cards = []
cpu_cards = []
player_cards.append(start_deal(cards))
player_cards.append(start_deal(cards))
cpu_cards.append(start_deal(cards))

cards 是牌面值列表:11 代表 A,10 出现四次代表 10/J/Q/K。没有花色、没有张数限制——random.choice 有放回,理论上能连抽 4 张 A(真实牌局只有 4 张)。

庄家只发一张牌(另一张暗着),这是正确的 21 点规则。

这份代码的问题

  1. 双方 21 点判成玩家输(player_loss 第二分支)。
  2. 双方都爆牌判成玩家赢(done_playing 第一条)。
  3. A 的处理只对玩家、只处理一张、条件写错。
  4. keep_playing 里两个独立 if 导致爆牌后还会再问一次。
  5. 庄家不补牌:真实规则是庄家 17 点以下必须继续要牌,这里庄家永远只有开局那一张(后面 keep_playing 里会 cpu_cards.append,但那是跟着玩家抽的,不是按规则)。
  6. 递归实现游戏循环,局数一多栈就深。
  7. from replit import clear 本地跑不了。

README.md(6 行)

标题 Day 11 - The Blackjack Capstone Project,知识点只有一行 Refactoring and calling procedures。

「Refactoring」指的就是把一段平铺的代码拆成 start_deal / player_loss / done_playing / keep_playing 四个函数——这一天不教新语法,只教「怎么把 100 行揉成一个能读的结构」。

文件间关系

main.py ← art.py。四个内层函数共享外层的 cards、player_cards、cpu_cards 三个变量,这就是为什么它们必须嵌套——放在模块级就得靠全局变量或传参。

微信收款码 微信
支付宝收款码 支付宝
评论