【问题标题】:Trouble with classes in pygamepygame中的类问题
【发布时间】:2018-09-02 06:58:55
【问题描述】:

我一直在使用 pygame 开发游戏。到目前为止,我已经开始拍摄了。 代码如下:

def game_loop():
    global x
    global y
    x=0
    y=0
    second_x=0
    second_y=0
    change_x=0
    change_y=0

    xlist=[]
    ylist=[]
    # paused=True


    while True:
        game_display.blit(background, (0, 0))


        mouseclk=pygame.mouse.get_pressed()


        for event in pygame.event.get():

            if event.type==pygame.QUIT:
                pygame.quit()
                quit()


            x, y = pygame.mouse.get_pos()
            xlist.append(x)
            ylist.append(y)


            if x>=display_width-40:
                x=display_width-40

            if y>=display_height-48:
                y=display_height-48


            if event.type == pygame.MOUSEBUTTONUP :
                if event.button==1:
                    bullets.append([x+16,y])
                    shoot.play()


        for bullet in bullets:
            game_display.blit(bulletpic, (bullet[0], bullet[1]+10))


        for b in range(len(bullets)):
            bullets[b][-1] -= 10


        for bullet in bullets:
            if bullet[1]>display_height:
                bullets.remove(bullet)


        mainship=Ship(spaceship, x, y, pygame.mouse.get_focused())
        mainship.MakeShip()


        if pygame.mouse.get_focused()==0:
            pause()


        pygame.display.update()


        clock.tick(60)

射击效果很好,但我真的很想在我的游戏中使用类。我尝试制作这样的课程:

class Bullet:

    def __init__(self, xpos, ypos, sprite, speed, llist):

        self.xpos=xpos
        self.ypos=ypos
        self.sprite=sprite
        self.speed=speed
        self.list=llist


        self.list.append([self.xpos+16,self.ypos])


        for bullet in self.list:
            game_display.blit(self.sprite, (bullet[0], bullet[1]+10))


        for b in range(len(self.list)):
            self.list[b][-1] -= self.speed

        for bullet in self.list:
            if bullet[1]>display_height:
                self.list.remove(bullet)

现在,尽管这看起来可行,但它只会使子弹出现故障且速度变慢,有时甚至无法正常生成子弹。

有什么办法可以让这个工作吗?我是一个菜鸟程序员,一般来说都是新手,所以任何帮助都将不胜感激。

【问题讨论】:

    标签: python python-3.x class pygame


    【解决方案1】:

    我认为你的 Bullet 做得太多了。你可以像这样对子弹建模:

    class Bullet: 
        """This is a bullet. It knows about its position, direction and speed.
        It can move. It knows when it crosses the classvariables bounds."""
    
        # bounds as class variable for _all_ bullets - set it to dimensions of your game field
        bounds = (0,0,10,10) # if position is lower or higher that these it is out of bounds
    
        # if you got only 1 spite for all bullets (no acid-, fire-, waterbullets) you could
        # set it here. I would not, I would leave bullets simply to do the movement and tell
        # me if they get out of bounds
    
        def __init__(self, xpos, ypos, xdir, ydir, speed):
            # where does the bullet start (f.e. muzzle position)
            self.xpos=xpos
            self.ypos=ypos
            # direction that the bullet flies
            self.xdir=xdir
            self.ydir=ydir
            # initial speed of the bullet
            self.speed=speed
    
        def moveBullet(self):
            self.xpos += int(self.xdir * self.speed) # speed may be 0.8 or so
            self.ypos += int(self.ydir * self.speed)
    
        def outOfBounds(self):
            minX,minY,maxX,maxY = Bullet.bounds
            return self.xpos < minX or self.ypos < minY or self.xpos > maxX or self.ypos > maxY
    
        def __repr__(self):
            """Pretty print stuff"""
            return "({},{}){}".format(self.xpos,self.ypos,"" if 
                                      not self.outOfBounds() 
                                      else " : Out Of Bounds {}".format(Bullet.bounds))
    

    然后,您的游戏会设置所有子弹的边界并跟踪子弹列表。如果您需要新的子弹,只需将其放入列表中即可

    Bullet.bounds = (0,0,90,90)
    bullets = [ Bullet(10,10,12,0,3), Bullet(10,10,11,9,3), Bullet(10,10,0,5,1)]
    
    while bullets:
        # you should move this into some kind of `def moveBullets(bulletlist): ...` 
        # that you then call inside your game loop
        for b in bullets:
            b.moveBullet()
            print(b)  # instead draw a spirte at b.xpos, b.ypos
        print("")
        # return from moveBullets(..)
    
        # remove all out of bounds bullets from list
        bullets = filter(lambda b: not b.outOfBounds(),bullets) 
    

    输出:

    (46,10)
    (43,37)
    (10,15)
    
    (82,10)
    (76,64)
    (10,20)
    
    (118,10) : Out Of Bounds (0, 0, 90, 90)
    (109,91) : Out Of Bounds (0, 0, 90, 90)
    (10,25)
    
    (10,30)
    
    (10,35)
    
    (10,40)
    
    (10,45)
    
    (10,50)
    
    (10,55)
    
    (10,60)
    
    (10,65)
    
    (10,70)
    
    (10,75)
    
    (10,80)
    
    (10,85)
    
    (10,90)
    
    (10,95) : Out Of Bounds (0, 0, 90, 90)
    

    【讨论】:

    • 这篇文章是一个很好的例子,说明了一种更好的方式来做你想做的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多