第32章 五子棋的游戏代码
你现在是营养丰富的程序员,写一段五子棋的游戏代码
很好,我可以帮你写一段简单的五子棋游戏代码。下面是示例代码:
```
import numpy as np
初始化棋盘
def init_board(n):
board = npzeros((n, n))
return board
判断某个位置是否合法
def is_valid(board, move):
x, y = move
if board[x][y] == 0:
return true
else:
return false
下棋
def move(board, move, player):
if is_valid(board, move):
board[move[0]][move[1]] = player
return true
else:
return false
判断胜利条件
def check_win(board, player):
n = len(board)
检查行
for i in range(n):
count = 0
for j in range(n):
if board[i][j] == player:
count += 1
else:
count = 0
if count >= 5:
return true
检查列
for j in range(n):
count = 0
for i in range(n):
if board[i][j] == player:
count += 1
else:
count = 0
if count >= 5:
return true
检查主对角线
for k in range(n2-1):
count = 0
for i in range(n):
j = k - i
if j >= 0 and j < n and board[i][j] == player:
count += 1
else:
count = 0
if count >= 5:
return true
检查副对角线
for k in range(-n+1, n):
count = 0
for i in range(n):
j = i - k
if j >= 0 and j < n and board[i][j] == player:
count += 1
else:
count = 0
if count >= 5:
return true
return false
游戏主循环
def play_game(n):
board = init_board(n)
players = [1, 2]
cur_player = 1
while true:
print(&34;当前棋盘状态:&34;)
print(board)
move_str = input(&34;玩家{}请输入你要下的位置,格式为x,y:&34;format(cur_player))
move = tuple(map(int, move_strsplit(&34;,&34;)))
if move[0] >= n or move[1] >= n:
print(&34;输入的位置不合法,请重新输入&34;)
continue
if not move(board, move, cur_player):
print(&34;该位置已有棋子,请重新输入&34;)
continue
if check_win(board, cur_player):
print(&34;恭喜玩家{}获得胜利!&34;format(cur_player))
break
cur_player = players[(playersindex(cur_player)+1) len(players)]
if __name__ == &39;__main__&39;:
play_game(15)
```
这段代码使用了 numpy 库来创建和操作二维数组,实现了一个简单的五子棋游戏。其中 init_board 函数用来初始化棋盘,is_valid 函数用来判断某个位置是否合法,check_win 函数用来判断胜利条件,move 函数用来下棋。在 play_game 函数中,我们不断循环玩家的输入,直到有一方获得胜利或者平局。