修改TicTacToe程序,补充“判断游戏结束”部分代码。
时间: 2024-03-25 07:37:03 浏览: 86
好的,我可以帮你修改TicTacToe程序并补充判断游戏结束的代码。在TicTacToe游戏中,判断游戏结束的条件通常有以下几种:
1. 棋盘填满,平局结束
2. 一方获胜,游戏结束
3. 玩家选择退出游戏
下面是修改后的TicTacToe程序,包含了判断游戏结束的代码:
```python
import random
# 初始化棋盘
board = [' '] * 10
# 随机决定玩家先手或电脑先手
def choose_first():
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
# 打印棋盘
def display_board(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
# 玩家选择棋子位置
def player_choice(board):
position = 0
while position not in range(1, 10) or not space_check(board, position):
try:
position = int(input('请选择你要下棋的位置(1-9): '))
except ValueError:
print('输入错误,请重新选择。')
return position
# 判断棋盘是否还有空位
def full_board_check(board):
return ' ' not in board[1:]
# 判断棋子位置是否可用
def space_check(board, position):
return board[position] == ' '
# 在棋盘上放置棋子
def place_marker(board, marker, position):
board[position] = marker
# 判断是否有一方获胜
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or
(board[4] == mark and board[5] == mark and board[6] == mark) or
(board[1] == mark and board[2] == mark and board[3] == mark) or
(board[7] == mark and board[4] == mark and board[1] == mark) or
(board[8] == mark and board[5] == mark and board[2] == mark) or
(board[9] == mark and board[6] == mark and board[3] == mark) or
(board[7] == mark and board[5] == mark and board[3] == mark) or
(board[9] == mark and board[5] == mark and board[1] == mark))
# 主游戏流程
print('欢迎来到井字棋游戏!')
while True:
# 初始化棋盘
board = [' '] * 10
player_marker = ''
computer_marker = ''
game_on = True
# 玩家选择棋子
while player_marker not in ['X', 'O']:
player_marker = input('请选择你要使用的棋子(X或O):').upper()
# 设置电脑使用的棋子
if player_marker == 'X':
computer_marker = 'O'
else:
computer_marker = 'X'
turn = choose_first()
print(turn + ' 先手。')
while game_on:
if turn == 'player':
# 玩家回合
display_board(board)
position = player_choice(board)
place_marker(board, player_marker, position)
# 判断是否获胜
if win_check(board, player_marker):
display_board(board)
print('恭喜你,你获胜了!')
game_on = False
else:
# 判断是否平局
if full_board_check(board):
display_board(board)
print('平局!')
break
else:
turn = 'computer'
else:
# 电脑回合
display_board(board)
position = random.randint(1, 9)
# 随机选择棋子位置
while not space_check(board, position):
position = random.randint(1, 9)
place_marker(board, computer_marker, position)
# 判断是否获胜
if win_check(board, computer_marker):
display_board(board)
print('很遗憾,你输了。')
game_on = False
else:
# 判断是否平局
if full_board_check(board):
display_board(board)
print('平局!')
break
else:
turn = 'player'
# 询问是否继续游戏
if input('是否继续游戏(Y/N)?').lower() != 'y':
break
```
在主游戏流程中,添加了游戏结束的判断,如果游戏结束,会提示玩家输赢或者平局,并询问是否继续游戏。
阅读全文
相关推荐
















