如何在pygame中让物体以随机模式移动?

3

我一直在制作一个“小行星”重制版。然而,我无法使对象以随机运动方式移动。我确定这需要使用向量,但是我不知道如何为每个单独的小行星随机生成一个向量。

我正在寻找类似于这个小行星游戏中所显示的运动方式,但我甚至不知道如何开始。这是我目前的代码:

import pygame as game
import random as r
import math

game.init()
game.display.set_caption("Asteroids")
screen = game.display.set_mode([800,600])
time=0
gameon=True
bgcolor = game.color.Color("#f6cb39")
black=game.color.Color("black")
badguy = game.image.load("asteroid.png")
badguy = game.transform.scale(badguy, (50, 50))
badguys=[]
SPAWNENEMY=10
CLOCK=11
game.time.set_timer(SPAWNENEMY,800)
game.time.set_timer(CLOCK,1000)

font=game.font.Font(None,20)
timetext=font.render("Time: 0", 0, black)

while gameon:
    screen.fill(bgcolor)
    event=game.event.poll()
    if event.type==SPAWNENEMY:
        bgbox = game.Rect(badguy.get_rect())
        bgbox.x = r.randint(50,800)
        bgbox.y = r.randint(50,600)
        badguys.append(bgbox)

    if event.type==game.QUIT:
        gameon=False;

    for bg in badguys:

        '''
        This is where I tried to put the mocment code,
        but I was unableto get randmom movments,
        only for asteroids to randomly appear or consistently
        move in one direction something like "bg.x+=2"

        '''

    for bg in badguys:
        screen.blit(badguy,(bg.x,bg.y))

    game.display.flip()

如果有一点长,我向您道歉,我不知道还能删掉什么来创建一个MCV。


对于每个坏人,只需初始化一个随机速度向量,并在每一步应用它到位置上,这样他们就会沿着随机方向进行线性移动。 - user2261062
使用随机数在屏幕边缘生成陨石。您可以做一些像是生成三个随机数的事情,其中一个在1-4之间,用于确定它生成的边缘,下一个在分辨率范围内,用于确定它将在边缘上生成的位置,最后一个用于随机精度修正器。将其向量指向屏幕中心,应用随机修饰符使其“瞄准”不完美。只是一个猜测! - KuboMD
非常抱歉,我对编程非常陌生。我从未涉及过向量,也不知道如何操作。但我可以将行星生成在屏幕边缘。 - Misha
2个回答

3

下面是使用向量进行操作的方法。现在,badguy列表中的每个项目都是一对项目,即其当前位置和相关速度向量。请注意,位置本身也是一个向量(也称为“位置向量”)。

通过将每个坏人的速度向量简单地加到其当前位置来更新当前位置。即 bg [0] + = bg [1]

import pygame as game
import pygame.math as math
from pygame.time import Clock
import random as r


game.init()
game.display.set_caption("Asteroids")
screen = game.display.set_mode([800, 600])

time = 0
gameon = True
bgcolor = game.color.Color("#f6cb39")
black = game.color.Color("black")
clock = Clock()

badguy = game.image.load("asteroid.png")
badguy = game.transform.scale(badguy, (50, 50))
badguys = []
SPAWNENEMY = 10
CLOCK = 11

game.time.set_timer(SPAWNENEMY, 800)
game.time.set_timer(CLOCK, 1000)

font=game.font.Font(None,20)
timetext=font.render("Time: 0", 0, black)

while gameon:
    screen.fill(bgcolor)

    event = game.event.poll()
    if event.type == SPAWNENEMY:
        # Select a random initial position vector.
        posn = math.Vector2(r.randint(50, 800), r.randint(50, 600))

        # Create a random speed vector.
        speed = r.randint(1, 10)
        dx = r.random()*speed * r.choice((-1, 1))
        dy = r.random()*speed * r.choice((-1, 1))
        vector = math.Vector2(dx, dy)

        # Each badguy item is a [position, speed vector].
        badguys.append([posn, vector])

    if event.type == game.QUIT:
        gameon = False;

    for bg in badguys:
        # Update positions.
        bg[0] += bg[1]  # Update position using speed vector.

    for bg in badguys:
        screen.blit(badguy, bg[0])

    clock.tick(60)
    game.display.flip()

正是我所需要的!非常感谢。 - Misha
1
Misha:很高兴你觉得它有用。你问题中的MCV非常有帮助。唯一能让它更好的是,如果你在问题中上传了asteroid.png图像文件某个地方,并且也在问题中提供了一个链接。 - martineau

1
因此,游戏中的每个小行星都由一个Rect表示,存储在badguys中。
使用Rect,您可以存储位置和大小(因为Rect具有属性xywidthheight)。
现在,您想为每个小行星存储附加信息/状态,因此仅使用Rect是不够的。您需要一个不同的数据结构来保存更多字段。
由于您使用Python,适合的数据结构是能够保存随机向量的类。
但让我们再深入思考一下。由于您使用pygame,pygame已经提供了一个用于表示游戏对象的类,该类称为Sprite
所以我们来看看代码(请注意代码中的注释):
import pygame
import random

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

class Asteroid(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()

        # let's create an image of an asteroid by drawing some lines
        self.image = pygame.Surface((50, 50))
        self.image.set_colorkey((11, 12, 13))
        self.image.fill((11, 12, 13))
        pygame.draw.polygon(self.image, pygame.Color('grey'), [(0, 11), (20, 0), (50, 10), (15, 22), (27, 36), (10, 50), (0, 11)], 1)

        # Let's store a copy of that image to we can easily rotate the image
        self.org_image = self.image.copy()

        # The rect is used to store the position of the Sprite
        # this is required by pygame
        self.rect = self.image.get_rect(topleft=(x, y))

        # Let's create a random vector for the asteroid
        self.direction = pygame.Vector2(0, 0) 
        while self.direction.length() == 0:
            self.direction = pygame.Vector2(random.uniform(-1, 2), random.uniform(-1, 2))

        # Also we want a constant, random speed
        self.direction.normalize_ip()
        self.speed = random.uniform(0.1, 0.3)

        # we additionaly store the position in a vector, so the math is easy
        self.pos = pygame.Vector2(self.rect.center)

        # Aaaaaaaaaand a random rotation, because why not
        self.rotation = random.uniform(-0.3, 0.3)
        self.angle = 0

    def update(self, dt):
        # movement is easy, just add the position and direction vector
        self.pos += self.direction * self.speed * dt
        self.angle += self.rotation * dt
        self.image = pygame.transform.rotate(self.org_image, self.angle)

        # update the rect, because that's how pygame knows where to draw the sprite
        self.rect = self.image.get_rect(center=self.pos)

SPAWNENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(SPAWNENEMY, 800)

asteroids = pygame.sprite.Group()
dt = 0
while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            quit()
        if e.type == SPAWNENEMY:
            asteroids.add(Asteroid(random.randint(50, 200), random.randint(50, 200)))
    screen.fill(pygame.Color('black'))
    asteroids.draw(screen)
    asteroids.update(dt)
    pygame.display.flip()
    dt = clock.tick(60)

它给我一个错误:“模块'pygame'没有属性'Vector2'”。 - Misha
1
@Misha 你似乎在使用较旧的pygame版本。你可以尝试使用pygame.math.Vector2或者升级你的pygame版本。 - sloth
在我看来,这个答案中有很多好的建议和示例代码,但其中许多内容可能对许多人来说过于高级,因为它远远超出了所提出的问题——尽管这本身并不是一件坏事。 - martineau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接