不使用库,设计一个python五子棋代码
时间: 2024-05-01 14:23:09 浏览: 97
python课程作业设计五子棋游戏源代码.zip
以下是一个简单的五子棋代码示例,主要使用了Python的基础语法:
```python
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘
board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
# 定义落子函数
def play(x, y, player):
if board[x][y] == 0:
board[x][y] = player
return True
return False
# 定义判断胜负函数
def is_win(player):
# 判断行
for i in range(BOARD_SIZE):
if all(board[i][j] == player for j in range(BOARD_SIZE)):
return True
# 判断列
for j in range(BOARD_SIZE):
if all(board[i][j] == player for i in range(BOARD_SIZE)):
return True
# 判断对角线
if all(board[i][i] == player for i in range(BOARD_SIZE)):
return True
if all(board[i][BOARD_SIZE - i - 1] == player for i in range(BOARD_SIZE)):
return True
return False
# 定义主函数
def main():
player = 1
while True:
# 打印棋盘
for row in board:
print(row)
# 输入坐标
x, y = map(int, input("Player %d's turn. Enter x, y: " % player).split())
# 落子
if play(x, y, player):
# 判断胜负
if is_win(player):
print("Player %d wins!" % player)
return
# 切换玩家
player = 3 - player
else:
print("Invalid move, try again.")
if __name__ == '__main__':
main()
```
该代码实现了基本的五子棋规则,包括棋盘大小、落子、判断胜负等功能。运行代码后,会要求两名玩家交替输入落子坐标。当一方获胜时,会打印出胜利者的信息并结束游戏。
阅读全文