你用python写一个象棋游戏
时间: 2023-05-11 09:04:21 浏览: 121
Chess-Project:尝试编写基于Python的国际象棋游戏
好的,我可以为您提供一个简单的象棋游戏的 Python 代码示例,如下所示:
```python
# 导入必要的模块
import random
# 定义棋盘大小
BOARD_SIZE = 9
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义棋盘
board = [[EMPTY for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)]
# 定义落子函数
def make_move(player, x, y):
if board[x][y] == EMPTY:
board[x][y] = player
return True
else:
return False
# 定义判断胜负函数
def is_win(player):
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if board[x][y] == player:
if (x <= BOARD_SIZE - 5 and
board[x+1][y] == player and
board[x+2][y] == player and
board[x+3][y] == player and
board[x+4][y] == player):
return True
if (y <= BOARD_SIZE - 5 and
board[x][y+1] == player and
board[x][y+2] == player and
board[x][y+3] == player and
board[x][y+4] == player):
return True
if (x <= BOARD_SIZE - 5 and y <= BOARD_SIZE - 5 and
board[x+1][y+1] == player and
board[x+2][y+2] == player and
board[x+3][y+3] == player and
board[x+4][y+4] == player):
return True
if (x >= 4 and y <= BOARD_SIZE - 5 and
board[x-1][y+1] == player and
board[x-2][y+2] == player and
board[x-3][y+3] == player and
board[x-4][y+4] == player):
return True
return False
# 定义主函数
def main():
# 随机先手
player = random.choice([BLACK, WHITE])
while True:
# 打印棋盘
for y in range(BOARD_SIZE):
for x in range(BOARD_SIZE):
if board[x][y] == EMPTY:
print(".", end=" ")
elif board[x][y] == BLACK:
print("X", end=" ")
elif board[x][y] == WHITE:
print("O", end=" ")
print()
# 判断胜负
if is_win(player):
print("Player", player, "wins!")
break
# 提示玩家落子
print("Player", player, "make a move:")
x = int(input("x: "))
y = int(input("y: "))
if make_move(player, x, y):
# 切换玩家
player = BLACK if player == WHITE else WHITE
else:
print("Invalid move, try again.")
# 运行主函数
if __name__ == "__main__":
main()
```
请注意,这只是一个简单的示例,可能还有很多需要改进的地方。
阅读全文