Как заставить объект перемещаться случайным образом в Pygame?

3
задан martineau 17 January 2019 в 22:59
поделиться

2 ответа

Вот как это сделать, используя векторы. Каждый элемент в списке 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()
0
ответ дан martineau 17 January 2019 в 22:59
поделиться

Таким образом, каждый астероид в вашей игре представлен как Rect, хранящийся в badguys.

С помощью Rect вы можете сохранить положение и размер (поскольку у Rect есть атрибуты x, y, width и height).

Теперь вы хотите сохранить дополнительную информацию / состояние для каждого астероида, поэтому недостаточно только использования 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)
0
ответ дан sloth 17 January 2019 в 22:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: