简体   繁体   中英

How to make a new object while the program is running (Python, pygame)

I am currently making 2048 and am having trouble with creating a new block whenever a move is made.

I made a list storing all the blocks there are, within the list there objects:

class Blocks:
   ~~~~~~~ code ~~~~~~~~~

block1 = Blocks()
block2 = Blocks()
block_list = [block1, block2] 

The issue is that it works perfectly when the blocks are pre-written, but I can not make a new block while the game is already running, is there any way to do this? Thank you in advance, stay safe:)

I don't see why this would not be possible. You should simply be able append a new block to your block_list:

block_n = Blocks()
block_list.append(block_n)

You place this in your game loop where you detect when a move is made.

Where you blit I assume you go through the block_list and blit all the blocks to the screen? Also make sure to always update the screen with pygame.display.flip().

  1. I suppose that you need "Reflection" in python. Reflection can get type of instance, create instance of type during code runtime.
  2. You can get some inspirations from the question Can you use a string to instantiate a class? or the article Classes and Class Creation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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