给出五子棋的python代码
时间: 2023-10-08 09:14:51 浏览: 91
以下是一个简单的五子棋Python代码:
```
import numpy as np
class Gomoku:
def __init__(self):
self.board = np.zeros((15, 15))
self.player = 1
self.gameover = False
def play(self, row, col):
if self.board[row][col] != 0 or self.gameover:
return False
self.board[row][col] = self.player
if self.check_win(row, col):
self.gameover = True
return True
self.player = 3 - self.player
return True
def check_win(self, row, col):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for d in directions:
count = 1
for k in range(1, 5):
i = row + k * d[0]
j = col + k * d[1]
if i < 0 or i >= 15 or j < 0 or j >= 15 or self.board[i][j] != self.player:
break
count += 1
for k in range(1, 5):
i = row - k * d[0]
j = col - k * d[1]
if i < 0 or i >= 15 or j < 0 or j >= 15 or self.board[i][j] != self.player:
break
count += 1
if count >= 5:
return True
return False
def print_board(self):
for i in range(15):
print(' '.join(str(int(x)) for x in self.board[i]))
if __name__ == '__main__':
game = Gomoku()
while not game.gameover:
game.print_board()
row = int(input('Player %d, enter row: ' % game.player))
col = int(input('Player %d, enter col: ' % game.player))
if not game.play(row, col):
print('Invalid move, try again.')
print('Player %d wins!' % game.player)
```
这个代码实现了一个简单的五子棋游戏,使用了numpy数组来存储棋盘状态。其中,play方法用于下棋,check_win方法用于检查是否有一方胜利,print_board方法用于打印当前棋盘状态。主函数中使用了一个while循环来不断询问玩家下棋,直到游戏结束。
阅读全文