python通过函数写一个五子棋代码
时间: 2024-05-03 11:19:40 浏览: 12
好的,下面是一个简单的五子棋代码实现。
```python
def print_board(board):
# 打印棋盘
for i in range(15):
for j in range(15):
print(board[i][j], end=" ")
print()
def check_win(board, x, y):
# 检查是否有玩家获胜
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
tx, ty = x, y
while tx + dx < 15 and tx + dx >= 0 and ty + dy < 15 and ty + dy >= 0 \
and board[tx + dx][ty + dy] == board[x][y]:
count += 1
tx += dx
ty += dy
tx, ty = x, y
while tx - dx >= 0 and tx - dx < 15 and ty - dy >= 0 and ty - dy < 15 \
and board[tx - dx][ty - dy] == board[x][y]:
count += 1
tx -= dx
ty -= dy
if count >= 5:
return True
return False
def game():
# 游戏主函数
board = [[0] * 15 for i in range(15)]
player = 1
while True:
print_board(board)
if player == 1:
print("轮到玩家1下棋")
else:
print("轮到玩家2下棋")
x = int(input("请输入横坐标:"))
y = int(input("请输入纵坐标:"))
if board[x][y] != 0:
print("该位置已经有棋子了,请重新输入")
continue
board[x][y] = player
if check_win(board, x, y):
print("玩家{}获胜".format(player))
break
player = 3 - player
game()
```
这个代码实现了一个简单的五子棋游戏,玩家1使用1表示,玩家2使用2表示。每次下棋时,程序会检查是否有玩家获胜,如果有,则输出获胜信息并结束游戏。