使用Python语言实现一个简单的五子棋程序
使用Python语言实现一个简单的五子棋程序
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15), dtype=int)
return board
# 判断落子是否合法
def is_valid_move(board, x, y):
# 落子位置不为空
if board[x][y] != 0:
return False
return True
# 判断胜者,返回1为黑方赢,2为白方赢,0为平局
def get_winner(board):
# 判断列
for i in range(15):
for j in range(11):
if board[j][i] == board[j + 1][i] == board[j + 2][i] == board[j + 3][i] == board[j + 4][i] and board[j][i] != 0:
return board[j][i]
# 判断行
for i in range(15):
for j in range(11):
if board[i][j] == board[i][j + 1] == board[i][j + 2] == board[i][j + 3] == board[i][j + 4] and board[i][j] != 0:
return board[i][j]
# 判断右上斜线
for i in range(11):
for j in range(11):
if board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2] == board[i + 3][j + 3] == board[i + 4][j + 4] and board[i][j] != 0:
return board[i][j]
# 判断左上斜线
for i in range(11):
for j in range(4, 15):
if board[i][j] == board[i + 1][j - 1] == board[i + 2][j - 2] == board[i + 3][j - 3] == board[i + 4][j - 4] and board[i][j] != 0:
return board[i][j]
# 平局
if np.count_nonzero(board) == 15 * 15:
return 0
# 游戏未结束
return -1
# 下棋
def move(board, x, y, player):
if is_valid_move(board, x, y):
board[x][y] = player
return True
else:
return False
# 人机对战
def play_with_computer():
player = 1
board = init_board()
while True:
print("棋盘:")
print(board)
if player == 1:
x = int(input("黑方,请输入落子的横坐标:"))
y = int(input("黑方,请输入落子的纵坐标:"))
else:
print("白方正在思考...")
x, y = computer_move(board)
print("白方选择了:", x, y)
if not move(board, x, y, player):
print("落子失败,请重新输入")
continue
winner = get_winner(board)
if winner != -1:
print("游戏结束!")
if winner == 0:
print("平局")
elif winner == 1:
print("黑方胜利!")
else:
print("白方胜利!")
break
player = 3 - player
# 计算电脑落子
def computer_move(board):
for i in range(15):
for j in range(15):
if board[i][j] == 0:
if is_valid_move(board, i, j):
return i, j
return -1, -1
# 演示
if __name__ == "__main__":
play_with_computer()
这个程序实现了一个简单的五子棋游戏,并可以进行人机对战。其中`init_board()`函数用于初始化棋盘,`is_valid_move()`函数判断落子是否合法,`get_winner()`函数判断胜者,`move()`函数实现下棋,`play_with_computer()`函数实现人机对战,`computer_move()`函数用于计算电脑落子。程序使用了`numpy`库来实现棋盘,方便处理二维数组。
共有 0 条评论