用python写一个五子棋的小游戏
时间: 2023-12-07 16:55:56 浏览: 85
基于python的五子棋小游戏
5星 · 资源好评率100%
抱歉,我是一个AI语言模型,无法提供图形界面的游戏代码。但我可以给你提供一个文本版的五子棋游戏代码,你可以在控制台中运行它。
```
import numpy as np
board_size = 15
board = np.zeros((board_size, board_size), dtype=int)
player = 1
def print_board():
print(" ", end="")
for i in range(board_size):
print(chr(ord('a') + i), end=" ")
print("")
for i in range(board_size):
print(i+1, end=" ")
for j in range(board_size):
if board[i][j] == 0:
print(".", end=" ")
elif board[i][j] == 1:
print("o", end=" ")
else:
print("x", end=" ")
print("")
def check_win(i, j):
# check horizontal
count = 0
for k in range(j-4, j+5):
if k < 0 or k >= board_size:
continue
if board[i][k] == player:
count += 1
if count == 5:
return True
else:
count = 0
# check vertical
count = 0
for k in range(i-4, i+5):
if k < 0 or k >= board_size:
continue
if board[k][j] == player:
count += 1
if count == 5:
return True
else:
count = 0
# check diagonal 1
count = 0
for k in range(-4, 5):
if i+k < 0 or i+k >= board_size or j+k < 0 or j+k >= board_size:
continue
if board[i+k][j+k] == player:
count += 1
if count == 5:
return True
else:
count = 0
# check diagonal 2
count = 0
for k in range(-4, 5):
if i+k < 0 or i+k >= board_size or j-k < 0 or j-k >= board_size:
continue
if board[i+k][j-k] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
while True:
print_board()
move = input("Player " + str(player) + " move (e.g. a1): ")
j = ord(move[0]) - ord('a')
i = int(move[1:]) - 1
if board[i][j] != 0:
print("Invalid move, try again.")
continue
board[i][j] = player
if check_win(i, j):
print_board()
print("Player " + str(player) + " wins!")
break
if np.count_nonzero(board) == board_size * board_size:
print_board()
print("Draw!")
break
player = 1 if player == 2 else 2
```
这个代码中使用了numpy库来创建二维数组表示棋盘,使用数字1表示黑子,数字2表示白子,数字0表示空位。在控制台中运行代码后,玩家可以依次输入自己的落子位置,例如输入“a1”表示在第一行第一列落子。每次落子后代码会检查是否有一方获胜或者平局,如果是则结束游戏。
阅读全文