- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在创建一个管理井字游戏的程序,我正在创建一个列表列表
[['', '', ''],
['', '', ''],
['', '', '']]
为了创建游戏网格,我希望程序在找到像这样的匹配时停止
[['x', 'x', 'x'],
['', '', ''],
[ '', '', '']
例如,在这种情况下,我需要能够说在其他框中可能有任何字符,'o','x',''
如果网格是获胜网格,我希望 python 程序必须停止
最佳答案
您会如何“手动”检查?
检查第一行是否所有三个位置都是玩家的代码
if b[0][0]==code and b[0][1]==code and b[0][2]==code: return True
检查第二行
检查第三行
检查第一列是否所有三列都是玩家的代码
if b[0][0]==code and b[1][0]==code and b[2][0]==code: return True
也检查第二列和第三列
也检查第一条和第二条对角线
对于行和列很容易编写循环而不是复制粘贴代码
还有其他方法可以编写更短的代码(使用类似 all(b[i][j] == code for j in range(3))
的代码)或更快的代码(使用位而不是字符以及对所有 x
或 o
的单个整数)。
另一个“技巧”是将棋盘保持在单个数组而不是矩阵中,并使用占位符(例如“-”)来表示空方 block
board = ['-', '-', '-',
'-', '-', '-',
'-', '-', '-']
然后您可以使用正则表达式检查获胜的罢工
s = "".join(board) # change to a single string
if re.match("xxx......", s) return True # first row check
if re.match("...xxx...", s) return True # second row check
if re.match("......xxx", s) return True # third row check
if re.match("x..x..x..", s) return True # first col check
if re.match(".x..x..x.", s) return True # second col check
if re.match("..x..x..x", s) return True # third col check
我要做的是使用位:棋盘由两个数字 0...511 表示:一个数字代表 x
标记是 o
的另一个标记。标记为:
# board bits are
#
# 1 2 4
# 8 16 32
# 64 128 256
#
Xs = Os = 0 # empty board
win_codes = [1+2+4, 8+16+32, 64+128+256, # rows
1+8+64, 2+16+128, 4+32+256, # cols
1+16+256, 4+16+64] # diags
def wins(pos):
return any((pos & c) == c for c in win_codes)
鉴于位置总数也很小(512),获胜位置也可以预先计算并存储在表中
win_pos = [wins(pos) for pos in range(512)]
那么检查就很简单了
if win_pos[Xs]: ... # player X won the game
关于python - 井字棋 python 中的简单帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47616264/
我有一个模板,可以获取从外部程序生成的所有信息。我试图让这个模板更现代一点,而不是 1992 年。 用于处理表格的页面。它看起来不太好,所以我试图移除 table ,让屏幕上的所有内容都流畅。 对于文
我使用 bootstrap 井来模拟卡片。我目前有两种不同类型的卡片,“普通”卡片位于屏幕中间,“特殊”卡片位于左侧和右侧。 我正在尝试复制的模板: 问题: 1.) bootstrap 中的井似乎不想
我有一个井 div,我想在 Angular 落附上一个小文本/图像,如此处所示 ( http://draw.to/D46BqsC )...并让该元素相对于井放置,以便它发生变化位置和井一样。什么是最好
我是一名优秀的程序员,十分优秀!