帮我用python写一个五子棋游戏
时间: 2023-09-13 07:05:17 浏览: 108
### 回答1:
好的,以下是一个简单的五子棋游戏的 Python 代码:
```
import numpy as np
BOARD_SIZE = 15
EMPTY = 0
BLACK = 1
WHITE = 2
class Board:
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
self.current_player = BLACK
def place(self, row, col):
if self.board[row][col] != EMPTY:
return False
self.board[row][col] = self.current_player
return True
def switch_player(self):
if self.current_player == BLACK:
self.current_player = WHITE
else:
self.current_player = BLACK
def check_win(self):
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
color = self.board[r][c]
if color == EMPTY:
continue
# check horizontal
if c <= BOARD_SIZE - 5 and len(set(self.board[r][c:c+5])) == 1:
return color
# check vertical
if r <= BOARD_SIZE - 5 and len(set(self.board[r:r+5, c])) == 1:
return color
# check diagonal right and down
if r <= BOARD_SIZE - 5 and c <= BOARD_SIZE - 5 and \
len(set([self.board[r+i][c+i] for i in range(5)])) == 1:
return color
# check diagonal left and down
if r <= BOARD_SIZE - 5 and c >= 4 and \
len(set([self.board[r+i][c-i] for i in range(5)])) == 1:
return color
return None
def __str__(self):
symbol = ['.', 'X', 'O']
rows = []
for r in range(BOARD_SIZE):
row = ''
for c in range(BOARD_SIZE):
row += symbol[self.board[r][c]]
rows.append(row)
return '\n'.join(rows)
if __name__ == '__main__':
board = Board()
while True:
print(board)
if board.current_player == BLACK:
move = input('Black to move (row,col): ').split(',')
else:
move = input('White to move (row,col): ').split(',')
row = int(move[0])
col = int(move[1])
if not board.place(row, col):
print('Invalid move.')
continue
winner = board.check_win()
if winner is not None:
print(board)
print('Winner:', 'Black' if winner == BLACK else 'White')
break
board.switch_player()
```
这个代码实现了一个简单的五子棋游戏,玩家可以在命令行中输入行号和列号来落子。当有任意一方获胜时,游戏结束。
### 回答2:
好的,下面是一个用Python写的简化版五子棋游戏代码:
```python
import numpy as np
# 生成棋盘
def create_board():
board = np.zeros((15, 15))
return board
# 判断当前位置是否合法
def is_valid_move(board, x, y):
if x < 0 or x >= 15 or y < 0 or y >= 15 or board[x][y] != 0:
return False
return True
# 判断是否有玩家获胜
def is_winner(board, player):
# 判断横向是否有五子连线
for i in range(11):
for j in range(15):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 判断纵向是否有五子连线
for i in range(15):
for j in range(11):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 判断左上到右下斜向是否有五子连线
for i in range(11):
for j in range(11):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
# 判断右上到左下斜向是否有五子连线
for i in range(11):
for j in range(4, 15):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player and board[i+4][j-4] == player:
return True
return False
# 打印棋盘
def print_board(board):
for i in range(15):
for j in range(15):
print(int(board[i][j]), end=' ')
print()
# 主函数
def main():
board = create_board()
player = 1
print_board(board)
while True:
if player == 1:
print("玩家1下棋")
else:
print("玩家2下棋")
x = int(input("请输入横坐标:"))
y = int(input("请输入纵坐标:"))
if is_valid_move(board, x, y):
board[x][y] = player
print_board(board)
if is_winner(board, player):
if player == 1:
print("玩家1获胜!")
else:
print("玩家2获胜!")
break
else:
player = 2 if player == 1 else 1
else:
print("无效的移动,请重新选择位置!")
if __name__ == '__main__':
main()
```
这段代码使用了一个15x15的二维数组来表示棋盘,1代表玩家1的棋子,2代表玩家2的棋子,0代表空格。
玩家可以通过输入横纵坐标来下棋,程序会判断下棋位置是否合法,并判断是否有玩家获胜,最后打印出获胜的玩家。
### 回答3:
当然可以!下面是一个使用Python编写的简单五子棋游戏的示例代码:
```python
import sys
# 初始化游戏板
board = [[' ' for _ in range(15)] for _ in range(15)]
player = 'X' # 玩家选择作为X
game_over = False
# 打印游戏板
def print_board():
for row in board:
print("|".join(row))
print("-" * 29)
# 检查游戏是否结束
def check_game_over(row, col):
global game_over
# 检查行
if all(board[row][i] == player for i in range(15)):
game_over = True
# 检查列
if all(board[i][col] == player for i in range(15)):
game_over = True
# 检查对角线1
if row - col == 0:
if all(board[i][i] == player for i in range(15)):
game_over = True
# 检查对角线2
if row + col == 14:
if all(board[i][14-i] == player for i in range(15)):
game_over = True
# 游戏主循环
while not game_over:
print_board()
try:
row = int(input("请输入行数(1-15):")) - 1
col = int(input("请输入列数(1-15):")) - 1
except ValueError:
print("输入无效,请重新输入!")
continue
if row < 0 or row > 14 or col < 0 or col > 14:
print("输入无效,请重新输入!")
continue
if board[row][col] != ' ':
print("该位置已被占用,请重新输入!")
continue
board[row][col] = player
check_game_over(row, col)
if player == 'X':
player = 'O'
else:
player = 'X'
print_board()
print("恭喜{0}获胜!".format(player))
```
使用这段代码,您可以和计算机对战五子棋。请注意,此代码只是一个简单的示例,并且没有考虑游戏结束后的处理(如重玩或退出游戏)。您可以根据需要进行改进和扩展。
阅读全文