How to continuously move an image in Pygame

2019-09-05 07:00发布

问题:

I have a game I am making in Python with the Pygame library. In it, I have two classes, the Main class, which causes the screen to appear, blits the images, etc. and the Monster class, which creates and renders my monster sprites, here they are:

Main class:

import pygame, sys, random
from monster import *

pygame.init()

class Main:
    clock = pygame.time.Clock()

    screenSize = (500,500)
    background = pygame.image.load("C:/Users/Nathan/PycharmProjects/Monsters II A Dark Descent/images/background.jpg")

    screen = pygame.display.set_mode(screenSize)
    pygame.display.set_caption("MONSTERS!")

    monsters = pygame.sprite.Group()

    counter = 0

    x = 450
    while counter < 5:
            y = random.randint(50,450)
            monster = Monster(x,y)
            monsters.add(monster)
            counter = counter + 1

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.blit(background,(0,0))

        for monster in monsters:
            monster.render(screen)

        x=x-1 #This doesn't move the sprites

        clock.tick(60)

        pygame.display.flip()


Main()

Monster class:

import random, pygame

class Monster(pygame.sprite.Sprite):

    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.image = pygame.image.load("C:\Users\Nathan\PycharmProjects\Monsters II A Dark Descent\images\monster.png")

    def render(self, screen):
        screen.blit(self.image, (self.x, self.y))

I want the Monsters to move to the left by a random x value continuously until they hit the other side of the screen. After that happens I want them to teleport back to their starting point and do it again. In the main class, I tried adding "x=x+1" in the main loop to at least get them to move by one but it didn't work. I also tried making a different loop with "x=x+1" which didn't work. If you need more details let me know. Thank you for your time.

回答1:

You are modifying the x variable, which was only used to create objects. To modify the members of a Monster object, you want to change them like this:

monster.x += 1

I would suggest to create a new function that will move the sprite, and reset it back to position. Something along these lines:

def move(self):
    if(self.x > 500):
        self.x = 0
    self.x += 1


回答2:

In your main loop, you need to update the x value in the monster. You can do it in the loop that goes over your monsters:

for monster in monsters:
    monster.x = monster.x-1
    monster.render(screen)

Notice, monster.x says change the x value in this specific monster. If you just do x, python has no idea your talking about the x values inside the monsters.



标签: python pygame