五子棋小游戏python
时间: 2023-06-22 12:37:07 浏览: 106
好的,我可以为您提供五子棋小游戏的Python代码。以下是一个简单的示例,您可以根据自己的需求进行修改:
```python
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def place(board, player, position):
if board[position] == 0:
board[position] = player
else:
print("This position is already occupied. Please try again.")
position = tuple(map(int, input("Player " + str(player) + ", please enter a different position (row,column): ").split(",")))
place(board, player, position)
def check_win(board, player):
# Check rows for a win
for row in range(15):
if board[row][0] == player and board[row][1] == player and board[row][2] == player and board[row][3] == player and board[row][4] == player:
return True
# Check columns for a win
for col in range(15):
if board[0][col] == player and board[1][col] == player and board[2][col] == player and board[3][col] == player and board[4][col] == player:
return True
# Check diagonals for a win
if board[0][0] == player and board[1][1] == player and board[2][2] == player and board[3][3] == player and board[4][4] == player:
return True
if board[0][4] == player and board[1][3] == player and board[2][2] == player and board[3][1] == player and board[4][0] == player:
return True
return False
def print_board(board):
print(" ", end="")
for i in range(15):
print(chr(i + ord('a')), end=" ")
print()
for i in range(15):
print("{0:2d}".format(i+1), end=" ")
for j in range(15):
if board[i][j] == 0:
print(".", end=" ")
elif board[i][j] == 1:
print("X", end=" ")
else:
print("O", end=" ")
print()
def play_game():
board = create_board()
print("Welcome to Five in a Row!")
print_board(board)
for player in [1, 2]:
while True:
position = tuple(map(int, input("Player " + str(player) + ", please enter a position to place your piece (row,column): ").split(",")))
place(board, player, position)
print_board(board)
if check_win(board, player):
print("Congratulations, Player " + str(player) + "! You have won the game!")
return
```
您可以将此代码复制并粘贴到Python解释器中,然后运行 play_game() 函数以开始游戏。希望这能对您有所帮助!