python编写程序,实现人机交互的3*3井字棋。玩家决定画○或画×,电脑随机位置下棋子。
时间: 2023-05-22 17:01:34 浏览: 80
以下是 Python 编写的 3*3 井字棋游戏的代码,其中玩家可以选择画○或画×,电脑会随机下棋子:
```python
import random
board = [' '] * 9
player = ''
computer = ''
def draw_board(board):
print(' %s | %s | %s ' % (board[0], board[1], board[2]))
print('---+---+---')
print(' %s | %s | %s ' % (board[3], board[4], board[5]))
print('---+---+---')
print(' %s | %s | %s ' % (board[6], board[7], board[8]))
def choose_player():
global player, computer
while True:
player = input('Do you want to be X or O? ').upper()
if player == 'X':
computer = 'O'
break
elif player == 'O':
computer = 'X'
break
else:
print('Invalid input. Please enter X or O.')
def is_winner(board, player):
return ((board[0] == player and board[1] == player and board[2] == player) or
(board[3] == player and board[4] == player and board[5] == player) or
(board[6] == player and board[7] == player and board[8] == player) or
(board[0] == player and board[3] == player and board[6] == 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[0] == player and board[4] == player and board[8] == player) or
(board[2] == player and board[4] == player and board[6] == player))
def is_board_full(board):
return ' ' not in board
def get_player_move(board):
while True:
move = input('What is your next move? (1-9) ')
if move.isdigit() and int(move) in range(1, 10) and board[int(move) - 1] == ' ':
return int(move) - 1
else:
print('Invalid input. Please enter a number from 1 to 9.')
def get_computer_move(board):
possible_moves = []
for i in range(9):
if board[i] == ' ':
possible_moves.append(i)
return random.choice(possible_moves)
def play_game():
global board
print('Welcome to Tic Tac Toe!')
draw_board([1, 2, 3, 4, 5, 6, 7, 8, 9])
choose_player()
while True:
if player == 'X':
player_move = get_player_move(board)
board[player_move] = player
draw_board(board)
if is_winner(board, player):
print('Congratulations! You have won the game!')
break
elif is_board_full(board):
print('The game is a tie!')
break
computer_move = get_computer_move(board)
board[computer_move] = computer
draw_board(board)
if is_winner(board, computer):
print('Sorry, the computer has won the game.')
break
elif is_board_full(board):
print('The game is a tie!')
break
else:
computer_move = get_computer_move(board)
board[computer_move] = computer
draw_board(board)
if is_winner(board, computer):
print('Sorry, the computer has won the game.')
break
elif is_board_full(board):
print('The game is a tie!')
break
player_move = get_player_move(board)
board[player_move] = player
draw_board(board)
if is_winner(board, player):
print('Congratulations! You have won the game!')
break
elif is_board_full(board):
print('The game is a tie!')
break
play_game()
```
请注意,这个代码只是一个简单的实现,还有很多可以改进的地方。