Python编写五子棋游戏
时间: 2023-07-11 20:33:07 浏览: 98
Python 五子棋小游戏 Python源码
好的,下面是一个简单的五子棋游戏的 Python 代码:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 判断是否胜利
def check_win(x, y, color):
# 判断横向是否连续五个棋子
count = 1
for i in range(x-1, -1, -1):
if board[i][y] == color:
count += 1
else:
break
for i in range(x+1, BOARD_SIZE):
if board[i][y] == color:
count += 1
else:
break
if count >= 5:
return True
# 判断纵向是否连续五个棋子
count = 1
for j in range(y-1, -1, -1):
if board[x][j] == color:
count += 1
else:
break
for j in range(y+1, BOARD_SIZE):
if board[x][j] == color:
count += 1
else:
break
if count >= 5:
return True
# 判断左上到右下是否连续五个棋子
count = 1
for i, j in zip(range(x-1, -1, -1), range(y-1, -1, -1)):
if board[i][j] == color:
count += 1
else:
break
for i, j in zip(range(x+1, BOARD_SIZE), range(y+1, BOARD_SIZE)):
if board[i][j] == color:
count += 1
else:
break
if count >= 5:
return True
# 判断左下到右上是否连续五个棋子
count = 1
for i, j in zip(range(x+1, BOARD_SIZE), range(y-1, -1, -1)):
if board[i][j] == color:
count += 1
else:
break
for i, j in zip(range(x-1, -1, -1), range(y+1, BOARD_SIZE)):
if board[i][j] == color:
count += 1
else:
break
if count >= 5:
return True
return False
# 打印棋盘
def print_board():
print(" ", end="")
for i in range(BOARD_SIZE):
print(chr(ord('A')+i), end=" ")
print()
for i in range(BOARD_SIZE):
print("{:2d}".format(i+1), end="")
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
print(" ", end="")
elif board[i][j] == BLACK:
print("●", end="")
else:
print("○", end="")
if j < BOARD_SIZE - 1:
print(" ", end="")
print()
# 主函数
def main():
print("欢迎来到五子棋游戏!")
print("游戏规则:先手执黑,后手执白,谁先连成五个棋子谁胜利。")
print_board()
color = BLACK
while True:
if color == BLACK:
print("请黑方落子:")
else:
print("请白方落子:")
move = input()
x = ord(move[0].upper()) - ord('A')
y = int(move[1:]) - 1
if board[x][y] != EMPTY:
print("该位置已经有棋子了,请重新落子!")
continue
board[x][y] = color
if check_win(x, y, color):
print_board()
if color == BLACK:
print("黑方胜利!")
else:
print("白方胜利!")
break
print_board()
color = WHITE if color == BLACK else BLACK
if __name__ == "__main__":
main()
```
这个程序使用 `numpy` 模块定义了一个 `BOARD_SIZE × BOARD_SIZE` 的二维数组 `board` 来表示棋盘状态,通过 `check_win` 函数判断是否胜利,通过 `print_board` 函数打印棋盘状态。主函数通过不断的输入落子位置,更新棋盘状态并判断胜利条件,最终输出胜利方。
通过这个简单的五子棋游戏,你可以熟悉 Python 中的二维数组和字符串处理,加深对条件判断和循环语句的理解。
阅读全文