用Python代码设计一个和电脑对战的五子棋游戏
时间: 2023-06-17 08:04:30 浏览: 103
好的,下面是一个简单的五子棋游戏的代码,你可以在自己的电脑上运行它:
```python
import numpy as np
def create_board():
board = np.zeros((15, 15))
return board
def is_valid_move(board, row, col):
return board[row][col] == 0
def get_next_move(board):
while True:
row = int(input("Enter row number (0-14): "))
col = int(input("Enter column number (0-14): "))
if is_valid_move(board, row, col):
return row, col
else:
print("Invalid move, please try again.")
def is_game_over(board, row, col):
# check row
count = 0
for i in range(15):
if board[row][i] == board[row][col]:
count += 1
else:
count = 0
if count == 5:
return True
# check column
count = 0
for i in range(15):
if board[i][col] == board[row][col]:
count += 1
else:
count = 0
if count == 5:
return True
# check diagonal
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col+i < 0 or col+i > 14:
continue
if board[row+i][col+i] == board[row][col]:
count += 1
else:
count = 0
if count == 5:
return True
# check anti-diagonal
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col-i < 0 or col-i > 14:
continue
if board[row+i][col-i] == board[row][col]:
count += 1
else:
count = 0
if count == 5:
return True
return False
def print_board(board):
print(" ", end="")
for i in range(15):
print("{:2d}".format(i), end=" ")
print()
for i in range(15):
print("{:2d}".format(i), 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_board(board)
player = 1
while True:
print("Player {}'s turn".format(player))
row, col = get_next_move(board)
board[row][col] = player
print_board(board)
if is_game_over(board, row, col):
print("Player {} wins!".format(player))
break
if player == 1:
player = 2
else:
player = 1
if __name__ == "__main__":
play_game()
```
这个代码实现了一个简单的交互式五子棋游戏,你可以通过输入行和列来下棋,电脑会检查你的落子是否有效,并且根据你的落子判断游戏是否结束。
这个代码可以作为一个起点,你可以根据自己的需要进行调整和扩展,比如增加一个 AI 程序来与玩家对战。
阅读全文