写一个五子棋游戏
时间: 2023-07-01 12:17:44 浏览: 54
好的,以下是一个简单的五子棋游戏的代码:
```python
import numpy as np
ROW = 15
COL = 15
class Game:
def __init__(self):
self.board = np.zeros((ROW, COL), dtype=int)
self.current_player = 1
def play(self, row, col):
if self.board[row][col] != 0:
print("Invalid move. Please choose an empty spot.")
return False
self.board[row][col] = self.current_player
self.current_player = 3 - self.current_player
return True
def is_win(self, player):
for i in range(ROW):
for j in range(COL):
if self.board[i][j] == player:
if self.check_horizontal(i, j, player) or self.check_vertical(i, j, player) or self.check_diagonal_1(i, j, player) or self.check_diagonal_2(i, j, player):
return True
return False
def check_horizontal(self, row, col, player):
if col + 4 >= COL:
return False
for i in range(1, 5):
if self.board[row][col+i] != player:
return False
return True
def check_vertical(self, row, col, player):
if row + 4 >= ROW:
return False
for i in range(1, 5):
if self.board[row+i][col] != player:
return False
return True
def check_diagonal_1(self, row, col, player):
if row + 4 >= ROW or col + 4 >= COL:
return False
for i in range(1, 5):
if self.board[row+i][col+i] != player:
return False
return True
def check_diagonal_2(self, row, col, player):
if row - 4 < 0 or col + 4 >= COL:
return False
for i in range(1, 5):
if self.board[row-i][col+i] != player:
return False
return True
def is_full(self):
return np.all(self.board != 0)
def print_board(self):
print(" ", end="")
for i in range(COL):
print(chr(ord('a') + i), end=" ")
print()
for i in range(ROW):
print("{:2d}".format(i+1), end=" ")
for j in range(COL):
if self.board[i][j] == 0:
print(".", end=" ")
elif self.board[i][j] == 1:
print("X", end=" ")
else:
print("O", end=" ")
print()
if __name__ == "__main__":
game = Game()
while not game.is_full():
game.print_board()
print("Player {}'s turn".format(game.current_player))
move = input("Enter your move (e.g. b3): ")
col = ord(move[0]) - ord('a')
row = int(move[1:]) - 1
if game.play(row, col):
if game.is_win(1):
print("Player 1 wins!")
break
elif game.is_win(2):
print("Player 2 wins!")
break
else:
print("Game over. It's a tie.")
game.print_board()
```
这个游戏使用了numpy数组来表示棋盘,1表示黑子,2表示白子,0表示空位。然后使用了一些简单的算法来检查是否有玩家获胜。游戏界面会打印出当前棋盘的状态,并提示下一位玩家的行动。当游戏结束时,会打印出最终的棋盘状态和胜者(如果有)。