Python五子棋游戏代码:简单实现
当然,我可以为您编写一个基于Python的五子棋代码。下面是一个简单的实现示例:
import numpy as np
# 创建一个15x15的棋盘
board = np.zeros((15, 15), dtype=int)
# 定义棋盘上的空、黑、白三种棋子状态
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义初始玩家为黑棋
player = BLACK
# 判断当前位置是否越界
def is_valid_move(x, y):
return x >= 0 and x < 15 and y >= 0 and y < 15
# 判断当前位置是否为空
def is_empty(x, y):
return board[x][y] == EMPTY
# 判断当前位置是否胜利
def is_winning_move(x, y):
# 检查横向是否胜利
for i in range(max(0, x - 4), min(15, x + 5)):
if board[i][y] == player and board[i + 1][y] == player and board[i + 2][y] == player and board[i + 3][y] == player and board[i + 4][y] == player:
return True
# 检查纵向是否胜利
for j in range(max(0, y - 4), min(15, y + 5)):
if board[x][j] == player and board[x][j + 1] == player and board[x][j + 2] == player and board[x][j + 3] == player and board[x][j + 4] == player:
return True
# 检查左上到右下是否胜利
for i in range(max(x - 4, 0), min(x + 5, 15)):
for j in range(max(y - 4, 0), min(y + 5, 15)):
if i + 4 < 15 and j + 4 < 15:
if board[i][j] == player and board[i + 1][j + 1] == player and board[i + 2][j + 2] == player and board[i + 3][j + 3] == player and board[i + 4][j + 4] == player:
return True
# 检查左下到右上是否胜利
for i in range(max(x - 4, 0), min(x + 5, 15)):
for j in range(min(y + 4, 14), max(y - 5, -1), -1):
if i + 4 < 15 and j - 4 >= 0:
if board[i][j] == player and board[i + 1][j - 1] == player and board[i + 2][j - 2] == player and board[i + 3][j - 3] == player and board[i + 4][j - 4] == player:
return True
return False
# 打印当前棋盘状态
def print_board():
for i in range(15):
for j in range(15):
if board[i][j] == EMPTY:
print('-', end=' ')
elif board[i][j] == BLACK:
print('X', end=' ')
else:
print('O', end=' ')
print()
# 下棋
def make_move(x, y):
if is_valid_move(x, y) and is_empty(x, y):
board[x][y] = player
return True
return False
# 切换玩家
def switch_player():
global player
if player == BLACK:
player = WHITE
else:
player = BLACK
# 游戏主循环
def play_game():
print('欢迎来到五子棋游戏!')
print('玩家1执黑棋,玩家2执白棋。')
print('请输入您的下棋位置,格式为 x y(0-14的整数,以空格分隔):')
while True:
print_board()
x, y = map(int, input('玩家{}的回合:'.format(player)).split())
if make_move(x, y):
if is_winning_move(x, y):
print_board()
print('恭喜玩家{}获胜!'.format(player))
break
switch_player()
else:
print('无效的位置,请重新下棋。')
# 启动游戏
play_game()
请注意,这只是一个简单的五子棋实现,还有很多可以改进和优化的地方。您可以根据自己的需求进行修改和扩展。希望对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/bRxv 著作权归作者所有。请勿转载和采集!