我还是python新手,所以我只是想知道是否可以编写如下语句:
def win_check(board, mark):
for mark in board:
if (mark == board [7] and mark == board [8] and mark == board [9]) or
(mark == board [4] and mark == board [5] and mark == board [6]) or
(mark == board [1] and mark == board [2] and mark == board [3]):
print("you won 1")
elif (mark == board [7] and mark == board [4] and mark == board [1]) or
(mark == board [8] and mark == board [5] and mark == board [2]) or
(mark == board [9] and mark == board [6] and mark == board [3]):
print("you won 2")
elif (mark == board [7] and mark == board [5] and mark == board [3]) or
(mark == board [9] and mark == board [5] and mark == board [1]) or
(mark == board [1] and mark == board [2] and mark == board [3]):
print("you won 3")
else:
print ("game tied")
这是井字游戏的一项功能。当我尝试运行该功能时,它提示我错误
File "<ipython-input-13-94777e972072>", line 4
if (mark == board [7] and mark == board [8] and mark == board [9]) or
^
SyntaxError: invalid syntax
我不太清楚这是什么意思和需要什么,任何人都可以在这方面帮助我并在方法上帮助我吗?
答案 0 :(得分:0)
您不能在语句前加结尾,不要在其末尾添加“ \”。 正确的方法是:
for mark in board:
if (mark == board[7] and mark == board[8] and mark == board[9]) or\
(mark == board[4] and mark == board[5] and mark == board[6]) or\
(mark == board[1] and mark == board[2] and mark == board[3]):
print("you won 1") ...
以此类推。
我还删除了分度板之前的间距,因此它应该是board [i]而不是board [i]
祝你好运!
答案 1 :(得分:0)
您的问题是if语句需要为连续的一行。或python将下一行视为新代码。您需要反斜杠以逃避行尾并继续其下的行。
for mark in board:
if (mark == board[7] and mark == board[8] and mark == board[9]) \
or (mark == board[4] and mark == board[5] and mark == board[6]) \
or (mark == board[1] and mark == board[2] and mark == board[3]):
print("you won 1")
elif (mark == board[7] and mark == board[4] and mark == board[1]) \
or (mark == board[8] and mark == board[5] and mark == board[2]) \
or (mark == board[9] and mark == board[6] and mark == board[3]):
print("you won 2")
elif (mark == board [7] and mark == board[5] and mark == board[3]) \
or (mark == board[9] and mark == board[5] and mark == board[1]) \
or (mark == board[1] and mark == board[2] and mark == board[3]):
print("you won 3")
else:
print ("game tied")
答案 2 :(得分:0)
只需在整个if表达式周围添加一个额外的括号...
if (
((a == b) and (b == c) and (c == d))
or ((e == f) and (f == g) and (g == h))
or ...
):
# do something here
print('Winner')
也就是说,这可能完全是您执行实际尝试的代码的错误方法。更为惯用的方法可能如下。请记住,您只需要检查当前玩家移动后是否真的赢了。
def detect_winner(win_value: str = 'o') -> bool:
"""Determines if current player won.
Args:
win_value: the value to check for a win; value of current player
Returns:
True if winner is detected otherwise False
"""
# Anything within a parenthesis can allow for newlines and ignore
# generally considered "good" and "pythonic" whitespacing
row_win = (
all(cell == win_value for cell in mark[1:3])
or all(cell == win_value for cell in mark[4:6])
or all(cell == win_value for cell in mark[7:9])
)
col_win = (...)
cross_win = (...)
possible_wins = (row_win, col_win, cross_win)
found_a_winner = True if any(possible_wins) else False
return found_a_winner