我对编程很陌生,并为Tic-Tac-Toe游戏编写了这段代码。
但是,我觉得代码可以压缩一些,特别是在函数、Map_1st_Player_Input_to_Player_Board、Map_2nd_Player_Input_to_Player_Board和Check_For_Win中,在这些函数中,我非常依赖if、elif语句。
我能得到一些关于优化这段代码的反馈吗?
#Function to print out the playing board
def Print_Player_Board():
print '\n'.join([' '.join(row) for row in Player_Board])
#Function to print out player ones position
def Map_1st_Player_Input_to_Player_Board():
while True:
try:
Entry = int(raw_input("Player One Enter Your Playing Position: "))
if Entry == 1 and Player_Board[2][1] not in ('X', 'O'):
Player_Board[2][1] = 'X'
break
elif Entry == 2 and Player_Board[2][3] not in ('X', 'O'):
Player_Board[2][3] = 'X'
break
elif Entry == 3 and Player_Board[2][5] not in ('X', 'O'):
Player_Board[2][5] = 'X'
break
elif Entry == 4 and Player_Board[1][1] not in ('X', 'O'):
Player_Board[1][1] = 'X'
break
elif Entry == 5 and Player_Board[1][3] not in ('X', 'O'):
Player_Board[1][3] = 'X'
break
elif Entry == 6 and Player_Board[1][5] not in ('X', 'O'):
Player_Board[1][5] = 'X'
break
elif Entry == 7 and Player_Board[0][1] not in ('X', 'O'):
Player_Board[0][1] = 'X'
break
elif Entry == 8 and Player_Board[0][3] not in ('X', 'O'):
Player_Board[0][3] = 'X'
break
elif Entry == 9 and Player_Board[0][5] not in ('X', 'O'):
Player_Board[0][5] = 'X'
break
elif Entry > 9:
print 'An Incorrect Board Position Was Entered. Player Please Try Again'
else:
print "Current Position Is Filled. Please Try Again."
except ValueError:
print 'Sorry, Invalid Entry Made, Please Try Again.'
#Function to print out player twos position
def Map_2nd_Player_Input_to_Player_Board():
while True:
try:
Entry = int(raw_input("Player Two Enter Your Playing Position: "))
if Entry == 1 and Player_Board[2][1] not in ('X', 'O'):
Player_Board[2][1] = 'O'
break
elif Entry == 2 and Player_Board[2][3] not in ('X', 'O'):
Player_Board[2][3] = 'O'
break
elif Entry == 3 and Player_Board[2][5] not in ('X', 'O'):
Player_Board[2][5] = 'O'
break
elif Entry == 4 and Player_Board[1][1] not in ('X', 'O'):
Player_Board[1][1] = 'O'
break
elif Entry == 5 and Player_Board[1][3] not in ('X', 'O'):
Player_Board[1][3] = 'O'
break
elif Entry == 6 and Player_Board[1][5] not in ('X', 'O'):
Player_Board[1][5] = 'O'
break
elif Entry == 7 and Player_Board[0][1] not in ('X', 'O'):
Player_Board[0][1] = 'O'
break
elif Entry == 8 and Player_Board[0][3] not in ('X', 'O'):
Player_Board[0][3] = 'O'
break
elif Entry == 9 and Player_Board[0][5] not in ('X', 'O'):
Player_Board[0][5] = 'O'
break
elif Entry > 9:
print 'An Incorrect Board Position Was Entered. 2nd Player Please Try Again'
else:
print "Current Position Is Filled. Please Try Again."
except ValueError:
print 'Sorry, Invalid Entry Made, Try Again Please.'
#Function to check for possible win.
def Check_For_Win():
if Player_Board[2][1] == 'X' and Player_Board[2][3] == 'X' and Player_Board[2][5] == 'X':
return 1
elif Player_Board[2][1] == 'O' and Player_Board[2][3] == 'O' and Player_Board[2][5] == 'O':
return 2
elif Player_Board[1][1] == 'X' and Player_Board[1][3] == 'X' and Player_Board[1][5] == 'X':
return 1
elif Player_Board[1][1] == 'O' and Player_Board[1][3] == 'O' and Player_Board[1][5] == 'O':
return 2
elif Player_Board[0][1] =='X' and Player_Board[0][3] == 'X' and Player_Board[0][5] == 'X':
return 1
elif Player_Board[0][1] == 'O' and Player_Board[0][3] == 'O' and Player_Board[0][5] == 'O':
return 2
elif Player_Board[2][1] == 'X' and Player_Board[1][1] == 'X' and Player_Board[0][1] == 'X':
return 1
elif Player_Board[2][1] == 'O' and Player_Board[1][1] == 'O' and Player_Board[0][1] == 'O':
return 2
elif Player_Board[2][3] == 'X' and Player_Board[1][3] == 'X' and Player_Board[0][3] == 'X':
return 1
elif Player_Board[2][3] == 'O' and Player_Board[1][3] == 'O' and Player_Board[0][3] == 'O':
return 2
elif Player_Board[2][5] == 'X' and Player_Board[1][5] == 'X' and Player_Board[0][5] == 'X':
return 1
elif Player_Board[2][5] == 'O' and Player_Board[1][5] == 'O' and Player_Board[0][5] == 'O':
return 2
elif Player_Board[2][1] == 'X' and Player_Board[1][3] == 'X' and Player_Board[0][5] == 'X':
return 1
elif Player_Board[2][1] == 'O' and Player_Board[1][3] == 'O' and Player_Board[0][5] == 'O':
return 2
elif Player_Board[0][1] == 'X' and Player_Board[1][3] == 'X' and Player_Board[2][5] == 'X':
return 1
elif Player_Board[0][1] == 'O' and Player_Board[1][3] == 'O' and Player_Board[2][5] == 'O':
return 2
else:
pass
#Function For Game Replay
def Replay():
while True:
Response = raw_input("Would You Like To Play Again? (Y/N): ")
if Response in ('y', 'Y', 'Yes', 'yes'):
print("\n\n\n")
Game_Start()
break
elif Response in ('n', 'N', 'No', 'no'):
print 'Have A Great Day - GoodBye'
break
else:
print 'Invalid Response Provided. Please Try Again'
#Game Play Function
def Game_Start():
global Player_Board
global Counter
print "This is a Tic-Tac-Toe Game To Be Played Between Two Players."
print "This Game is Played with a Keypad Using the Numbers 1 Through 9"
print "Which Represent Board Locations as Follows;"
print ' | 7 | 8 | 9 |'
print ' | 4 | 5 | 6 |'
print ' | 1 | 2 | 3 |'
print "Player 1 Begins By Placing an 'X' Marker On the Board."
print "Player 2 Then Places an 'O' Marker On the Board."
print "The Game Will End At Any Time Either Player Succeeds In Landing Three Markers In Series"
print "This Can Be Done Horizontally, Vertically, Or Diagonally."
print "If At Any Time a Player Selects An Already Filled Position An Error Message Will Appear On The Screen"
print "The Player Will Then Take Another Turn And the Game Will Resume Until Either Player Wins "
print '\n'
Player_Board = [['|',' ','|',' ','|',' ','|'],['|',' ','|',' ','|',' ','|'], ['|',' ','|',' ','|',' ','|']]
print "Game Start"
Print_Player_Board()
Counter = 0 # Counter used to keep count of play moves. Use for Tie Game Logic
while Check_For_Win() not in (1, 2) and Counter < 9:
Map_1st_Player_Input_to_Player_Board()
Counter +=1
if Check_For_Win() == 1:
Print_Player_Board()
print '!!One Has Won!!'
break
else:
Print_Player_Board()
pass
if Counter < 9:
Map_2nd_Player_Input_to_Player_Board()
Counter +=1
if Check_For_Win() == 2:
Print_Player_Board()
print '!!Two Has Won!!'
break
else:
Print_Player_Board()
pass
if Counter > 8 and Check_For_Win() not in (1,2):
print '!GAME!'
Replay()
if Check_For_Win() in (1,2):
Replay()发布于 2017-02-03 22:27:54
Check_For_Win函数可以编写得更紧凑:
# Function to check for possible win.
# Returns the symbol of the player who has Won
# Returns False if nobody has won
def Check_For_Win(board):
# check for win in a row
for row in board:
if row[1] == row[3] == row[5] and row[1] != ' ':
return row[1]
# Check for win in a column
for i in [1, 3, 5]:
if board[0][i] == board[1][i] == board[2][i] and board[0][i] != ' ':
return board[0][i]
# Check for diagonal win:
if board[0][0] == board[1][1] == board[2][2] or board[0][2] == board[1][1] == board[2][0]:
return board[1][1] if board[1][1] != ' ' else False您还可以重写获得输入的输入方法,比如@ImperialJustinian建议的输入。我重写了您的Game_Start方法:
# Game Play Function
def Game_Start():
print "This is a Tic-Tac-Toe Game To Be Played Between Two Players."
print "This Game is Played with a Keypad Using the Numbers 1 Through 9"
print "Which Represent Board Locations as Follows;"
print ' | 7 | 8 | 9 |'
print ' | 4 | 5 | 6 |'
print ' | 1 | 2 | 3 |'
print "Player 1 Begins By Placing an 'X' Marker On the Board."
print "Player 2 Then Places an 'O' Marker On the Board."
print "The Game Will End At Any Time Either Player Succeeds In Landing Three Markers In Series"
print "This Can Be Done Horizontally, Vertically, Or Diagonally."
print "If At Any Time a Player Selects An Already Filled Position An Error Message Will Appear On The Screen"
print "The Player Will Then Take Another Turn And the Game Will Resume Until Either Player Wins "
print '\n'
print "Game Start"
Player_Board = [['|',' ','|',' ','|',' ','|'],['|',' ','|',' ','|',' ','|'], ['|',' ','|','','|',' ','|']]
Print_Player_Board(Player_Board) # Print_Player_Board now takes the board as an parameter to avoid these globals
Counter = 0 # Counter used to keep count of play moves. Use for Tie Game Logic
current_player = "X"
winner = False
while not winner and Counter < 9:
# the new input method should take the board and the current player and return the new board
Player_Board = get_input(board, current_player)
Print_Player_Board(Player_Board)
winner = Check_For_Win(Player_Board)
current_player = "X" if current_player == "0" else "0"
Counter += 1
if not winner:
print '!GAME!'
else:
print "!!'{}' Has Won!!".format(winner)
Replay()要使此工作,您必须将Print_Player_Board更改为:
# Function to print out the playing board
def Print_Player_Board(board):
print '\n'.join([' '.join(row) for row in board])您已经自己编写了函数get_input(board, player)
发布于 2017-02-02 17:39:27
首先,我想说我不熟悉Python本身。然而,我熟悉游戏之间相同的基本编程原则。
第二,你有太多的if语句。输入职位时只应有一个if语句,即检查所选职位是否有效;也就是说,其中包含X或O。(或者更好的情况是,如果我理解是正确的,则不是‘')。应该将用户输入的数字转换为数组中的坐标,而不是所拥有的。Ie:
x = Entry / 3;
y = Entry % 3;我进行了检查,并且模块在python中与其他语言(如C# )是相同的。Modulo从除法操作中检索余数。您可能需要更改哪个数字对应于可见网格中的位置的顺序。
此外,用于检查位置是否清楚的代码对于两位玩家来说几乎是相同的,并且可以移动到一个单独的函数(返回玩家选择正确的bool ),该函数接受玩家的字符来编写,这将具有确保两个玩家的代码是相同的优点。
我知道必须有一个更好的方法来检查胜利的状况,而不是if的声明,但我不知道这是什么从我的头顶。就像上面的一样,检查本身可以移动到它自己的基于字符的检查函数中,而不是对两个玩家重复每一个if。然后,可以为每个玩家调用此函数。
还有其他基于python本身的优化,我不知道。但这些是在任何语言中都应该有助于提高效率的基本要素。
https://codereview.stackexchange.com/questions/154274
复制相似问题