如何在 Pygame 中连续移动图像 [英] How to continuously move an image in Pygame

查看:114
本文介绍了如何在 Pygame 中连续移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Pygame 库用 Python 制作的游戏.在其中,我有两个类,一个是 Main 类,它使屏幕出现,图像闪烁等.Monster 类,它创建和渲染我的怪物精灵,它们是:

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:

主类:

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()

怪物类:

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))

我希望怪物连续向左移动一个随机的 x 值,直到它们撞到屏幕的另一侧.在那之后,我希望他们传送回他们的起点,然后再做一次.在主类中,我尝试在主循环中添加x=x+1"以至少让它们移动一个,但它没有用.我还尝试用 "x=x+1" 制作一个不同的循环,但没有用.如果您需要更多详细信息,请告诉我.感谢您抽出宝贵时间.

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.

推荐答案

您正在修改 x 变量,该变量仅用于创建对象.要修改 Monster 对象的成员,您需要像这样更改它们:

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

这篇关于如何在 Pygame 中连续移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