- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
所以,我试图用 python 制作一个基本的 Tic-Tac-Toe 游戏,我创建了一个运行良好的游戏,但我的代码不太好,因为它有很多代码用于检查列表索引(游戏的获胜者),这有点困扰我。那么,如何避免使用左索引来检查游戏的获胜者?
我的代码:
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def show_board():# for showing the tic-tac-toe board
print(' | ' + str(board[0]) + ' | ' +
str(board[1]) + ' | ' + str(board[2]) + ' | ')
print(' | ' + str(board[3]) + ' | ' +
str(board[4]) + ' | ' + str(board[5]) + ' | ')
print(' | ' + str(board[6]) + ' | ' +
str(board[7]) + ' | ' + str(board[8]) + ' | ')
def main():
one = 1
flag = 1
show_board()
while one == 1:
if flag == 1:
x_o = 'X'
if flag == 2:
x_o = 'O'
pos = int(input('Player "' + x_o + '" Turn: '))
if x_o == 'o':
x_o = 'O'
if x_o == 'x':
x_o = 'X'
if board[pos - 1] == 'O' or board[pos - 1] == 'O':
print('That Place Is Already Filled By Player "0"')
if board[pos - 1] == 'X' or board[pos - 1] == 'X':
print('That Place Is Already Filled By Player "X"')
else:
try:
board[pos - 1] = x_o
except IndexError:
print('Type Numbers Between Only 1 And 9')
if flag == 1:
flag = 2
elif flag == 2:
flag = 1
show_board()
# Checking The Winner Of The Game
# for horizontal X
if board[0] == board[1] == board[2] == 'X':
one = 2
print('The Winner Is Player "X"!')
elif board[3] == board[4] == board[5] == 'X':
one = 2
print('The Winner Is Player "X"!')
elif board[6] == board[7] == board[8] == 'X':
one = 2
print('The Winner Is Player "X"!')
# for Daigonal X
elif board[0] == board[4] == board[8] == 'X':
one = 2
print('The Winner Is Player "X"!')
elif board[2] == board[4] == board[6] == 'X':
one = 2
print('The Winner Is Player "X"!')
# for Vertical X
elif board[1] == board[4] == board[7] == 'X':
one = 2
print('The Winner Is Player "X"!')
elif board[2] == board[5] == board[8] == 'X':
one = 2
print('The Winner Is Player "X"!')
elif board[0] == board[3] == board[6] == 'X':
one = 2
print('The Winner Is Player "X"!')
# for horizontal O
elif board[0] == board[1] == board[2] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[3] == board[4] == board[5] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[6] == board[7] == board[8] == 'O':
one = 2
print('The Winner Is Player "O"!')
# for Diagonal O
elif board[0] == board[4] == board[8] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[2] == board[4] == board[6] == 'O':
one = 2
print('The Winner Is Player "O"!')
# for Vertical 0
elif board[1] == board[4] == board[7] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[2] == board[5] == board[8] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[0] == board[3] == board[6] == 'O':
one = 2
print('The Winner Is Player "O"!')
elif board[0] != ' ' and board[1] != ' ' and board[2] != ' ' and board[3] != ' ' and board[4] != ' ' and board[5] != ' ' and board[6] != ' ' and board[7] != ' ' and board[8] != ' ':
print('The Match Is A Tie!')
one = 2
main()
因此,如您所见,我使用了很多 if 语句来检查游戏的获胜者。我怎样才能避免这种情况并在更少的行中做到这一点。
最佳答案
您可以用一些循环替换它们,例如:
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def show_board():# for showing the tic-tac-toe board
print(' | ' + str(board[0]) + ' | ' +
str(board[1]) + ' | ' + str(board[2]) + ' | ')
print(' | ' + str(board[3]) + ' | ' +
str(board[4]) + ' | ' + str(board[5]) + ' | ')
print(' | ' + str(board[6]) + ' | ' +
str(board[7]) + ' | ' + str(board[8]) + ' | ')
def main():
one = 1
flag = 1
show_board()
while one == 1:
if flag == 1:
x_o = 'X'
if flag == 2:
x_o = 'O'
pos = int(input('Player "' + x_o + '" Turn: '))
if x_o == 'o':
x_o = 'O'
if x_o == 'x':
x_o = 'X'
if board[pos - 1] == 'O' or board[pos - 1] == 'O':
print('That Place Is Already Filled By Player "0"')
if board[pos - 1] == 'X' or board[pos - 1] == 'X':
print('That Place Is Already Filled By Player "X"')
else:
try:
board[pos - 1] = x_o
except IndexError:
print('Type Numbers Between Only 1 And 9')
if flag == 1:
flag = 2
elif flag == 2:
flag = 1
show_board()
# Checking The Winner Of The Game
won = False
for turn in ('X', 'O'):
# horizontal
if not won:
for i in (0, 3, 6):
if all(board[i + k] == turn for k in range(3)):
won = True
break
# vertical
if not won:
for i in range(3):
if all(board[i + k] == turn for k in (0, 3, 6)):
won = True
break
# diagonal
if not won:
if all(board[k] == turn for k in (0, 4, 8)) or \
all(board[k] == turn for k in (2, 4, 6)):
won = True
# handle winning
if won:
one = 2
print(f'The Winner Is Player "{turn}"!')
break
# handle a tie
if not won and all(square != ' ' for square in board):
one = 2
print('The Match Is A Tie!')
main()
(您可能还可以对其余代码进行相当多的润色/简化)
这里有一些类似的代码被简化/完善/扩展为:
NUM_ROWS = 3
NUM_COLS = 3
NUM_WIN = 3
BOARD_SIZE = NUM_ROWS * NUM_COLS
EMPTY = ' '
BOARD = [EMPTY] * BOARD_SIZE
TURNS = 'X', 'O'
def show_board(board):
"""Show the tic-tac-toe board."""
for i in range(0, BOARD_SIZE, NUM_COLS):
print(' | ' + ' | '.join(board[i:i + NUM_COLS]) + ' | ')
def ij(i, j):
"""Convert (row, col) to board index."""
return i + NUM_COLS * j
def check_winner(board, turn):
"""Check if there is a winner."""
# horizontal
for i in range(NUM_ROWS):
for j in range(NUM_COLS - NUM_WIN + 1):
if all(board[ij(i, j + k)] == turn for k in range(NUM_WIN)):
return True
# vertical
for i in range(NUM_ROWS - NUM_WIN + 1):
for j in range(NUM_COLS):
if all(board[ij(i + k, j)] == turn for k in range(NUM_WIN)):
return True
# diagonal
for i in range(NUM_ROWS - NUM_WIN + 1):
for j in range(NUM_COLS - NUM_WIN + 1):
K = NUM_WIN
if all(board[ij(i + k, j + k)] == turn for k in range(NUM_WIN)):
return True
if all(board[ij(i + NUM_WIN - k - 1, j + k)] == turn
for k in range(NUM_WIN)):
return True
def check_tie(board):
"""Check if tie."""
return all(square != EMPTY for square in board)
def next_turn(turn):
"""Advance to next turn."""
return TURNS[(TURNS.index(turn) + 1) % 2]
def main():
"""Tic-tac-toe game."""
turn = TURNS[0]
show_board(BOARD)
while True:
valid_input = False
while not valid_input:
try:
choice = int(input(f'Player `{turn}` turn: '))
valid_input = (1 <= choice <= BOARD_SIZE)
if not valid_input:
raise ValueError
except ValueError:
print(f'Type numbers between 1 and {BOARD_SIZE} only.')
else:
idx = choice - 1
if BOARD[idx] != EMPTY:
print(f'Position `{idx}` already taken by `{BOARD[idx]}`')
else:
BOARD[idx] = turn
show_board(BOARD)
won = check_winner(BOARD, turn)
if won:
print(f'The winner is player `{turn}`!')
break
# handle a tie
if not won and check_tie(BOARD):
print('The match is a tie!')
break
turn = next_turn(turn)
if __name__ == '__main__':
main()
请查看mnk-game的 source code对于使用 NumPy 和类(尤其是 Board.py
)的类似实现。免责声明:我是该软件包的作者。
请注意,仅对于 tic-tac-toe,可以使用类似于 @rusu_ro1 proposed 的方法缩短 check_winner()
:
WIN_CASES = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], # horizontal
[0, 3, 6], [1, 4, 7], [2, 5, 8], # vertical
[0, 4, 8], [2, 4, 6], # diagonal
]
def check_winner(board, turn, win_cases=WIN_CASES):
"""Check if there is a winner."""
for win_case in win_cases:
if all(board[i] == turn for i in win_case):
return True
关于python - 如何避免多个 `elif` 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933057/
创建一个“海盗对话”,可以选择左手或右手。我希望它对“左”和“右”的不同拼写做出积极的回答(正如您将在代码中看到的那样),但是,当我为所有非“右”或“左”的输入添加最终的“else”代码时,它给了我一
With 语句 对一个对象执行一系列的语句。 With object statements End With 参数 object 必需的部分
While...Wend 语句 当指定的条件为 True 时,执行一系列的语句。 While condition  ; Version [stat
所以我正在处理的代码有一个小问题。 while True: r = input("Line: ") n = r.split() if r == " ":
我有一个对象数组: var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number"
int main() { int f=fun(); ... } int fun() { return 1; return 2; } 在上面的程序中,当从main函数中调用一个
我的项目中有很多 if 语句、嵌套 if 语句和 if-else 语句,我正在考虑将它们更改为 switch 语句。其中一些将具有嵌套的 switch 语句。我知道就编译而言,switch 语句通常更
Rem 语句 包含程序中的解释性注释。 Rem comment 或 ' comment comment 参数是需要包含的注释文本。在 Rem 关键字和 comment 之间应有一个空格。
ReDim 语句 在过程级中声明动态数组变量并分配或重新分配存储空间。 ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
Randomize 语句 初始化随机数生成器。 Randomize [number] number 参数可以是任何有效的数值表达式。 说明 Randomize 使用 number 参数初始
Public 语句 定义公有变量并分配存储空间。在 Class 块中定义私有变量。 Public varname[([subscripts])][, varname[([subscripts])
Sub 语句 声明 Sub 过程的名称、参数以及构成其主体的代码。 [Public [Default]| Private] Sub name [( arglist )]
Set 语句 将对象引用赋给一个variable或property,或者将对象引用与事件关联。 Set objectvar = {objectexpression | New classname
我有这个代码块,有时第一个 if 语句先运行,有时第二个 if 语句先运行。我不确定为什么会这样,因为我认为 javascript 是同步的。 for (let i = 0; i < dataObje
这是一个 javascript 代码,我想把它写成这样:如果此人回答是,则回复“那很酷”,如果此人回答否,则回复“我会让你开心”,如果此人回答的问题包含"is"或“否”,请说“仅键入”是或否,没有任何
这是我的任务,我尝试仅使用简短的 if 语句来完成此任务,我得到的唯一错误是使用“(0.5<=ratio<2 )”,除此之外,构造正确吗? Scanner scn = new Scanner(
有没有办法在 select 语句中使用 if 语句? 我不能在这个中使用 Case 语句。实际上我正在使用 iReport 并且我有一个参数。我想要做的是,如果用户没有输入某个参数,它将选择所有实例。
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: If vs. Switch Speed 我将以 C++ 为例,但我要问的问题不是针对特定语言的。我的意思是一
Property Set 语句 在 Class 块中,声明名称、参数和代码,这些构成了将引用设置到对象的 Property 过程的主体。 [Public | Private] Pro
Property Let 语句 在 Class 块中,声明名称、参数和代码等,它们构成了赋值(设置)的 Property 过程的主体。 [Public | Private] Prop
我是一名优秀的程序员,十分优秀!