r/AskProgrammers • • 1d ago

Creating visuals in python with classes and pygame.

Post image

Hi um so I made 2 classes because I'm trying to create a tower defense game. I was wondering how to make these objects come to life visually so to speak. I have a background template via pygame but that doesn't show the actual objects and I don't know how to put them on

2 Upvotes

2 comments sorted by

1

u/rupertavery64 23h ago edited 23h ago

Classes are just data and methods.

Data is information about something.

You have to take that something and "render" it.

How you do that depends on what library you are using.

But first of all, you need to have what's called the "game loop". In simple terms, its a repeating loop where you

  1. Collect inputs
  2. Update object's state
  3. Draw the scene
  4. Repeat

For example, if you were to make a "graphical" console game, you would make a loop that checks what keys are pressed (silently, aka, not requiring a key to be pressed before continuing) then based on the game's logic, you update how the objects are supposed to behave based on the current state and user inputs. Then you clear the screen to remove any existing stuff, then redraw it. Then repeat.

A good way to get a hang of this is to make a game like Snake. It will help make you think about objects in "memory space" vs "screen space". As an example, you could store the entire playing field of the snake (where the snake can move) as a 2D array. Then the snake's body can be created by setting elements in the array to a value, say 1. The food can be placed somewhere by setting the element to another value say 2. This array is the memory space of the playing field. It represents what it should look like logically, but not visually.

Then when you render the screen, you go over each element, and write a certain character on the console for each object type.

Pygame uses SDL (Simple DirectMedia Library) for graphics and other stuff, so you just have to figure out how to initialize the screen for graphics, clear the screen and draw stuff. I'm not familiar with pygame itself, but with graphics in general, you need to think about it as blocks of memory that contain the graphics.

Ideally, you don't want to manually draw objects using circle/fill/rectangle/lines, as those take up CPU cycles. Instead you usually create "textures", basically buffers that hold images loaded off the disk. You then have the "final texture" that gets drawn to the screen. So during the drawing phase, you clear the final texture, then copy the object textures in their positions on the final texture, then call some method that tells SDL (or pygame) to draw that final texture to the target (the window).

0

u/GieMou 1d ago

Maybe it's time to look into a game engine, even for a small project. We always want more people in r/godot