简体   繁体   English

Pygame:精灵只绘制三个对象中的最后一个

[英]Pygame: Sprites are only drawing the last of the three objects

I am trying to make a stage builder that will ease with the development of adding objects, individually check for their collision, and so forth for every single object, I add-in code.我正在尝试制作一个舞台构建器,该构建器将简化添加对象的开发,单独检查它们的碰撞等等,对于每个 object,我添加了代码。

My idea is to place objects in groups and have their data be retrieved from JSON data.我的想法是将对象分组并从 JSON 数据中检索它们的数据。 While it seemed that it works from gathering and placing data as I have coded, it only just wants to draw the very last object there.虽然它似乎可以像我编码的那样收集和放置数据,但它只想在那里绘制最后一个 object。 Meaning if I were to have 100 objects with their respective data in JSON, only the 100th object will be drawled.这意味着如果我在 JSON 中有 100 个对象及其各自的数据,则只有第 100 个 object 将被拉长。

In that case, I, of course, want to have all the 99th other objects be also drawled.在这种情况下,我当然希望所有第 99 个其他对象也被拉长。

From the code that I have posted below, I have checked in a print statement that I indeed got the three object data, ''.从我在下面发布的代码中,我检查了一个打印语句,我确实得到了三个 object 数据,''。 This should mean that the JSON data itself is not the problem.这应该意味着 JSON 数据本身不是问题。

If I have to guess, I think the problem is the conversion of individuals and adding them in Groups();如果我不得不猜测,我认为问题在于个人的转换并将它们添加到 Groups(); StartHorizontalObjectRepeats() function could be the problem. StartHorizontalObjectRepeats() function 可能是问题所在。

Here is a minimum, reproducible code, recreated from my main program.这是从我的主程序重新创建的最小的、可重现的代码。

Codes:代码:

main.py主文件

import pygame
from settings import StartupSettings
import mechanic as m
from object import HorizontalObject
from pygame.sprite import Group

if __name__ == "__main__":
    pygame.init()
    Settings = StartupSettings()

    Objects = HorizontalObject(Settings.screen)
    Objects = Group()

    m.HorizontalObjectRepeats(Settings.screen, Objects)

    while True:
        m.Refresh(Settings, Objects)

settings.py设置.py

import pygame

class StartupSettings():
    def __init__(self):
        self.screen = pygame.display.set_mode((800,600))
        self.background = [70,70,70]

object.py object.py

import pygame
from pygame.sprite import Sprite

class HorizontalObject(Sprite):
    def __init__(self, screen):
        super().__init__()

        self.screen = screen
        self.screen_rect = self.screen.get_rect()

        self.image = pygame.image.load('img_test_object.png')
        self.rect = self.image.get_rect()

mechanic.py机械师.py

import pygame
import json
from object import HorizontalObject

def HorizontalObjectRepeats(screen, ObjectExport):
    '''Initates the repeats of given horizontal test objects.'''
    NumberOfObjects = ReadJSONFileGeneral(1)
    for PlacementsofObjects in range(NumberOfObjects):
        StartHorizontalObjectRepeats(screen, ObjectExport, NumberOfObjects)

def StartHorizontalObjectRepeats(screen, ObjectExport, NumberOfObjects):
    '''Starts the repeat.'''
    Object = HorizontalObject(screen)

    for i in range(NumberOfObjects):
        Object.rect = ReadJSONFileObject(0, i)

    ObjectExport.add(Object)
    print(ObjectExport)

def StageBuilderTemplate(templateKeycode):
    '''Template data when starting out the stage builder.'''
    dictObjects = {"HorizontalObjectsData": {0: (50, 50, 308, 76), 1: (100, 100, 308, 76), 2: (150, 150, 308, 76)}}
    dictGeneral = {"BackgroundColor": (255, 0, 255), "HorizontalObjects": len(dictObjects["HorizontalObjectsData"].keys())}

    if templateKeycode == 0:
        return dictGeneral        
    elif templateKeycode == 1:
        return dictObjects

