一个五子棋游戏的完整代码
时间: 2024-03-01 10:50:48 浏览: 18
以下是一个使用Python语言实现的简单五子棋游戏的完整代码:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋类
class Chess:
def __init__(self, x, y, chess_type):
self.x = x
self.y = y
self.chess_type = chess_type
# 定义棋盘类
class Board:
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 落子
def move(self, chess):
self.board[chess.x][chess.y] = chess.chess_type
# 判断是否有五子连珠
def is_win(self, chess):
count = 1
# 水平方向
for i in range(1, 5):
if chess.y-i < 0 or self.board[chess.x][chess.y-i] != chess.chess_type:
break
count += 1
for i in range(1, 5):
if chess.y+i >= BOARD_SIZE or self.board[chess.x][chess.y+i] != chess.chess_type:
break
count += 1
if count >= 5:
return True
count = 1
# 竖直方向
for i in range(1, 5):
if chess.x-i < 0 or self.board[chess.x-i][chess.y] != chess.chess_type:
break
count += 1
for i in range(1, 5):
if chess.x+i >= BOARD_SIZE or self.board[chess.x+i][chess.y] != chess.chess_type:
break
count += 1
if count >= 5:
return True
count = 1
# 左上到右下方向
for i in range(1, 5):
if chess.x-i < 0 or chess.y-i < 0 or self.board[chess.x-i][chess.y-i] != chess.chess_type:
break
count += 1
for i in range(1, 5):
if chess.x+i >= BOARD_SIZE or chess.y+i >= BOARD_SIZE or self.board[chess.x+i][chess.y+i] != chess.chess_type:
break
count += 1
if count >= 5:
return True
count = 1
# 右上到左下方向
for i in range(1, 5):
if chess.x-i < 0 or chess.y+i >= BOARD_SIZE or self.board[chess.x-i][chess.y+i] != chess.chess_type:
break
count += 1
for i in range(1, 5):
if chess.x+i >= BOARD_SIZE or chess.y-i < 0 or self.board[chess.x+i][chess.y-i] != chess.chess_type:
break
count += 1
if count >= 5:
return True
return False
# 判断是否有棋子可下
def can_move(self):
return np.count_nonzero(self.board) < BOARD_SIZE * BOARD_SIZE
# 打印棋盘
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[i][j] == 1:
print('x', end=' ')
elif self.board[i][j] == 2:
print('o', end=' ')
else:
print('-', end=' ')
print()
# 定义游戏类
class Game:
def __init__(self):
self.board = Board()
self.current_player = 1
# 切换玩家
def switch_player(self):
if self.current_player == 1:
self.current_player = 2
else:
self.current_player = 1
# 运行游戏
def run(self):
while True:
self.board.print_board()
print('Player', self.current_player, 'move:')
x = int(input('x = '))
y = int(input('y = '))
# 判断落子是否合法
if x < 0 or x >= BOARD_SIZE or y < 0 or y >= BOARD_SIZE or self.board.board[x][y] != 0:
print('Invalid move!')
continue
chess = Chess(x, y, self.current_player)
self.board.move(chess)
# 判断是否获胜
if self.board.is_win(chess):
self.board.print_board()
print('Player', self.current_player, 'wins!')
break
# 判断是否平局
if not self.board.can_move():
self.board.print_board()
print('Draw game!')
break
self.switch_player()
# 运行游戏
game = Game()
game.run()
```
注意:此代码仅实现了基本的五子棋游戏逻辑,由于没有使用任何AI算法,玩家与电脑的对弈需要自己实现。