0

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

  • Note that `block1 = Blocks()` already creates an instance of the `Blocks` class while the program is running. You do something similar on each move. – Code-Apprentice Jan 26 '21 at 00:37
  • As a point of clarification, what does the class `Blocks` represent? Is it all of the blocks on the screen? Or is it just a single block? If so, I suggest removing the "s" from the end of the class name. – Code-Apprentice Jan 26 '21 at 00:38
  • @Code-Apprentice "Blocks" is a class that represents one block and within a list, there are objects of that class that can fill up the screen. I will definitely take your suggestion to remove the "s" so thank you so much! but I still don't really know how to for example add an object to the list while the program is already running, I know I need to ".append" something but im not exactly sure how to. – Isaak Mishiev Jan 26 '21 at 02:47
  • As the answer below shows, you create a new `Blocks` object, just like you do with the first two then you append that object to the list. – Code-Apprentice Jan 26 '21 at 18:08

2 Answers2

1

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

eligolf
  • 1,682
  • 1
  • 6
  • 22
-1
  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
KennetsuR
  • 704
  • 8
  • 17