Python Bingo卡片游戏的Bingo判定逻辑错误如何修复
Bingo卡片游戏判定逻辑修复方案
原有代码的错误原因
- 条件表达式逻辑错误:
(row_zeros[i] or col_zeros[i]) == 5的写法不符合Python语法规则,该表达式会先计算row_zeros[i] or col_zeros[i]的布尔值(非0值为True,0为False),再和5比较,永远无法得到True的结果 - 提前终止检查:for循环第一次执行(i=0)时就会触发return逻辑,根本不会检查第1到4行/列的匹配情况
- 对角线判断冗余:对角线状态不需要放在for循环中重复执行5次,全局判断一次即可
- 结果无输出:
called_value返回的判定结果没有被打印,用户看不到最终的Bingo/未Bingo提示
修复后的完整代码
import random import numpy as np def bingo_card(): test1=np.array(random.sample(range(1,16),5)) test2=np.array(random.sample(range(16,31),5)) test3=np.array(random.sample(range(31,46),5)) test4=np.array(random.sample(range(46,61),5)) test5=np.array(random.sample(range(61,76),5)) test= np.concatenate((test1,test2,test3,test4,test5)) test= test.reshape(5,5) test[2,2]=0 bingo_card.test = test print("Your Card") print("B", test[0]) print("I", test[1]) print("N", test[2]) print("G", test[3]) print("O", test[4]) def called_value(): checked_card = bingo_card.test while True: called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower() if called_num != "s": number_check = int(called_num) checked_card = np.where(checked_card==number_check,0,checked_card) print("Your Card") print("B", checked_card[0]) print("I", checked_card[1]) print("N", checked_card[2]) print("G", checked_card[3]) print("O", checked_card[4]) elif called_num == "s": print("Your Card") print("B", checked_card[0]) print("I", checked_card[1]) print("N", checked_card[2]) print("G", checked_card[3]) print("O", checked_card[4]) row_zeros = np.count_nonzero(checked_card == 0, axis=1) col_zeros = np.count_nonzero(checked_card == 0, axis=0) diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0) diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0) # 修正后的判定逻辑 if 5 in row_zeros or 5 in col_zeros or diagonal_zeros ==5 or diagonal1_zeros ==5: return "Bingo!" else: return "Not Bingo" def solo(): bingo_card() res = called_value() print(res) solo()
核心修改说明
- 替换了原有的for循环判定逻辑,直接用
5 in row_zeros判断是否存在整行被标记的情况,同理判断整列,逻辑更简洁也不会漏检 - 对角线判定直接放在全局条件里,不需要循环执行
- 移除了原代码中
BINGO= print("Your Card")的无意义赋值,print函数返回值为None,赋值没有实际作用 - 在solo函数中增加了判定结果的打印,用户可以直接看到最终判定结果
内容的提问来源于stack exchange,提问作者Ben Fitzgerald
相关产品推荐
相关产品推荐

