python小游戏开心消消乐制作5-美化界面


Bug解决

通过一顿的代码分析后,我发现是i和j计算公式对调了,因为x其实代表的才是游戏元素的起始left位置,y代表的才是游戏元素的起始top位置。所以正确代码应该是:

j = (x-20)//50 #20为游戏元素起始top位置,50为游戏元素长度 
i = (y-20)//50#20为游戏元素起始left位置,50为游戏元素宽度

完整正确代码:

import pygame
import sys
import time
import random
from MagicBlock import Block

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))
        	
    blocks=[[0]*8 for i in range(8)]
    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,(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
            blocks[i][j].draw()
    #更新窗口
    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为游戏元素宽度 
                blocks[i][j].color = (124,114,242)
                blocks[i][j].draw()
        pygame.display.update()
        time.sleep(0.3)


前言

在上篇文章中,我们实现了点击消除游戏元素事件,由于矩形元素有点太丑陋了,所以我们将矩形元素替换成图像元素会好看点(说白了这章就是美化用的哈哈哈哈哈哈)


一、美化游戏元素

1. 图像元素绘制

pygame中我们可以使用screen.blit(source,dest)函数来绘制图像。
其中参数source是某矩形图像(Surface实例),将被绘制到另一矩形图像screen(Surface实例)上由参数dest指定位置。参数dest是矩形图像source左上角在screen上的坐标。
为了获得Surface实例,我们可以通过pygame.image.load(图片路径)加载图片,获取Surface实例。在这里我找了五张和消消乐相关的图片作为游戏元素,想要的可以私聊我找我要。
在这里插入图片描述
我们在原有的代码基础上添加如下代码进行测试:

screen.blit(pygame.image.load('./image/01_hightlight.png'),(20,450))

完整代码如下:

import pygame
import sys
import time
import random
from MagicBlock import Block

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))
        	
    blocks=[[0]*8 for i in range(8)]
    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,(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
            blocks[i][j].draw()
    screen.blit(pygame.image.load('./image/01_hightlight.png'),(20,450))

    #更新窗口
    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为游戏元素宽度 
                blocks[i][j].color = (124,114,242)
                blocks[i][j].draw()
        pygame.display.update()
        time.sleep(0.3)

效果图如下:
在这里插入图片描述
我们可以看到在全部元素下方显示了小熊的图像。

2. 矩形元素替换为图像元素

我们想要Block类既能绘制矩形元素,又能绘制图像元素,我们可以给Block类添加type属性,在绘制中判断该Block实例是矩形元素还是图像元素。
由于不同的元素,所需要的属性是不同的(比如矩形元素需要颜色信息,图像元素需要图像),所以我们可以通过将image和color设置默认为None,在需要的时候进行赋值即可。
代码如下:

-MagicBlock.py
import pygame
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):
		position = self.left,self.top,self.width,self.height
		pygame.draw.rect(self.screen,self.color,position)

上述代码仅只是将属性进行添加,类的行为也要改变,我们可以通过if判断类型来实现不同元素的绘制。同时我们可以给Block设置全局变量来判断是那种类型,具体代码如下:

-MagicBlock.py
import pygame

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))

同时我们也要更改主入口文件中调用类的接口,由于我们的image文件名呢是根据0i{1-5}_hightlight.png来命名,所以我们可以通过random.randint(1,5)来动态变更每个位置的图像。更改代码如下:

import MagicBlock
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"))

完整代码如下:

-main.py
import pygame
import sys
import time
import random
from MagicBlock import Block
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))
        	
    blocks=[[0]*8 for i in range(8)]
    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"))
            blocks[i][j].draw()
    #更新窗口
    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为游戏元素宽度 
                blocks[i][j].color = (124,114,242)
                blocks[i][j].draw()
        pygame.display.update()
        time.sleep(0.3)

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

总结

本篇文章美化了游戏元素,但是深入分析我们发现点击消除事件失效,以及对于每一个元素消除都需要在主函数中独立操作,且我们看到随着后续内容的增加,main.py会越来越臃肿,我们想着能否再用一个类来将矩阵游戏元素作为整体来操作,我们只需要在主函数中操作该类需要执行的动作即可,这样不仅架构清晰,而且操作方便,也就不需要再主函数中不断修改了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

怪蜀黍客栈

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

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

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

打赏作者

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

抵扣说明:

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

余额充值