关于codereview的前面的代码
我是这里的新手,所以事先为任何愚蠢的错误道歉
我一直在写一个简单的抽搐脚趾游戏,这是我在udemy课程的一部分。
由于这是我的第一个项目,除了学习如何更好地编码之外,我还想尽我最大的努力来学习新的东西。通常,我希望尽可能地优化我的代码。
有人能帮我吗?
# Tic Tac Toe
# 17 July 2020
import os
test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_input_num = 0 # numbers of inputs entered by player
player_num = 0
won = False
marker = 'X'
def clear_screen():
os.system("clear")
def display_board(board_cords):
'''
display the board
board_cords = list(left to right from top to bottom)
'''
line = '-'*40
for counter in range(0, len(board_cords), 3):
print("\t|\t\t|")
print(
f"{board_cords[counter]}\t|\t{board_cords[counter+1]}\t|\t{board_cords[counter+2]}")
print(line)
counter += 3 # go to next row
def check_player_input(number):
if number < 10 and number >= 0: # checking the range
return True
else:
print('Sorry the input is not in range [0-9] .')
return False
def player_input(player_in):
global player_input_num # access to player_input_num
if player_input_num >= 2:
# check if the position is free to use
if check_capacity(test_board, player_in):
result = place_marker(test_board, 'X', player_in)
clear_screen()
display_board(result)
if check_win(test_board, marker):
print("You Won!")
global won
won = True
else:
print("The current position is occupied.")
else:
if check_capacity(test_board, player_in):
result = place_marker(test_board, 'X', player_in)
clear_screen()
display_board(result)
player_input_num += 1
else:
print("The current position is occupied.")
def check_capacity(board, position):
'''
Check if the current position is free to use.
'''
return board[position] == ' '
def place_marker(board, marker, position):
'''
Replace the position with a marker
'''
board[position] = marker
return board
def check_win(board, marker):
'''
Check if the current game is finished
'''
if board[0] == board[1] == board[2] == marker:
return True
if board[0] == board[3] == board[6] == marker:
return True
if board[0] == board[4] == board[8] == marker:
return True
if board[2] == board[5] == board[8] == marker:
return True
if board[6] == board[7] == board[8] == marker:
return True
if board[2] == board[4] == board[6] == marker:
return True
return False
def wanna_play():
answer = input("Wanna play again? (Y or N)")
return answer
# Main
display_board(test_board)
while True:
while won == False:
try: # checking if input is int
player_num = int(input("Enter a position: "))
except:
print("Input is not a number")
continue
if check_player_input(player_num):
player_input(player_num)
if wanna_play() in ['y', 'Y', 'n', 'N']:
print("something")
else:
print("Invalid input.")
# print("Thanks for playing :)")请注意,代码正在工作,我只想知道其他方法,并优化它的工作服。
发布于 2020-07-17 21:56:56
不要使用从0到9的索引,而是将存储板的方式改为3x3列表。
board = list([[0] * 3] * 3)
"""
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
"""这将允许您回到它并添加一个GUI。对于任何阅读代码的人来说,直观地理解正在发生的事情也变得更加容易了。
下一个是你的打印板。加入会是你的朋友。
for row in board:
printout = "\t|\t".join(str(element) for element in row)
print(printout) # this can be reduced to a single line if you want.range()接受3个变量。启动、停止和增量量
for i in range(0, 9, 3):您也可以使用负值进行反转。
for i in range(9, 0, -1):或
for row in board[::-1]:在数学课上,你知道怎么能写出一个 b吗?您可以在python中做到这一点,而不需要and。
if 0 <= number > 10:然后检查董事会的状态是否有人赢了。当前的方法需要大量的编码,不能快速扩展。
有几种不同的方法,你可以这样做。一切都会“起作用”
首先是行
for row in board:
if len(set(row)) == 1:
return Truefor row in board:
if all(element == row[0] for element in rows):
return True下一步是对角线(我将使用tempory虚拟变量来提高len(board)的可读性。-> _ = len(board)
if len(set(board[i][i] for i in range(len(board)) == 1:
return True
if len(set(board[i][len(board)-i-1] for i in range(len(board)) == 1:
return True柱可以是一个更棘手的,但转置可能是最重要的仿生方式来接近它。
board_T = [list(column) for column in zip(board)]这将允许您再次调用行,并检查是否有人获胜。
应该注意的是,胜利者状态的返回值可以返回True或False的播放器。Python在if语句中将0、None、空迭代和False视为False。
我还注意到,你并没有遵循在最初的文章中给你的很多建议。您仍然缺少一个if __name__ == "__main__":语句
def playTicTacToe():
display_board(test_board)
...
...
if __name__ == "__main__":
playTicTacToe()https://codereview.stackexchange.com/questions/245639
复制相似问题