在开始之前,让我们先了解一下什么是连接四游戏。它是一种双人连线棋盘游戏,玩家选择一种颜色,然后轮流将彩色圆盘投放到一个七列六行垂直悬挂的网格中。棋子直接落下,占据列内最低的可用空间。
游戏的目的是最先将自己的四个棋子排成水平、垂直或对角线。四子连环是一种解谜游戏。
第一个玩家只要走对一步棋,就能永远获胜。听起来很有趣吧?让我们来了解一下如何用 python 编程语言编码这个游戏。
导入四连棋游戏所需的库
1. NumPy 模块
NumPy 库:NumPy 是 Numerical Python 的缩写。NumPy 是一个用于处理数组的 Python 库。它还具有线性代数、傅里叶变换和矩阵等领域的函数。它是一个开源项目,你可以免费使用。NumPy 是一个 Python 库,它提供了一个简单而强大的数据结构:n 维数组。
如果系统中尚未预装 NumPy,请在窗口的 cmd 中键入以下命令:
pip install numpy
当你调用 import numpy as np 语句时,你是在将 "numpy "缩短为 “np”,以使你的代码更容易阅读。这还有助于避免命名空间问题。
import numpy as np
2. Pygame 模块
Pygame 是一个免费开源的跨平台库,用于使用 Python 开发视频游戏等多媒体应用程序。
它使用简单直接媒体层库(Simple DirectMedia Layer)和其他几个流行的库来抽象最常用的功能,使编写这些程序变得更加直观。
如果您的系统中还没有预装 Pygame,请在窗口的 cmd 中键入以下命令:
pip install pygame
3. Python sys 模块
python sys 模块提供了用于操作 Python 运行环境不同部分的函数和变量。它允许我们访问特定于系统的参数和函数。首先,在运行任何函数之前,我们必须在程序中导入 sys 模块。
4.Python math模块
数学模块中定义了一些最常用的数学函数。这些函数包括三角函数、表示函数、对数函数、角度转换函数等。此外,该模块还定义了两个数学常量。
如果系统中没有预装数学模块,请在窗口的 cmd.Ctrl 中键入以下命令:
pip install maths
用 Python 实现四连棋游戏
步骤 01
以 np 的形式导入 NumPy 软件包。然后,我们将创建一个名为 create_board( ) 的 python 函数。
np.zeros( ) 函数用于创建一个充满零的矩阵。Python 中的这个函数可以在 TensorFlow 和其他统计任务中的第一次迭代中初始化权重时使用。((6,7)) 是维数。6 行 7 列。然后我们只需返回该棋盘即可。
我们现在开始编写主游戏循环。我们将创建一个 while not game_over 循环。while not 循环会重复执行循环体,直到满足循环终止的条件。只要 game_over 变量为 false,我们的循环就会运行。我们将把 game_over 初始化为 false。只有当有人连续获得 4 个圆圈时,它才会转换为 true。
要将回合数增加 1,我们将使用 turn +=1。要在玩家 1 和玩家 2 之间交替切换,我们使用 turn = turn % 2。
import numpy as np
def create_board():
board = np.zeros((6,7))
return board
#initialize board
board = create_board()
#We will initialize the game_over as False.
game_over = False
turn = 0
while not game_over:
#Ask for player 1 input
if turn == 0:
selection = int(input("Player 1, Make your Selection(0-6):"))
#Ask for player 2 input
else:
selection = int(input("Player 2, Make your Selection(0-6):"))
turn += 1
turn = turn % 2
步骤 02
在步骤 02 中,我们对之前的代码进行了一些修改和更新。
我们希望选择变量能真正将棋子落到棋盘上。为此,我们首先要创建另外三个函数,分别叫做 def drop_piece()、def is_valid_location( ) 和 def get_next_open_row()。
这些函数的工作原理如下:玩家将进行选择。代码中的(0-6)代表玩家想要投放棋子的列。因此,我们将选择变量的名称更新为列变量(col)。
现在,我们将在当前棋盘中使用该列变量,并将其作为参数传递给带有棋盘的所有三个函数。
我们将初始化名为 ROW_COUNT 和 COLUMN_COUNT 的全局变量。在 Python 中,在函数之外或全局范围内声明的变量称为全局变量。这意味着全局变量可以在函数内部或外部被访问。
np.flip( ) 函数沿指定的轴颠倒数组元素的顺序,保留数组的形状。
Syntax: np.flip(array, axis)
import numpy as np
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = np.zeros((6,7))
return board
def drop_piece(board,row,col,piece):
board[row][col]= piece
def is_valid_location(board,col):
#if this condition is true we will let the use drop piece here.
#if not true that means the col is not vacant
return board[5][col]==0
def get_next_open_row(board,col):
for r in range(ROW_COUNT):
if board[r][col]==0:
return r
def print_board(board):
print(np.flip(board,0))
board = create_board()
print_board(board)
game_over = False
turn = 0
while not game_over:
#Ask for player 1 input
if turn == 0:
col = int(input("Player 1, Make your Selection(0-6):"))
#Player 1 will drop a piece on the board
if is_valid_location(board,col):
row = get_next_open_row(board,col)
drop_piece(board,row,col,1)
#Ask for player 2 input
else:
col = int(input("Player 2, Make your Selection(0-6):"))
#Player 2 will drop a piece on the board
if is_valid_location(board,col):
row = get_next_open_row(board,col)
drop_piece(board,row,col,2)
print_board(board)
turn += 1
turn = turn % 2
步骤 03:完整代码演练
在步骤 03 中,我们将创建一个带图形用户界面的游戏,而不仅仅是带矩阵的游戏。上述代码和我们所做的新修改将使游戏看起来像一个真正的棋盘游戏。
首先,我们将导入所有必要的库。
接下来,我们将把蓝色、黑色、红色和黄色定义为全局静态变量。这些值将是 rgb 值。
我们将初始化名为 ROW_COUNT 和 COLUMN_COUNT 的全局变量。行数为 6,列数为 7。
然后我们创建 5 个函数,分别名为 create_board()、drop_piece()、is_valid_location()、get_next_open_row( ) 和 print_board()。
然后,我们创建一个名为 winning_move() 的函数,并检查水平位置是否获胜、垂直位置是否获胜、正斜对角线和负斜对角线是否获胜。
在水平和垂直位置,我们为行和列创建一个嵌套的 for 循环,并检查 if 条件语句,查看棋子是否已落到棋盘上的该位置。如果 if 条件满足,则返回 TRUE。我们还将对垂直位置、正斜对角线和负斜线重复同样的步骤。
在函数 def draw_board( ) 中,pygame.draw 是一个绘制图形的模块。
pygame.draw.rect 用于绘制矩形。现在我们将定义三角形。定义高度、宽度和位置。
因此,位置将是 cSQUARESIZE,Y 轴的位置将是 rSQUARESIZE+SQUARESIZE。
另外两个参数是高度和宽度,即 SQUARESIZE、SQUARESIZE。对圆形也重复同样的步骤。
import numpy as np
import pygame
import sys
import math
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = np.zeros((ROW_COUNT,COLUMN_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# Check horizontal locations for win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check vertical locations for win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if board[r][c] == 1:
pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
elif board[r][c] == 2:
pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
board = create_board()
print_board(board)
game_over = False
turn = 0
#initalize pygame
pygame.init()
#define our screen size
SQUARESIZE = 100
#define width and height of board
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
#Calling function draw_board again
draw_board(board)
pygame.display.update()
myfont = pygame.font.SysFont("monospace", 75)
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
posx = event.pos[0]
if turn == 0:
pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
else:
pygame.draw.circle(screen, YELLOW, (posx, int(SQUARESIZE/2)), RADIUS)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
#print(event.pos)
# Ask for Player 1 Input
if turn == 0:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1)
if winning_move(board, 1):
label = myfont.render("Player 1 wins!!", 1, RED)
screen.blit(label, (40,10))
game_over = True
# # Ask for Player 2 Input
else:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2)
if winning_move(board, 2):
label = myfont.render("Player 2 wins!!", 1, YELLOW)
screen.blit(label, (40,10))
game_over = True
print_board(board)
draw_board(board)
turn += 1
turn = turn % 2
if game_over:
pygame.time.wait(3000)
结束语…
这就是如何用 Python 编写著名的四连线游戏代码的完整解释。Pygame 可以让用户轻松学习和编码许多游戏。我希望你一定会尝试编码这个游戏,并享受你自己创建的游戏。