def CreateJSONFile(jsonCreationKeycode):
    '''Dumps data to the specified json based on the sented keycode.'''
    if jsonCreationKeycode == 0:
        with open('General.json', 'w') as f:
            json.dump(StageBuilderTemplate(0), f)
    elif jsonCreationKeycode == 1:
        with open('Object.json', 'w') as f:
            json.dump(StageBuilderTemplate(1), f)     

def ReadJSONFileObject(keycode, Repeats):
    '''Attempts to read Object.json file. It will create Object.json
    if it does not exist.

    After reading and extracting the entire data from Object.json,
    it will sent on specific data based on the sented keycode.'''
    try:
        with open("Object.json", 'r') as f:
            data = json.load(f)

            if keycode == 0:
                return data["HorizontalObjectsData"].get(str(Repeats))
    except FileNotFoundError:
        CreateJSONFile(1)

def ReadJSONFileGeneral(jsonGeneralKeycode):
    '''Attempts to read General.json file. It will create General.json
    if it does not exist.

    After reading and extracting the entire data from General.json,
    it will sent on specific data based on the sented keycode.'''
    try:
        with open("General.json", 'r') as f:
            data = json.load(f)

            if jsonGeneralKeycode == 0:
                return data.get('BackgroundColor')
            elif jsonGeneralKeycode == 1:
                return data.get('HorizontalObjects')
    except FileNotFoundError:
            CreateJSONFile(0)

def Refresh(Settings, Objects):
    '''Updates the screen'''
    Settings.screen.fill(Settings.background)
    Objects.draw(Settings.screen)
    pygame.display.flip()

General.json通用.json

{"BackgroundColor": [255, 0, 255], "HorizontalObjects": 3}

Object.json Object.json

{"HorizontalObjectsData": {"0": [50, 50, 308, 76], "1": [100, 100, 308, 76], "2": [150, 150, 308, 76]}}

Object Image: Object 图片:

对象图像

Output: Output:

输出

Notes:笔记:

  • I understand that the creation of new JSON files, specifically General.json, will have to crash once, before having the program be running back to normal.我了解创建新的 JSON 文件,特别是 General.json,必须崩溃一次,然后程序才能恢复正常运行。 This is not related to this current problem that I am asking for help.这与我正在寻求帮助的当前问题无关。
  • For the output, (Not Responding) cannot also be related as I do not have this similar occurrence on my main program.对于 output, (不响应)也不能相关,因为我的主程序上没有类似的情况。

In the StartHorizontalObjectRepeats function, when you get the rect for the object, you loop through all the objects and get the rect, meaning, they all have the same rect and are in the same spot.StartHorizontalObjectRepeats function 中,当您获取 object 的矩形时,您循环遍历所有对象并获取矩形,这意味着它们都具有相同的矩形并且位于同一位置。

To fix this:要解决此问题:

def HorizontalObjectRepeats(screen, ObjectExport):
    '''Initates the repeats of given horizontal test objects.'''
    NumberOfObjects = ReadJSONFileGeneral(1)
    for PlacementsofObjects in range(NumberOfObjects):
        StartHorizontalObjectRepeats(screen, ObjectExport, PlacementsofObjects) #changed the last parameter

def StartHorizontalObjectRepeats(screen, ObjectExport, objNum):
    '''Starts the repeat.'''
    Object = HorizontalObject(screen)

    Object.rect = ReadJSONFileObject(0, objNum) # get the nth objects rect

    ObjectExport.add(Object)

In the first function in mechanic.py the first function has a for loop in range(blah) that calls the second function which for loops in range(blah) again and based on your description isn't implemented correctly.在 mechanic.py 中的第一个 function 中,第一个 function 有一个范围内的 for 循环(等等),它调用第二个 function 并基于您的范围内的描述(没有正确执行)。 Can you get just one of the json files to display singly?您能否仅获取 json 文件之一来单独显示? I would try and start there and once you have that working properly implementation new features And from there try and figure out to use the classes and sprites我会尝试从那里开始,一旦你可以正常工作,实现新功能然后从那里尝试找出使用类和精灵

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM