如何使用类方法update()使组中的精灵独立更新其位置?

huangapple go评论52阅读模式
英文:

How to make sprites in a group update their position independently using class method update()?

问题

以下是您提供的代码的翻译部分:

我是新手使用pygame正在尝试创建一个具有随机移动并在屏幕边界上弹跳的小狗精灵的游戏

在我的精灵类中我使用update()方法来更新精灵的个体位置但是当我运行代码时所有精灵似乎一起移动所以我想知道是否应该以不同的方式组织代码或将精灵放入不同的组中

这是代码

import pygame, random

pygame.init()

class puppy(pygame.sprite.Sprite):
    def __init__(self, pos_x, pos_y, filepath, speed=[2,2]):
        super().__init__()
        self.image = pygame.image.load(filepath)
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x, pos_y]
        self.speed = speed
    def update(self):
        if (self.rect.x < 0) or (self.rect.x > 850):
            self.speed[0] *= -1
        if (self.rect.y < 0) or (self.rect.y > 615):
            self.speed[1] *= -1
        self.rect.x = self.rect.x + self.speed[0]
        self.rect.y = self.rect.y + self.speed[1]

puppies = pygame.sprite.Group()

dogimages = ['pupp1.png', 'pupp2.png', 'pupp3.png', 'pupp4.png', 'pup5.png']

for i in range(5):
    new_pup = puppy(random.randint(75, 925), random.randint(75, 675), dogimages[i])
    puppies.add(new_pup)

screen = pygame.display.set_mode((1000, 750))
screen.fill((255, 255, 255))
clock = pygame.time.Clock()
background = pygame.image.load('bg.jpeg')

running = True
while running:
    clock.tick(60)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.blit(background, (0, 0))
    puppies.draw(screen)
    puppies.update()
    pygame.display.update()

希望这能帮助您理解代码。如果您有任何其他问题,请随时提出。

英文:

Hi I'm new to using pygame and I'm trying to build a game with sprites of puppies moving randomly around the screen and bouncing off the boundaries.

I'm using the method update() within my sprite class on my group of sprites ' puppies ' to update the sprites' individual locations, however when I run the code all of the sprites seem to move together so I'm wondering if I should be structuring the code differently or putting the sprites in individual groups?

Here's the code:

import pygame, random
pygame.init()
class puppy(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y,filepath, speed=[2,2]):
super().__init__()
self.image = pygame.image.load(filepath)
self.rect=self.image.get_rect()
self.rect.center = [pos_x,pos_y]
self.speed = speed
def update(self):
if (self.rect.x &lt; 0) or (self.rect.x &gt; 850):
self.speed[0] *= -1
if (self.rect.y &lt; 0) or (self.rect.y &gt; 615):
self.speed[1] *= -1
self.rect.x = self.rect.x + self.speed[0]
self.rect.y = self.rect.y + self.speed[1]
puppies = pygame.sprite.Group()
dogimages = [&#39;pupp1.png&#39;,&#39;pupp2.png&#39;,&#39;pupp3.png&#39;,&#39;pupp4.png&#39;,&#39;pup5.png&#39;]
for i in range(5):
new_pup=puppy(random.randint(75,925),random.randint(75,675),dogimages[i])
puppies.add(new_pup)
screen = pygame.display.set_mode((1000, 750))
screen.fill((255,255,255))
clock=pygame.time.Clock()
background = pygame.image.load(&#39;bg.jpeg&#39;)
running=True
while running:
clock.tick(60)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(background, (0, 0))
puppies.draw(screen)
puppies.update()
pygame.display.update()

答案1

得分: 1

你正在使用一个默认值为[2,2]的列表。强烈不建议使用可变对象作为默认值,因为这可能导致各种问题:请参见这里讨论为什么会出现这种情况。

更好的做法是:

class puppy(pygame.sprite.Sprite):
    def __init__(self, pos_x, pos_y, filepath, speed=None):
        if speed is None:
            speed = [2, 2]
        ...

这是通常用来实现可变默认参数以避免出现这种问题的方式。

英文:

You are using a list [2,2] as a default value. Using mutables as default values is highly discouraged as it can lead to all sorts of issues: see here for a discussion on why this is the case.

It would be better to do:

class puppy(pygame.sprite.Sprite):
def __init__(self,pos_x, pos_y, filepath, speed=None):
if speed is None:
speed = [2, 2]
...

which is how mutable default arguments are usually implemented to avoid this exact issue.

huangapple
  • 本文由 发表于 2023年7月6日 16:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定