帮我用Python写一个五子棋小游戏
时间: 2023-12-07 18:17:10 浏览: 97
基于python的五子棋小游戏
5星 · 资源好评率100%
好的,以下是一个简单的五子棋游戏 Python 代码,希望可以帮到你:
```python
# 定义棋盘大小
ROWS = 15
COLS = 15
# 棋盘数组
board = [['-' for j in range(COLS)] for i in range(ROWS)]
# 用于记录当前玩家
currentPlayer = 'X'
# 初始化棋盘
def initBoard():
for i in range(ROWS):
for j in range(COLS):
board[i][j] = '-'
# 打印棋盘
def printBoard():
for i in range(ROWS):
for j in range(COLS):
print(board[i][j], end=' ')
print()
# 判断当前位置是否可落子
def isValidMove(row, col):
if row < 0 or row >= ROWS or col < 0 or col >= COLS:
return False
if board[row][col] != '-':
return False
return True
# 判断是否有玩家获胜
def isWin():
# 横向检查
for i in range(ROWS):
count = 0
for j in range(COLS):
if board[i][j] == currentPlayer:
count += 1
if count == 5:
return True
else:
count = 0
# 纵向检查
for j in range(COLS):
count = 0
for i in range(ROWS):
if board[i][j] == currentPlayer:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下斜线检查
for i in range(ROWS - 4):
for j in range(COLS - 4):
count = 0
while count < 5 and board[i + count][j + count] == currentPlayer:
count += 1
if count == 5:
return True
# 左下到右上斜线检查
for i in range(4, ROWS):
for j in range(COLS - 4):
count = 0
while count < 5 and board[i - count][j + count] == currentPlayer:
count += 1
if count == 5:
return True
return False
# 主函数
def main():
initBoard()
printBoard()
while True:
row, col = map(int, input("玩家 %s,请输入您要落子的位置(格式为 行 列,例如:3 4):" % currentPlayer).split())
if isValidMove(row, col):
board[row][col] = currentPlayer
printBoard()
if isWin():
print("恭喜玩家 %s 获胜!" % currentPlayer)
break
if currentPlayer == 'X':
currentPlayer = 'O'
else:
currentPlayer = 'X'
else:
print("无效的位置,请重新输入。")
if __name__ == '__main__':
main()
```
该代码实现了一个简单的五子棋游戏,可以在控制台中运行。玩家轮流落子,当有任意一方连成五子时,游戏结束并宣布胜利者。
阅读全文