怎么用python做一个井字棋游戏
时间: 2023-05-31 08:01:44 浏览: 121
python实现井字棋小游戏
5星 · 资源好评率100%
以下是一个简单的井字棋游戏的Python代码:
```
board = {'1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '}
def print_board(board):
print(board['1'] + '|' + board['2'] + '|' + board['3'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['7'] + '|' + board['8'] + '|' + board['9'])
def check_win(board, player):
if (board['1'] == player and board['2'] == player and board['3'] == player) or \
(board['4'] == player and board['5'] == player and board['6'] == player) or \
(board['7'] == player and board['8'] == player and board['9'] == player) or \
(board['1'] == player and board['4'] == player and board['7'] == player) or \
(board['2'] == player and board['5'] == player and board['8'] == player) or \
(board['3'] == player and board['6'] == player and board['9'] == player) or \
(board['1'] == player and board['5'] == player and board['9'] == player) or \
(board['3'] == player and board['5'] == player and board['7'] == player):
return True
else:
return False
def tic_tac_toe():
player = 'X'
count = 0
while count < 9:
print_board(board)
print("It's", player, "turn. Which place do you want to mark?")
move = input()
if board[move] == ' ':
board[move] = player
count += 1
if check_win(board, player):
print_board(board)
print("Congratulations! Player", player, "wins!")
return
if player == 'X':
player = 'O'
else:
player = 'X'
else:
print("This place is already marked. Choose another one.")
print_board(board)
print("It's a tie!")
tic_tac_toe()
```
该代码定义了一个空的棋盘(用字典实现),并实现了打印棋盘、检查胜利和游戏逻辑的函数。在主函数中,玩家按照交替的顺序输入所选择的棋盘位置,并判断是否出现胜利或平局的情况。如果出现了胜利或平局,游戏将结束并打印相应的信息。
阅读全文