python五子棋小游戏的源码
时间: 2023-10-15 11:04:31 浏览: 92
以下是一个简单的 Python 五子棋小游戏的源码:
```python
import numpy as np
BOARD_SIZE = 15 # 棋盘大小
EMPTY = 0 # 空棋子
BLACK = 1 # 黑棋子
WHITE = 2 # 白棋子
class Board:
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
self.current_player = BLACK
def place(self, x, y):
if self.board[x][y] == EMPTY:
self.board[x][y] = self.current_player
self.current_player = WHITE if self.current_player == BLACK else BLACK
return True
else:
return False
def check_win(self):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] != EMPTY:
# 横向
if j <= BOARD_SIZE - 5:
if self.board[i][j] == self.board[i][j+1] == self.board[i][j+2] == self.board[i][j+3] == self.board[i][j+4]:
return self.board[i][j]
# 纵向
if i <= BOARD_SIZE - 5:
if self.board[i][j] == self.board[i+1][j] == self.board[i+2][j] == self.board[i+3][j] == self.board[i+4][j]:
return self.board[i][j]
# 左上到右下
if i <= BOARD_SIZE - 5 and j <= BOARD_SIZE - 5:
if self.board[i][j] == self.board[i+1][j+1] == self.board[i+2][j+2] == self.board[i+3][j+3] == self.board[i+4][j+4]:
return self.board[i][j]
# 右上到左下
if i >= 4 and j <= BOARD_SIZE - 5:
if self.board[i][j] == self.board[i-1][j+1] == self.board[i-2][j+2] == self.board[i-3][j+3] == self.board[i-4][j+4]:
return self.board[i][j]
return EMPTY
class Game:
def __init__(self):
self.board = Board()
def start(self):
while True:
self.print_board()
x, y = input(f"请 {self.board.current_player} 玩家下棋(x,y):").split(',')
x, y = int(x), int(y)
if 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE:
if self.board.place(x, y):
winner = self.board.check_win()
if winner != EMPTY:
self.print_board()
print(f"{winner} 玩家获胜!")
break
else:
print("此处已经有棋子了,请重新下棋!")
else:
print("坐标范围不正确,请重新输入!")
def print_board(self):
print(" ", end="")
for i in range(BOARD_SIZE):
print(i, end=" ")
print()
for i in range(BOARD_SIZE):
print(i, end=" ")
for j in range(BOARD_SIZE):
if self.board.board[i][j] == BLACK:
print("●", end=" ")
elif self.board.board[i][j] == WHITE:
print("○", end=" ")
else:
print("+", end=" ")
print()
if __name__ == '__main__':
game = Game()
game.start()
```
使用方法:
- 下载源码并保存到本地;
- 在终端或命令行窗口中进入源码所在目录;
- 输入 `python gomoku.py` 命令运行程序;
- 根据提示输入坐标下棋。
注意:此程序为简单版本,可能存在一些小问题,欢迎大家提出改进意见。
阅读全文