我为井字游戏创建了一个简单的程序。我需要程序最后一部分的帮助。程序会检查游戏是否结束——有四种可能的判断:游戏应该继续,或者游戏以平局结束,你赢了,或者电脑赢了;有人可以帮忙吗。
function Victory
检查行、列和对角线值。如果行、列或对角线值等于 'X'
或 'O'
,则程序应打印 computer's win
或 User's win
。但我不确定在 Update_board
中的何处调用它。有人可以帮忙吗。
import random
def board():
"Creating Board dictionary"
dic_board = {}
v = 1
for i in range(3):
for j in range(3):
k = str(i) + str(j)
dic_board[k] = v
v += 1
update_board(dic_board)
def draw_board(board):
"""Draw board"""
for i in range(3):
print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+', end='')
print()
print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
for j in range(3):
k = str(i) + str(j)
print('| ' + str(board[k]) + ' ' * 3, end='')
print('|')
print('|' + ' ' * 5 + '|' + ' ' * 5 + '|' + ' ' * 5 + '|')
print('+' + '-' * 5 + '+' + '-' * 5 + '+' + '-' * 5 + '+', end='')
print()
def update_board(board):
"""the first move belongs to the computer -
it always puts its first 'X' in the middle of the board that is at 5;"""
total_moves = 0
flag = True #Flag = True for computer's move and False for user's move
while total_moves < 9 :
available_num = [v for k, v in board.items() if v not in ('X','O')]
if flag :
if total_moves == 0:
Update_moves(board, 'Comp', 5)
flag = False
draw_board(board)
else:
num = random.choice(available_num)
Update_moves(board, 'Comp', num)
flag = False
draw_board(board)
else:
try:
s = str(available_num)
val = int(input('Select Number '+ s + ': '))
Update_moves(board, 'User', val)
flag = True
except:
print('Invalid Input!!')
total_moves += 1
return board
def Update_moves(board, moves,val):
"Updating borad as per input"
key_to_update = [k for k, v in board.items() if v == val]
if moves == 'Comp':
board[key_to_update[0]] = 'X'
elif moves == 'User':
board[key_to_update[0]] = 'O'
return board
def Victory(board,sign):
message = ''
message = row_status(board,sign,message)
message = column_status(board,sign,message)
message = digonals_status(board,sign,message)
return message
def row_status(board,sign,message):
"""checking for Horizontal row"""
if board['00'] == board['01'] == board['02'] == sign or \
board['10'] == board['11'] == board['12'] == sign or \
board['20'] == board['21'] == board['22'] == sign:
if sign == 'X':
message = 'computer win !!'
elif sign == 'O':
message = 'Your win !!'
return message
def column_status(board,sign,message):
"""checking for verticle column """
if board['00'] == board['10'] == board['20'] == sign or \
board['01'] == board['11'] == board['21'] == sign or \
board['02'] == board['12'] == board['22'] == sign:
if sign == 'X':
message = 'computer win !!'
elif sign == 'O':
message = 'Your win !!'
return message
def digonals_status(board,sign,message):
"""checking for digonals """
if board['00'] == board['11'] == board['22'] == sign or \
board['02'] == board['11'] == board['20'] == sign :
if sign == 'X':
message = 'computer win !!'
elif sign == 'O':
message = 'Your win !!'
return message
print(board())