Python实现的井字棋(Tic Tac Toe)游戏示例
简介
本文将介绍Python实现的井字棋(Tic Tac Toe)游戏示例的完整攻略,包含游戏规则、实现过程、代码实现、运行效果等。
游戏规则
井字棋(Tic Tac Toe)是一种非常简单的两人游戏,用于培养儿童的逻辑思维能力。游戏规则如下:
- 游戏由两个玩家轮流下棋,由 X 先手,O 后手;
- 棋盘是一个 3x3 的方格,在空白处进行填字游戏。第一方在棋盘中部填上 X ,接下来轮流放棋子;
- 玩家必须在落子后,连成一行、一列或一斜线的三个自己棋子点,才能获胜;
- 如棋盘被填满,双方都没有赢,则游戏结束,平局。
实现过程
本游戏的实现过程大致如下:
- 初始化棋盘界面
- 玩家进行落子
- 验证是否获胜/平局,否则切换到另一个玩家继续游戏
- 输出结果
代码实现
下面是该游戏的Python代码实现:
def print_board(board):
print(board[0], "|", board[1], "|", board[2])
print("---------")
print(board[3], "|", board[4], "|", board[5])
print("---------")
print(board[6], "|", board[7], "|", board[8])
def win(board, player):
# 判断行是否连成一条线
if board[0] == player and board[1] == player and board[2] == player:
return True
if board[3] == player and board[4] == player and board[5] == player:
return True
if board[6] == player and board[7] == player and board[8] == player:
return True
# 判断列是否连成一条线
if board[0] == player and board[3] == player and board[6] == player:
return True
if board[1] == player and board[4] == player and board[7] == player:
return True
if board[2] == player and board[5] == player and board[8] == player:
return True
# 判断两个对角线是否连成一条线
if board[0] == player and board[4] == player and board[8] == player:
return True
if board[2] == player and board[4] == player and board[6] == player:
return True
return False
def tic_tac_toe():
board = [" "] * 9
player = "X"
while True:
print_board(board)
print("It's", player, "turn. Choose a position:")
choice = int(input()) - 1
if board[choice] == " ":
board[choice] = player
if win(board, player):
print_board(board)
print(player, "wins!")
break
if " " not in board:
print_board(board)
print("Draw!")
break
player = "O" if player == "X" else "X"
else:
print("Invalid move, try again.")
tic_tac_toe()
运行效果
你可以把代码复制一下,粘贴到Python解释器或者Pycharm等开发工具里执行。
下面是一局游戏的示例:
| |
---------
| |
---------
| |
It's X turn. Choose a position:
5
| |
---------
| X |
---------
| |
It's O turn. Choose a position:
1
O | |
---------
| X |
---------
| |
It's X turn. Choose a position:
2
O | X |
---------
| X |
---------
| |
It's O turn. Choose a position:
4
O | X |
---------
O | X |
---------
| |
It's X turn. Choose a position:
3
O | X | X
---------
O | X |
---------
| |
X wins!
示例说明
- 示例1: 初始化一个棋盘,并且将第4个位置填上X,结果显示为:
| | |
---------
| X | |
---------
| | |
- 示例2: 在填上X之后,O方填上3号位置。结果显示为:
| | |
---------
| X | |
---------
| O | |
总结
通过本文的Python实现的井字棋(Tic Tac Toe)游戏示例的完整攻略,你学习了Python语言实现简易版棋盘游戏的基本方法,掌握了编写复杂逻辑的技巧和技术,相信你已经顺利完成了代码实现并且得到了该游戏的完整运行效果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python实现的井字棋(Tic Tac Toe)游戏示例 - Python技术站