怎么用python做一个五子棋游戏
时间: 2023-05-30 21:04:13 浏览: 114
基于python的五子棋小游戏
5星 · 资源好评率100%
以下是一个简单的五子棋游戏的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.player = BLACK
# 下棋函数
def move(self, row, col):
if self.board[row][col] == EMPTY:
self.board[row][col] = self.player
self.player = BLACK if self.player == WHITE else WHITE
return True
else:
return False
# 判断是否有五子连珠
def has_winner(self):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
continue
if j + 4 < BOARD_SIZE and \
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 + 4 < BOARD_SIZE:
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 j + 4 < BOARD_SIZE and 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 j - 4 >= 0 and 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
# 打印棋盘
def print_board(self):
print(" ", end="")
for i in range(BOARD_SIZE):
print("{0:2d}".format(i), end="")
print()
for i in range(BOARD_SIZE):
print("{0:2d}".format(i), end="")
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
print(" . ", end="")
elif self.board[i][j] == BLACK:
print(" X ", end="")
else:
print(" O ", end="")
print()
# 游戏主函数
def main():
board = Board()
while True:
board.print_board()
winner = board.has_winner()
if winner != EMPTY:
if winner == BLACK:
print("黑方胜利!")
else:
print("白方胜利!")
break
if board.player == BLACK:
print("黑方下棋:")
else:
print("白方下棋:")
x, y = map(int, input().split())
if board.move(x, y):
continue
else:
print("该位置已有棋子,请重新下棋!")
if __name__ == '__main__':
main()
```
运行该代码后,可以通过输入坐标来进行下棋。在棋盘上输入坐标时,以空格分隔行和列,例如“1 2”表示在第1行第2列下棋。程序会根据输入的坐标在棋盘上下棋,并交替更换玩家。当有一方获得五子连珠时,程序会宣布胜利者并结束游戏。
阅读全文