如何让对象在pygame中以随机模式移动?

2024-06-26 14:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为“小行星”的翻拍工作。但是我不能让物体随机运动。我确信这是使用向量进化而来的,但是我不知道如何随机为每个小行星生成一个向量。在

我正在寻找一个类似于这个asteroid game中显示的运动的运动,但是我甚至不知道如何开始。这是我目前为止的代码:

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。在


Tags: importeventgametimedisplayscreenbgblack
2条回答

所以游戏中的每颗小行星都由一个Rect表示,存储在badguys中。在

使用Rect,您可以存储一个位置和一个大小(因为Rect具有xywidthheight)的属性。在

现在,您需要为每颗小行星存储额外的信息/状态,因此仅使用Rect是不够的。您需要一个包含更多字段的不同数据结构。在

由于使用python,fitting数据结构是一个能够保存随机向量的类。在

但让我们再考虑一下。由于您使用了pygame,pygame已经提供了一个用于表示游戏对象的类,该类称为^{}。在

所以我们开始(注意代码中的注释):

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)

下面是如何使用向量来实现这一点。badguy列表中的每个项现在都是一对项、其当前位置和相关的速度矢量。注意,位置本身也是一个向量(又名“位置向量”)。在

更新当前位置只需将每个坏蛋的速度矢量添加到当前位置即可。i、 e.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()

相关问题 更多 >