这是我第二次尝试用Python制作Tic。这是我学习的一部分。明天我会做一些简单的人工智能和更好的菜单。你觉得那个怎么样?你有什么建议吗?代码:
class Field:
val = " "
pos = 0
weight = 0
def __init__(self, n):
self.pos = n
self.val = str(n)
def display_board(b):
br = 1
for i in b:
if br >= 3:
print("[", i.val, "]", end='\n')
br = 0
else:
print("[", i.val, "]", end='')
br += 1
def did_player_won(b, t):
indexes = (
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Cols
(0, 4, 8), (2, 4, 6) # Diag
)
for idx in indexes:
if sum(b[i].weight for i in idx if b[i].val == t) == 15:
return True
def get_move(b, turn):
# Get user input while it's wrong
while True:
try:
move = int(input("Player %s turn!\n>>>" % turn))
# if input isn't an integer
except ValueError:
print("Wrong field!")
continue
else:
if 0 < move < 10:
for item in b:
if item.pos == move:
# Check if place is taken
if item.val == "X" or item.val == "O":
print("Field is taken!")
continue
else:
item.val = turn
item.weight = 5
print("Player %s took place %d" % (turn, move))
return True
else:
print("Incorrect field!")
continue
def next_turn(currentturn):
if currentturn == "X":
return "O"
else:
return "X"
def reset_game():
global board
global turn
global turns
board = [Field(7), Field(8), Field(9),
Field(4), Field(5), Field(6),
Field(1), Field(2), Field(3)]
turn = "X"
turns = 0
board = [Field(7), Field(8), Field(9),
Field(4), Field(5), Field(6),
Field(1), Field(2), Field(3)]
turn = "X"
turns = 0
moveMessage = "Player (%s) move: " % turn
while True:
display_board(board)
if turns >= 9:
display_board(board)
print("Draw!")
choice = input(">>>")
if choice == "play":
reset_game()
else:
break
if get_move(board, turn):
if did_player_won(board, turn):
display_board(board)
print("Player %s won! Congrats Comrade! It's OUR win!" % turn)
choice = input(">>>")
if choice == "play":
reset_game()
else:
break
else:
turn = next_turn(turn)
turns += 1发布于 2018-04-20 17:43:04
在编程中有一个一般的原则,你想避免重复自己。例如,您定义启动游戏设置两次,一次在重置函数中,一次在主脚本中。你可以拥有这个函数,然后在主脚本中调用它来设置第一个游戏。这意味着如果你想要改变它,你只需要更新一个地方。
当使用try和catch时,如果您的逻辑是在try中工作的话,它通常更容易读懂。这有助于按顺序读取代码,因为它是要执行的。这是一种平衡的行为,因为你确实想弄清楚你可能会遇到哪些失败。在这种情况下,我会填补它。
我的最后一个建议是考虑使用类来保持游戏状态。这只是帮助保持整洁的事情,特别是当你看到做人工智能。毕竟,你的人工智能将需要想象一堆游戏板,如果你只有一个板变量,这将是困难的。
接受player输入的主循环应该在类之外,但大多数其他东西都应该在类中。
发布于 2018-04-20 13:59:31
不是一个重大的建议,而是一个风格的建议。
您可以使用indent spacing of 2而不是4。
这会使代码看起来更好。
4个空间缩进
def hi(crazy):
if crazy:
print("...")
else:
print("Hi there")2个空间缩进
def hi(crazy):
if crazy:
print("...")
else:
print("Hi there")https://codereview.stackexchange.com/questions/192503
复制相似问题