编写一个字符界面的五子棋人机对战程序。
时间: 2023-10-11 18:09:55 浏览: 78
好的,下面是一个简单的字符界面的五子棋人机对战程序,使用 Python 语言编写:
```python
import random
# 定义棋盘大小
SIZE = 15
# 定义棋子类型
NONE = 0
BLACK = 1
WHITE = 2
# 初始化棋盘
board = [[NONE for i in range(SIZE)] for j in range(SIZE)]
# 判断某个位置是否在棋盘内
def is_valid(x, y):
return x >= 0 and x < SIZE and y >= 0 and y < SIZE
# 判断某个位置是否为空
def is_empty(x, y):
return board[x][y] == NONE
# 判断某个位置是否为黑子
def is_black(x, y):
return board[x][y] == BLACK
# 判断某个位置是否为白子
def is_white(x, y):
return board[x][y] == WHITE
# 判断是否有五子连珠
def has_five_in_a_row(color, x, y):
count = 1
for i in range(1, 5):
if is_valid(x+i, y) and color == board[x+i][y]:
count += 1
else:
break
if count >= 5:
return True
for i in range(1, 5):
if is_valid(x-i, y) and color == board[x-i][y]:
count += 1
else:
break
if count >= 5:
return True
count = 1
for i in range(1, 5):
if is_valid(x, y+i) and color == board[x][y+i]:
count += 1
else:
break
if count >= 5:
return True
for i in range(1, 5):
if is_valid(x, y-i) and color == board[x][y-i]:
count += 1
else:
break
if count >= 5:
return True
count = 1
for i in range(1, 5):
if is_valid(x+i, y+i) and color == board[x+i][y+i]:
count += 1
else:
break
if count >= 5:
return True
for i in range(1, 5):
if is_valid(x-i, y-i) and color == board[x-i][y-i]:
count += 1
else:
break
if count >= 5:
return True
count = 1
for i in range(1, 5):
if is_valid(x+i, y-i) and color == board[x+i][y-i]:
count += 1
else:
break
if count >= 5:
return True
for i in range(1, 5):
if is_valid(x-i, y+i) and color == board[x-i][y+i]:
count += 1
else:
break
if count >= 5:
return True
return False
# 判断是否已经下满棋子
def is_full():
for i in range(SIZE):
for j in range(SIZE):
if board[i][j] == NONE:
return False
return True
# 打印棋盘
def print_board():
print(" ", end="")
for i in range(SIZE):
print(" %d" % i, end="")
print("")
for i in range(SIZE):
print("%d " % i, end="")
for j in range(SIZE):
if board[i][j] == NONE:
print(". ", end="")
elif board[i][j] == BLACK:
print("X ", end="")
elif board[i][j] == WHITE:
print("O ", end="")
print("")
# 人机对战
def play():
print("欢迎来到五子棋游戏!")
print("您将执黑先行,电脑将执白后行。")
print("请输入您的下棋坐标,例如 3,4。")
while True:
print_board()
x, y = input("请输入您的下棋坐标:").split(",")
x = int(x)
y = int(y)
if not is_valid(x, y):
print("输入的坐标不合法,请重新输入!")
continue
if not is_empty(x, y):
print("该位置已经有棋子,请重新输入!")
continue
board[x][y] = BLACK
if has_five_in_a_row(BLACK, x, y):
print_board()
print("您赢了!")
break
if is_full():
print_board()
print("平局!")
break
print("电脑正在思考中......")
while True:
x = random.randint(0, SIZE-1)
y = random.randint(0, SIZE-1)
if is_empty(x, y):
break
board[x][y] = WHITE
if has_five_in_a_row(WHITE, x, y):
print_board()
print("电脑赢了!")
break
if is_full():
print_board()
print("平局!")
break
# 运行程序
play()
```
该程序使用随机算法实现电脑下棋,可以适当增加算法复杂度以提高游戏难度。此外,也可以使用其他算法实现更加智能的电脑下棋,例如 AlphaGo 等。
阅读全文