python小游戏开心消消乐制作10完结篇-搜索两个元素之间的连接路径


前言

在上一章中,介绍了在消消乐中连接路径如何判定,什么是广度优先搜索算法,它的作用。在本章中我们将会将使用广度优先搜索算法来搜索两个元素之间的连接路径。

一、扩展节点

由上一章我们可以看到每个元素可以扩展的节点是与其相邻的上下左右的节点。
同时我们也可以看到在边缘的元素节点扩展的节点是有限的。
1、中间节点的扩展节点有四个节点,分别为上下左右
2、四个角节点的扩展节点只有两个节点
3、边节点的扩展节点有三个节点
我们可以在GameBlock类中单独定义一个扩展节点函数expandNode

	def expandNode(self,node):
		neighbors = []
		if node[1] < self.blocks_type.shape[1]-1:#节点上方还有节点则可以扩展上方节点
			neighbors.append((node[0],node[1]+1))
		if node[1] > 0:#节点下方还有节点则可以扩展下方节点
			neighbors.append((node[0],node[1]-1))
		if node[0] < self.blocks_type.shape[0]-1: #节点右方还有节点则可以扩展右方节点
			neighbors.append((node[0]+1,node[1])) 
		if node[0] > 0:#节点左方还有节点则可以扩展左方节点
			neighbors.append((node[0]-1,node[1]))
		return neighbors

完整代码:

-MagicBlock.py
import pygame
import random
import numpy as np
TYPE_RECT = 0
TYPE_IMAGE = 1

class Block:
	
	def __init__(self,screen,left,top,width,height,type,image=None,color=None):
		self.screen = screen
		self.left = left
		self.top = top
		self.type = type
		self.image = image
		self.color = color
		self.width = width
		self.height = height
		
	def draw(self):
		
		if self.type == TYPE_RECT:
			position = self.left,self.top,self.width,self.height
			pygame.draw.rect(self.screen,self.color,position)
		elif self.type == TYPE_IMAGE:
			self.screen.blit(self.image,(self.left,self.top))

class GameBlock:
	def __init__(self,screen,start_left,start_top,block_height,block_width,row,col,type):
		self.row = row
		self.col = col
		self.screen = screen
		self.start_left = start_left
		self.start_top = start_top
		self.block_width = block_width
		self.block_height = block_height
		self.type = type
		self.blocks=[[0]*self.col for i in range(self.row)]
		self.blocks_type = np.zeros((self.row,self.col),dtype=np.int8)
		self.click_num = 0
		self.click_list = list()
	def initMagicBlock(self):
		for i in range(0,self.row,1):
			for j in range(0,self.col,1):
				if self.type == TYPE_IMAGE:
					self.blocks_type[i][j] = random.randint(1,5)
					self.blocks[i][j] = Block(self.screen,self.start_left+self.block_width*j,self.start_top+self.block_height*i,self.block_width,self.block_height,self.type,image=pygame.image.load('./image/0'+str(self.blocks_type[i][j])+"_hightlight.png"))
					self.blocks[i][j].draw()
				elif self.type == TYPE_RECT:
					self.blocks[i][j] = Block(self.screen,self.start_left+self.block_width*j,self.start_top+self.block_height*i,self.block_width,self.block_height,self.type,color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
					self.blocks[i][j].draw()
	def mouseClick(self,x,y):
		i = (y-self.start_top)//self.block_height
		j = (x-self.start_left)//self.block_width
		if i<0 or i>self.row-1 or j<0 or j >self.col-1 or self.blocks_type[i][j] == 0:
			return False
		if self.click_num %2 == 1 and self.click_list[0][0] == i and self.click_list[0][1] == j:
			return False

		self.click_num += 1
		self.click_list.append([i,j])
		if self.click_num % 2 == 0:

			if self.blocks_type[self.click_list[0][0]][self.click_list[0][1]] == self.blocks_type[self.click_list[1][0]][self.click_list[1][1]]:
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].type = TYPE_RECT
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].color = (255,255,255)
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].draw()#进行重渲染
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].type = TYPE_RECT
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].color = (255,255,255)
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].draw()#进行重渲染
			self.click_list = list()
	
	def expandNode(self,node):
		neighbors = []
		if node[1] < self.blocks_type.shape[1]-1:#节点上方还有节点则可以扩展上方节点
			neighbors.append((node[0],node[1]+1))
		if node[1] > 0:#节点下方还有节点则可以扩展下方节点
			neighbors.append((node[0],node[1]-1))
		if node[0] < self.blocks_type.shape[0]-1: #节点右方还有节点则可以扩展右方节点
			neighbors.append((node[0]+1,node[1])) 
		if node[0] > 0:#节点左方还有节点则可以扩展左方节点
			neighbors.append((node[0]-1,node[1]))
		return neighbors

我们已经可以扩展节点了,接着我们判断是否有连接路径。

二、搜索路径

在上一章的广度优先搜索算法的基础上,我们需要在在访问邻近节点时,将其换成扩展节点。并且需要判断扩展的节点是否为目标节点,将未访问过的节点且可以扩展的节点加入待扩展队列中。

	def breadth_first_search(self,startnode,destinationnode):
		visited = set()#访问过的节点集合
		queue =  deque([tuple(startnode)]) #队列,存储待访问的节点

		while queue:
			node = queue.popleft() #从队列左侧弹出一个节点
			if node not in visited:
                
				visited.add(node)
				for neighbor in self.expandNode(node):
					if tuple(neighbor) == tuple(destinationnode):
						return True 
					if tuple(neighbor) not in visited and self.blocks_type[neighbor[0]][neighbor[1]] == 0:
						queue.append(tuple(neighbor))  # 将未访问的邻居加入队列
		return False

完整代码:

-MagicBlock.py
import pygame
import random
import numpy as np
from collections import deque
TYPE_RECT = 0
TYPE_IMAGE = 1

class Block:
	
	def __init__(self,screen,left,top,width,height,type,image=None,color=None):
		self.screen = screen
		self.left = left
		self.top = top
		self.type = type
		self.image = image
		self.color = color
		self.width = width
		self.height = height
		
	def draw(self):
		
		if self.type == TYPE_RECT:
			position = self.left,self.top,self.width,self.height
			pygame.draw.rect(self.screen,self.color,position)
		elif self.type == TYPE_IMAGE:
			self.screen.blit(self.image,(self.left,self.top))

class GameBlock:
	def __init__(self,screen,start_left,start_top,block_height,block_width,row,col,type):
		self.row = row
		self.col = col
		self.screen = screen
		self.start_left = start_left
		self.start_top = start_top
		self.block_width = block_width
		self.block_height = block_height
		self.type = type
		self.blocks=[[0]*self.col for i in range(self.row)]
		self.blocks_type = np.zeros((self.row,self.col),dtype=np.int8)
		self.click_num = 0
		self.click_list = list()
	def initMagicBlock(self):
		for i in range(0,self.row,1):
			for j in range(0,self.col,1):
				if self.type == TYPE_IMAGE:
					self.blocks_type[i][j] = random.randint(1,5)
					self.blocks[i][j] = Block(self.screen,self.start_left+self.block_width*j,self.start_top+self.block_height*i,self.block_width,self.block_height,self.type,image=pygame.image.load('./image/0'+str(self.blocks_type[i][j])+"_hightlight.png"))
					self.blocks[i][j].draw()
				elif self.type == TYPE_RECT:
					self.blocks[i][j] = Block(self.screen,self.start_left+self.block_width*j,self.start_top+self.block_height*i,self.block_width,self.block_height,self.type,color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
					self.blocks[i][j].draw()
	def mouseClick(self,x,y):
		i = (y-self.start_top)//self.block_height
		j = (x-self.start_left)//self.block_width
		if i<0 or i>self.row-1 or j<0 or j >self.col-1 or self.blocks_type[i][j] == 0:
			return False
		if self.click_num %2 == 1 and self.click_list[0][0] == i and self.click_list[0][1] == j:
			return False

		self.click_num += 1
		self.click_list.append([i,j])
		if self.click_num % 2 == 0:

			if self.blocks_type[self.click_list[0][0]][self.click_list[0][1]] == self.blocks_type[self.click_list[1][0]][self.click_list[1][1]] :
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].type = TYPE_RECT
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].color = (255,255,255)
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].draw()#进行重渲染
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].type = TYPE_RECT
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].color = (255,255,255)
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].draw()#进行重渲染
				self.blocks_type[self.click_list[0][0]][self.click_list[0][1]] = 0
				self.blocks_type[self.click_list[1][0]][self.click_list[1][1]] = 0
			self.click_list = list()
	
	def breadth_first_search(self,startnode,destinationnode):
		visited = set()#访问过的节点集合
		queue =  deque([tuple(startnode)]) #队列,存储待访问的节点

		while queue:
			node = queue.popleft() #从队列左侧弹出一个节点
			if node not in visited:
                
				visited.add(node)
				for neighbor in self.expandNode(node):
					if tuple(neighbor) == tuple(destinationnode):
						return True 
					if tuple(neighbor) not in visited and self.blocks_type[neighbor[0]][neighbor[1]] == 0:
						queue.append(tuple(neighbor))  # 将未访问的邻居加入队列
		return False
	
	def expandNode(self,node):
		neighbors = []
		if node[1] < self.blocks_type.shape[1]-1:#节点上方还有节点则可以扩展上方节点
			neighbors.append((node[0],node[1]+1))
		if node[1] > 0:#节点下方还有节点则可以扩展下方节点
			neighbors.append((node[0],node[1]-1))
		if node[0] < self.blocks_type.shape[0]-1: #节点右方还有节点则可以扩展右方节点
			neighbors.append((node[0]+1,node[1])) 
		if node[0] > 0:#节点左方还有节点则可以扩展左方节点
			neighbors.append((node[0]-1,node[1]))
		return neighbors

这样在执行完广度优先搜索算法后,我们就可以知道两个元素之间有没有连接路径。

三、调用连接路径判断

我们可以在第二次点击事件时搜索连接路径。代码如下:

	def mouseClick(self,x,y):
		i = (y-self.start_top)//self.block_height
		j = (x-self.start_left)//self.block_width
		if i<0 or i>self.row-1 or j<0 or j >self.col-1 or self.blocks_type[i][j] == 0:
			return False
		if self.click_num %2 == 1 and self.click_list[0][0] == i and self.click_list[0][1] == j:
			return False

		self.click_num += 1
		self.click_list.append([i,j])
		if self.click_num % 2 == 0:

			if self.blocks_type[self.click_list[0][0]][self.click_list[0][1]] == self.blocks_type[self.click_list[1][0]][self.click_list[1][1]] and self.breadth_first_search((self.click_list[0][0],self.click_list[0][1]),(self.click_list[1][0],self.click_list[1][1])):
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].type = TYPE_RECT
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].color = (255,255,255)
				self.blocks[self.click_list[0][0]][self.click_list[0][1]].draw()#进行重渲染
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].type = TYPE_RECT
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].color = (255,255,255)
				self.blocks[self.click_list[1][0]][self.click_list[1][1]].draw()#进行重渲染
				self.blocks_type[self.click_list[0][0]][self.click_list[0][1]] = 0
				self.blocks_type[self.click_list[1][0]][self.click_list[1][1]] = 0
			self.click_list = list()

效果图:
在这里插入图片描述

这样我们就完成了游戏的基本逻辑。

四、完整代码

完整代码我会传到资源上,大家有需要可以在资源上免费获得,进行进一步开发。


总结

至此,我们的python小游戏开心消消乐/连连看就已经完成了,大家如果感兴趣可以自行下载我上传的资源,可以在此基础上进行二次开发,可以发出来一起分享各自的成果一起交流。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个简单的开心消消乐游戏的Python实现,使用了Pygame库: ```python import pygame import random # 初始化游戏 pygame.init() # 游戏窗口大小 WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # 创建游戏窗口 game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("开心消消乐") # 加载游戏图片 ball_images = [] for i in range(1, 6): ball_images.append(pygame.image.load(f"ball{i}.png")) # 球的大小和间距 BALL_SIZE = 60 BALL_SPACING = 10 # 生成随机球的颜色 def generate_random_color(): return random.choice([RED, GREEN, BLUE, YELLOW]) # 生成随机球的图片 def generate_random_ball_image(): return random.choice(ball_images) # 生成随机的球 def generate_random_ball(x, y): return { "x": x, "y": y, "color": generate_random_color(), "image": generate_random_ball_image() } # 生成随机的球列表 def generate_random_balls(num_balls): balls = [] for i in range(num_balls): x = (i % 8) * (BALL_SIZE + BALL_SPACING) + BALL_SPACING y = (i // 8) * (BALL_SIZE + BALL_SPACING) + BALL_SPACING balls.append(generate_random_ball(x, y)) return balls # 绘制球到屏幕 def draw_balls(balls): for ball in balls: game_window.blit(ball["image"], (ball["x"], ball["y"])) # 检查球是否相邻 def is_adjacent(ball1, ball2): return abs(ball1["x"] - ball2["x"]) <= BALL_SIZE + BALL_SPACING and \ abs(ball1["y"] - ball2["y"]) <= BALL_SIZE + BALL_SPACING # 寻找相邻的球 def find_adjacent_balls(balls, ball): adjacent_balls = [ball] stack = [ball] while len(stack) > 0: current_ball = stack.pop() for other_ball in balls: if other_ball not in adjacent_balls and is_adjacent(current_ball, other_ball) and other_ball["color"] == ball["color"]: adjacent_balls.append(other_ball) stack.append(other_ball) return adjacent_balls # 删除相邻的球 def remove_adjacent_balls(balls, adjacent_balls): for ball in adjacent_balls: balls.remove(ball) # 移动球到空缺位置 def move_balls(balls): for i in range(len(balls)): if balls[i] is None: balls[i] = generate_random_ball(i % 8 * (BALL_SIZE + BALL_SPACING) + BALL_SPACING, i // 8 * (BALL_SIZE + BALL_SPACING) + BALL_SPACING) # 检查游戏是否结束 def is_game_over(balls): for ball in balls: if find_adjacent_balls(balls, ball) != [ball]: return False return True # 游戏循环 def game_loop(): num_balls = 64 balls = generate_random_balls(num_balls) selected_ball = None game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos i = y // (BALL_SIZE + BALL_SPACING) * 8 + x // (BALL_SIZE + BALL_SPACING) if i < num_balls: ball = balls[i] if selected_ball is None: selected_ball = ball elif selected_ball == ball: selected_ball = None elif is_adjacent(selected_ball, ball): adjacent_balls = find_adjacent_balls(balls, selected_ball) if len(adjacent_balls) >= 2: remove_adjacent_balls(balls, adjacent_balls) move_balls(balls) selected_ball = None game_window.fill(WHITE) draw_balls(balls) if is_game_over(balls): font = pygame.font.Font(None, 36) text = font.render("游戏结束!", True, BLACK) text_rect = text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)) game_window.blit(text, text_rect) pygame.display.update() # 退出游戏 pygame.quit() quit() # 启动游戏 game_loop() ``` 运行上述代码,可以看到一个简单的开心消消乐游戏。玩家可以点击相邻的个颜色相同的球,将它们消除,直到所有的球都被消除为止。当没有相邻的球可以消除时,游戏结束。 注意:上述代码中的游戏图片 ball1.png 到 ball5.png 需要你自己准备,可以从网络上搜索到类似的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怪蜀黍客栈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值