【发布时间】:2022-12-10 20:27:35
【问题描述】:
我想在 pygame 中制作可收集和易碎的物品,例如箱子、板条箱、桶、头盔、硬币、钥匙。 然后在与角色互动时;当角色接触到它或弄坏它时,我希望它被移除。 我可以根据需要在屏幕上多次绘制所有项目,但是当我尝试删除它们时,要么全部删除,要么一个都不删除。 这次我尝试了另一种方法并使用了一个类,在 for 循环中我创建了一个类项目并将其添加到列表中,在主循环中我将列表中的项目绘制到屏幕上。如果有任何干扰,我会将其从列表中删除。问题是,当我这样做时,我的 fps 严重下降。 我无法理解如何解决它以及这项工作的逻辑。抱歉,如果标题或问题不是不言自明的,我感谢您的帮助。 我的最后一个代码;
import pygame
from pygame.locals import *
pygame.init()
surface = pygame.display.set_mode((640,256))
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 32)
map="0b0b0\n11111"
gameMap=[(list(row)) for row in map.split("\n")]
position=(0,0)
barrelList=[]
condition=True
class Barrel:
def __init__(self,coord):
self.coord=coord
self.image=pygame.transform.scale(pygame.image.load("barrel.png"),(64,80))
self.rect=pygame.Rect((coord[0],coord[1],64,80))
def draw(self,surface):
surface.blit(self.image,self.coord)
while True:
surface.fill((0,0,0))
for ev in pygame.event.get():
if ev.type == QUIT:
pygame.quit()
if ev.type == MOUSEBUTTONDOWN:
position=pygame.mouse.get_pos()
y=0
for layer in gameMap:
x=0
for tile in layer:
if tile=="1":#tiles ... etc.
pygame.draw.rect(surface,"cyan",(x*128,y*128,128,128))
if tile=="b":#chest, crate, barrel, healt, coin, key ... etc.
if condition:
barrelList.append(Barrel((x*128,y*128)))
x+=1
y+=1
for barrel in barrelList:
barrel.draw(surface)
if barrel.rect.collidepoint(position):
barrelList.remove(barrel)
condition=False
surface.blit(font.render("fps:{}".format(int(clock.get_fps())), 1, (255, 255, 255)), (0, 0))
pygame.display.flip()
clock.tick(60)
【问题讨论】: