五子棋游戏python代码
时间: 2024-06-11 09:02:17 浏览: 13
五子棋游戏是一款非常经典的棋类游戏,下面是一个简单的五子棋Python代码示例:
```
import numpy as np
class Board:
def __init__(self, rows=15, cols=15, win=5):
self.rows = rows
self.cols = cols
self.win = win
self.board = np.zeros((rows, cols), dtype=np.int8)
self.current_player = 1
def move(self, row, col):
if self.board[row][col] == 0:
self.board[row][col] = self.current_player
self.current_player = 3 - self.current_player
return True
else:
return False
def check_win(self):
for i in range(self.rows):
for j in range(self.cols):
if self.board[i][j] != 0:
if j + self.win <= self.cols and len(set(self.board[i][j:j+self.win])) == 1:
return True
if i + self.win <= self.rows and len(set(self.board[i:i+self.win, j])) == 1:
return True
if i + self.win <= self.rows and j + self.win <= self.cols and len(set([self.board[i+k][j+k] for k in range(self.win)])) == 1:
return True
if i + self.win <= self.rows and j - self.win >= -1 and len(set([self.board[i+k][j-k] for k in range(self.win)])) == 1:
return True
return False
def display(self):
print(' ', end=' ')
for j in range(self.cols):
print(j, end=' ')
print()
for i in range(self.rows):
print(i, end=' ')
for j in range(self.cols):
if self.board[i][j] == 0:
print('.', end=' ')
elif self.board[i][j] == 1:
print('O', end=' ')
else:
print('X', end=' ')
print()
def reset(self):
self.board = np.zeros((self.rows, self.cols), dtype=np.int8)
self.current_player = 1
game = Board()
while True:
game.display()
row = int(input('Enter row: '))
col = int(input('Enter col: '))
if game.move(row, col):
if game.check_win():
game.display()
print(f'Player {3 - game.current_player} wins!')
break
else:
print('Invalid move!')
```
这个示例代码实现了基本的五子棋游戏功能,包括落子、检测胜负、显示棋盘等功能。你可以通过修改Board类的构造函数参数来调整棋盘大小和胜利条件,也可以根据自己的需求添加更多的功能。如果你不理解这段代码的具体实现方法,可以在CSDN的Python社区或者其他相关论坛上寻求帮助。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)