Python 井字棋4*4棋盘
时间: 2023-07-29 22:05:49 浏览: 240
以下是一个简单的 Python 井字棋 4*4 棋盘的实现:
```python
board = ['-'] * 16
def display_board():
row1 = '|'.join(board[0:4])
row2 = '|'.join(board[4:8])
row3 = '|'.join(board[8:12])
row4 = '|'.join(board[12:16])
print(row1)
print('-' * 9)
print(row2)
print('-' * 9)
print(row3)
print('-' * 9)
print(row4)
def check_valid_move(position):
if board[position] == '-':
return True
else:
return False
def check_win(player):
if (board[0] == board[1] == board[2] == board[3] == player or
board[4] == board[5] == board[6] == board[7] == player or
board[8] == board[9] == board[10] == board[11] == player or
board[12] == board[13] == board[14] == board[15] == player or
board[0] == board[4] == board[8] == board[12] == player or
board[1] == board[5] == board[9] == board[13] == player or
board[2] == board[6] == board[10] == board[14] == player or
board[3] == board[7] == board[11] == board[15] == player or
board[0] == board[5] == board[10] == board[15] == player or
board[3] == board[6] == board[9] == board[12] == player):
return True
else:
return False
def play_game():
display_board()
player = 'X'
while True:
position = int(input("Player " + player + ", enter a position (1-16): ")) - 1
if check_valid_move(position):
board[position] = player
display_board()
if check_win(player):
print("Player " + player + " wins!")
break
if '-' not in board:
print("Tie game!")
break
if player == 'X':
player = 'O'
else:
player = 'X'
else:
print("Invalid move, try again.")
play_game()
```
你可以在命令行中运行这段代码,开始玩井字棋游戏。
阅读全文