python井字棋游戏之选15
时间: 2023-07-19 10:24:37 浏览: 86
您好,关于 Python 的井字棋游戏选 15,我能够提供一些思路和代码实现。
首先,我们需要定义一个二维列表来表示井字棋盘面。可以使用数字 1 表示玩家 1 的棋子,数字 2 表示玩家 2 的棋子,0 表示空格。
```python
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
```
接着,我们可以定义一个函数来打印当前的棋盘状态。
```python
def print_board(board):
print(" 1 2 3")
for i in range(3):
row = str(i + 1) + " "
for j in range(3):
if board[i][j] == 1:
row += "X "
elif board[i][j] == 2:
row += "O "
else:
row += "_ "
print(row)
```
然后,我们需要定义一个函数来检查是否有玩家获胜。可以使用一个列表来存储所有可能的获胜组合,然后遍历这个列表,检查当前棋盘是否匹配其中任意一种获胜情况。
```python
def check_win(board):
# 所有可能的获胜组合
win_positions = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)]
]
for pos in win_positions:
if board[pos[0][0]][pos[0][1]] != 0 and \
board[pos[0][0]][pos[0][1]] == board[pos[1][0]][pos[1][1]] and \
board[pos[1][0]][pos[1][1]] == board[pos[2][0]][pos[2][1]]:
return True
return False
```
接下来,我们可以定义一个函数来让玩家下棋。该函数会循环等待玩家输入有效位置,然后更新棋盘状态,直到有玩家获胜或棋盘下满。
```python
def play_game():
print("Welcome to the game of Tic Tac Toe!")
print("Player 1 uses X and Player 2 uses O.")
current_player = 1
while True:
print_board(board)
row = int(input("Player " + str(current_player) + ", enter row number (1-3): "))
col = int(input("Player " + str(current_player) + ", enter column number (1-3): "))
row -= 1
col -= 1
if board[row][col] != 0:
print("Invalid move, try again.")
continue
board[row][col] = current_player
if check_win(board):
print_board(board)
print("Player " + str(current_player) + " wins!")
break
if sum([row.count(0) for row in board]) == 0:
print_board(board)
print("It's a tie!")
break
current_player = 3 - current_player
```
最后,我们可以调用 `play_game()` 函数来开始游戏。
```python
play_game()
```
希望这些代码能够帮助您实现 Python 的井字棋游戏选 15。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)