python井字棋代码
时间: 2023-07-02 08:08:22 浏览: 99
python实现井字棋小游戏
以下是一个简单的 Python 井字棋代码:
```python
def print_board(board):
print(f'{board[0]} | {board[1]} | {board[2]}')
print('-' * 9)
print(f'{board[3]} | {board[4]} | {board[5]}')
print('-' * 9)
print(f'{board[6]} | {board[7]} | {board[8]}')
def play_game():
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 'X'
print_board(board)
while True:
move = input(f'Player {player}, enter a position number (1-9): ')
move = int(move) - 1
if board[move] == ' ':
board[move] = player
print_board(board)
if check_winner(board, player):
print(f'Player {player} wins!')
break
if check_tie(board):
print('It\'s a tie!')
break
player = 'O' if player == 'X' else 'X'
else:
print('That position is already taken. Please try again.')
def check_winner(board, player):
wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
for win in wins:
if board[win[0]] == board[win[1]] == board[win[2]] == player:
return True
return False
def check_tie(board):
return ' ' not in board
play_game()
```
这个代码实现了一个基本的井字棋游戏,玩家通过输入数字来选择下棋的位置。代码使用一个列表来存储棋盘,并且在每次玩家下完棋后检查是否有胜者或者是否平局。
阅读全文