当然可以!下面是一个简单的五子棋游戏的实现示例:
# 初始化棋盘
board = [[' ']*15 for _ in range(15)]
# 定义棋盘打印函数
def print_board(board):
for i in range(len(board)):
print(' '.join(board[i]))
# 判断是否连成五子
def check_win(board, row, col, player):
# 判断水平方向
count = 0
i = col - 4 if col >= 4 else 0
while i <= col:
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
i = col + 1
while i < len(board[0]) and i <= col + 4:
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
# 判断垂直方向
count = 0
i = row - 4 if row >= 4 else 0
while i <= row:
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
i = row + 1
while i < len(board) and i <= row + 4:
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
# 判断左上到右下方向
count = 0
i, j = row - 4 if row >= 4 else 0, col - 4 if col >= 4 else 0
while i <= row and j <= col:
if board[i][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
j += 1
i, j = row + 1, col + 1
while i < len(board) and i <= row + 4 and j < len(board[0]) and j <= col + 4:
if board[i][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
i += 1
j += 1
# 判断右上到左下方向
count = 0
i, j = row + 4 if row + 4 < len(board) else len(board) - 1, col - 4 if col >= 4 else 0
while i >= row and j <= col:
if board[i][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
i -= 1
j += 1
i, j = row - 1, col + 1
while i >= 0 and i >= row - 4 and j < len(board[0]) and j <= col + 4:
if board[i][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
i -= 1
j += 1
return False
# 游戏主循环
player = 'X'
print_board(board)
while True:
move = input("请玩家 %s 输入落子位置,格式为 行,列:" % player).split(',')
row, col = int(move[0]), int(move[1])
if board[row][col] == ' ':
board[row][col] = player
if check_win(board, row, col, player):
print("玩家 %s 获胜!" % player)
break
player = 'O' if player == 'X' else 'X'
else:
print("该位置已有棋子,请重新输入!")
print_board(board)
这个游戏使用命令行进行交互,每次轮到一个玩家输入棋子的坐标。游戏会根据输入的坐标在棋盘上放置对应的棋子,并判断是否有玩家获胜。如果某个玩家连成了五子,游戏结束并宣布获胜者。
希望这可以帮助到你!祝玩得愉快!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |