python小游戏开心消消乐制作6-1


前言

上一章中我们美化了游戏界面,同时我们提出了将游戏元素矩阵封装成单个类的必要性,所以在这一章中我们围绕这一目标来实现。


一、创建游戏元素矩阵类

我们将类的实现放在MagicBlock.py中,我们将该元素矩阵类命名为MagicBlock

class MagicBlock:
	def __init__(self):
		pass

接着呢我们分析一下我们需要这个类做什么呢?
1、绘制矩阵游戏元素
2、点击消除特定游戏元素
那么我们围绕这两个点来设计MagicBlock

1.绘制矩阵游戏元素

我们从属性行为两个方面分别来看如何实现这一目标。
在上篇文章中我们知道绘制矩阵游戏元素的代码如下:

for i in range(8):
        for j in range(8):
        	#位置的计算公式为left = 起始left位置+元素宽度*j,top=起始top位置+元素高度*i
            blocks[i][j] = Block(screen,20+50*j,20+50*i,50,50,MagicBlock.TYPE_IMAGE,image=pygame.image.load('./image/0'+str(random.randint(1,5))+"_hightlight.png"))

属性角度来看,为了绘制矩阵游戏元素,我们需要使用screen这一游戏窗口画布。
紧接着呢需要获得元素开始的位置,即start_left,start_top
还有就是每个元素的长宽block_height,block_width
同时绘制矩阵我们也需要指定是多少行,多少列row,col
同时我们还需要知道这个矩阵游戏元素是图片类型还是矩形元素type
根据以上特点我们可以在类的初始化函数中将这些属性进行赋值。

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

行为上看我们只需要实现绘制矩阵元素这一项工作即可,由于我们已经将绘制所需属性已经初始化,那么我们根据上述属性设置绘制函数即可。在这里我们也需要调用Block类进行绘制,所以我们可以看到类调用关系是这样的GameBlock->Block
在绘制过程中,我们也需要根据type的类别去判定需要绘制图像元素还是矩形元素。

-MagicBlock.py
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
	def initMagicBlock(self):
		for i in range(0,self.row,1):
			for j in range(0,self.col,1):
				if self.type == TYPE_IMAGE:
					block = 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(random.randint(1,5))+"_hightlight.png"))
					block.draw()
				elif self.type == TYPE_RECT:
					block = 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)))
					block.draw()

这样主函数想要绘制矩阵元素时,只需要调用该函数即可。

-main.py
import pygame
import sys
import time
import random
from MagicBlock import Block,GameBlock
import MagicBlock

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_HEIGHT,SCREEN_WIDTH))
    pygame.display.set_caption("happy remove")
    screen.fill((124,114,242))
        	
    gameblock = GameBlock(screen,start_left=20,start_top=20,block_height=50,block_width=50,row=8,col=8,type=MagicBlock.TYPE_IMAGE)
    gameblock.initMagicBlock()
    #更新窗口
    pygame.display.update()
    while True:
        
        #获取鼠标响应
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)
            elif event.type ==pygame.MOUSEBUTTONDOWN:
                x,y = event.pos
                j = (x-20)//50 #20为游戏元素起始top位置,50为游戏元素长度 
                i = (y-20)//50#20为游戏元素起始left位置,50为游戏元素宽度 
        pygame.display.update()
        time.sleep(0.3)

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


总结

在本章中我们只围绕了第一点显示元素做了封装,在下一章中我们将围绕第二点消除元素做封装。(ps:因为今天是五一劳动节所以投个懒,就只写了一个小点哈哈哈哈哈哈哈哈哈哈哈,因为要出去玩,那么祝大家五一劳动节玩得开心喽)

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
好的,下面是一个简单的开心消消乐游戏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 需要你自己准备,可以从网络上搜索到类似的图片。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

怪蜀黍客栈

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

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

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

打赏作者

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

抵扣说明:

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

余额充值