【发布时间】:2021-07-19 03:24:53
【问题描述】:
我一直在研究井字游戏,获胜逻辑的一部分是我决定将获胜的条件语句(即连续三个、三个列或三个对角线)存储在常量变量中。我面临的问题是布尔 False 是我所做的所有陈述的结果。我有prints 的证明,我已插入我的程序。
代码:
# Create game cells
list = [' ' for n in range(10)]
# Coniditions for winning
O_ROW = (
(list[1] == 'O' and list[2] == 'O' and list[3] == 'O') or
(list[4] == 'O' and list[5] == 'O' and list[6] == 'O') or
(list[7] == 'O' and list[8] == 'O' and list[9] == 'O')
)
O_COL = (
(list[1] == 'O' and list[4] == 'O' and list[7] == 'O') or
(list[2] == 'O' and list[5] == 'O' and list[8] == 'O') or
(list[3] == 'O' and list[6] == 'O' and list[9] == 'O')
)
X_ROW = (
(list[1] == 'X' and list[2] == 'X' and list[3] == 'X') or
(list[4] == 'X' and list[5] == 'X' and list[6] == 'X') or
(list[7] == 'X' and list[8] == 'X' and list[9] == 'X')
)
X_COL = (
(list[1] == 'X' and list[4] == 'X' and list[7] == 'X') or
(list[2] == 'X' and list[5] == 'X' and list[8] == 'X') or
(list[3] == 'X' and list[6] == 'X' and list[9] == 'X')
)
O_DIAG = (
(list[1] == 'O' and list[5] == 'O' and list[9] == 'O') or
(list[3] == 'O' and list[5] == 'O' and list[7] == 'O')
)
X_DIAG = (
(list[1] == 'X' and list[5] == 'X' and list[9] == 'X') or
(list[3] == 'X' and list[5] == 'X' and list[7] == 'X')
)
def displayBoard():
# Printing the game board
print()
print(f'\t {list[1]} | {list[2]} | {list[3]}')
print('\t-----------')
print(f'\t {list[4]} | {list[5]} | {list[6]}')
print('\t-----------')
print(f'\t {list[7]} | {list[8]} | {list[9]}')
print()
def playBoard(pos, pl):
# Position the play in the cell and check for already-placed cells
if list[pos] != 'X' and list[pos] != 'O':
list[pos] = pl.upper()
else:
print("Already played! Try again")
# Determine winning condition or tie
if O_ROW and O_COL and O_DIAG:
print("O Wins!")
sys.exit()
elif X_ROW and X_COL and X_DIAG:
print("X Wins!")
sys.exit()
print('''Welcome to the game of Tic-Tac-Toe.
You will pick a play (X or O) and then pick from a place of 1 to 9 on
the board. Let's begin
''')
# Print for debugging
print(X_ROW)
print(X_COL)
print(X_DIAG)
print(O_ROW)
print(O_COL)
print(O_DIAG)
输出:
Welcome to the game of Tic-Tac-Toe.
You will pick a play (X or O) and then pick from a place of 1 to 9 on
the board. Let's begin
False
False
False
False
False
False
Play X or O?
他们都评估为False的逻辑有什么问题?
如果这个逻辑错误的原因是将条件语句封装成变量/常量,那么请原谅我的无知。我尝试这样做是因为代码后面的 if 语句中的文字条件语句看起来太长且难以阅读。
【问题讨论】:
-
在你开始游戏之前当然是False
-
If the reason for this logic error is encapsulating conditional statements into variables/constants- 你已经知道问题出在哪里了 :) 它们都是常量错误的,因为它们只在板为空时在启动时运行一次 -
我确实有一个主游戏循环,但我故意将其从粘贴的代码中删除,因为我认为代码已经很长了。
标签: python python-3.x variables conditional-statements tic-tac-toe