用python写一个一百行的五子棋
时间: 2024-05-07 15:18:28 浏览: 64
好的,下面是一个简单的五子棋游戏实现,代码共计 99 行:
```python
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def is_valid_move(board, row, col):
if row < 0 or row > 14 or col < 0 or col > 14:
return False
if board[row][col] != 0:
return False
return True
def get_winner(board):
# 横向判断
for i in range(15):
for j in range(11):
if board[i][j] == board[i][j+1] == board[i][j+2] == board[i][j+3] == board[i][j+4] and board[i][j] != 0:
return board[i][j]
# 纵向判断
for i in range(11):
for j in range(15):
if board[i][j] == board[i+1][j] == board[i+2][j] == board[i+3][j] == board[i+4][j] and board[i][j] != 0:
return board[i][j]
# 左上到右下判断
for i in range(11):
for j in range(11):
if board[i][j] == board[i+1][j+1] == board[i+2][j+2] == board[i+3][j+3] == board[i+4][j+4] and board[i][j] != 0:
return board[i][j]
# 右上到左下判断
for i in range(11):
for j in range(4, 15):
if board[i][j] == board[i+1][j-1] == board[i+2][j-2] == board[i+3][j-3] == board[i+4][j-4] and board[i][j] != 0:
return board[i][j]
return 0
def print_board(board):
for i in range(15):
print("{} {}".format(str(i).zfill(2), " ".join(str(int(x)) for x in board[i])))
print(" " + " ".join(str(i).zfill(2) for i in range(15)))
def play_game():
board = create_board()
current_player = 1
while True:
print_board(board)
row = int(input("Player {}'s turn. Enter row number (00-14): ".format(current_player)).strip())
col = int(input("Player {}'s turn. Enter col number (00-14): ".format(current_player)).strip())
if not is_valid_move(board, row, col):
print("Invalid move!")
continue
board[row][col] = current_player
winner = get_winner(board)
if winner != 0:
print_board(board)
print("Player {} wins!".format(winner))
break
current_player = 3 - current_player
if __name__ == "__main__":
play_game()
```
这个五子棋游戏实现了以下功能:
1. 创建一个 15x15 的棋盘(通过 numpy 库实现)。
2. 判断玩家输入的落子是否有效。
3. 判断游戏是否结束并宣布获胜者。
4. 在控制台中显示当前棋盘状态,要求玩家输入落子坐标。
5. 实现玩家轮流落子,直到游戏结束。
由于这只是一个简单的五子棋游戏,所以还有很多地方可以改进,例如:
1. 可以添加人机对战模式。
2. 可以添加悔棋功能。
3. 可以添加保存和读取游戏进度的功能。
4. 可以美化游戏界面等等。
阅读全文