Searching...
Flashcards in this deck (41)
  • What does import pygame do in a Python game file?

    Imports the Pygame library, giving access to graphics, sound, and input functions.

    pygame setup
  • Why use from pygame.locals import *?

    Imports constants like QUIT, K_UP, K_DOWN so they can be used without the pygame.locals. prefix.

    pygame setup
  • What does pygame.init() do?

    Initializes all Pygame modules (font, mixer, display, etc.) and must be called before most Pygame functions.

    pygame setup
  • What is the purpose of setting fps = 60?

    Sets the target frames per second, controlling how many times the game loop runs per second and game speed.

    pygame timing
  • What does fpsClock = pygame.time.Clock() create?

    Creates a Clock object used to control the frame rate by calling .tick(fps) each loop.

    pygame timing
  • What do width, height = 640, 480 define?

    Defines the width and height in pixels of the game window.

    pygame display
  • What does screen = pygame.display.set_mode((width, height)) do?

    Creates the game window Surface where everything will be drawn.

    pygame display
  • What is TILE_WIDTH = 16 used for in an isometric grid?

    Specifies the width (base) in pixels of one isometric tile, affecting horizontal spacing.

    isometric tiles
  • Why calculate TILE_WIDTH_HALF = TILE_WIDTH/2?

    Pre-calculates half the tile width to speed up isometric conversion formulas.

    isometric tiles
  • What is TILE_HEIGHT = 8 used for in an isometric grid?

    Specifies the height (base) in pixels of one isometric tile, affecting vertical spacing.

    isometric tiles
  • Why calculate TILE_HEIGHT_HALF = TILE_HEIGHT/2?

    Pre-calculates half the tile height for use in isometric conversion formulas.

    isometric tiles
  • What does class Player(): define?

    Defines a Player object type that bundles data (position, image) and behaviors (update, render).

    python classes
  • What is the role of def __init__(self, gridx, gridy, image): in the Player class?

    Constructor method that runs when creating a Player and sets up its initial state.

    python classes
  • What does self.gridx represent for a Player?

    The player's column on the logical isometric grid used for movement logic.

    isometric player
  • What does self.gridy represent for a Player?

    The player's row on the logical isometric grid used for movement logic.

    isometric player
  • What is stored in self.image for a Player?

    The Pygame Surface (picture) that represents the player on screen.

    pygame player
  • What is the isometric formula for a Player's screen X coordinate?

    The formula is \(\text{self.x} = (\text{self.gridx} - \text{self.gridy}) \times \text{TILE\_WIDTH\_HALF}\).

    isometric formulas
  • What is the isometric formula for a Player's screen Y coordinate?

    The formula is \(\text{self.y} = (\text{self.gridx} + \text{self.gridy}) \times \text{TILE\_HEIGHT\_HALF}\).

    isometric formulas
  • What does def update(self, udlr): do in the Player class?

    Method that changes the player's state (position) based on input and is called once per frame.

    python player
  • What is the udlr parameter passed to Player.update?

    A tuple of four booleans (up, down, left, right) indicating which arrow keys are pressed.

    input player
  • What does u, d, l, r = udlr accomplish inside update?

    Unpacks the udlr tuple into four variables for easier use inside the method.

    python player
  • What happens when if u: self.gridy -= 1 executes?

    If the up arrow is pressed, the player's grid row decreases, moving the player up on the grid.

    input movement
  • What happens when elif d: self.gridy += 1 executes?

    If the down arrow is pressed, the player's grid row increases, moving the player down on the grid.

    input movement
  • What happens when elif l: self.gridx -= 1 executes?

    If the left arrow is pressed, the player's grid column decreases, moving the player left on the grid.

    input movement
  • What happens when elif r: self.gridx += 1 executes?

    If the right arrow is pressed, the player's grid column increases, moving the player right on the grid.

    input movement
  • Why recalculate self.x and self.y at the end of update?

    To update the player's screen position after changing the grid coordinates using the isometric formulas.

    isometric player
  • What does update recalculate after the grid position changes?

    Recalculates the screen Y position after the grid position has changed.

    player update
  • What is the purpose of def render(self, screen): in the Player class?

    A method that draws the player onto the given screen surface at its current screen coordinates.

    player render
  • What does screen.blit(self.image, (self.x, self.y)) do?

    Copies the player's image onto the screen at the calculated position.

    render blit
  • What does pygame.image.load('player.png').convert_alpha() do?

    Loads an image file from disk and optimises it for fast drawing with transparency.

    assets image
  • What does player = Player(30, 30, player_img) create?

    Creates a Player object starting at grid position (30,30) using the loaded image.

    player instance
  • What is the role of while True: in a Pygame program?

    The infinite loop that keeps the game running; each iteration is one frame.

    loop game
  • What does for event in pygame.event.get(): do?

    Loops through all events (key presses, mouse clicks, window closing) since the last frame.

    events input
  • What does if event.type == QUIT: check for?

    Checks if the user clicked the window's close button so the game should exit.

    events quit
  • Why are pygame.quit() and exit() used together?

    pygame.quit() uninitialises Pygame; exit() stops the Python script to quit cleanly.

    quit cleanup
  • What does screen.fill((30, 30, 30)) accomplish each frame?

    Fills the entire screen with a dark grey colour and erases everything from the previous frame.

    render screen
  • What does inputs = pygame.key.get_pressed() return?

    The current state of all keyboard keys as a list where each index is a key with True/False.

    input keyboard
  • What is inputs_udlr = (inputs[K_UP], inputs[K_DOWN], inputs[K_LEFT], inputs[K_RIGHT]) used for?

    Creates a tuple of the four arrow key states to pass to the player's update method.

    input controls
  • What does player.update(inputs_udlr) do in the main loop?

    Calls the player's update method, passing arrow key states so the player can move.

    player update
  • What is the effect of pygame.display.flip()?

    Updates the entire screen to show everything drawn since the last flip, making the new frame visible.

    display flip
  • What does fpsClock.tick(fps) control?

    Pauses enough to keep the loop running at the target FPS, preventing the game from running too fast.

    performance timing
Study Notes

Overview

  • These notes summarize a minimal Pygame setup and an isometric grid player implementation.
  • Focus: initialization, coordinate conversion for isometric tiles, Player class (state, update, render), input & game loop, resource loading, and quitting.

Pygame setup (basic boilerplate)

  • Import Pygame: import pygame — gives access to graphics, sound, input, etc.
  • Helpful constants: from pygame.locals import * — allows QUIT, K_UP, K_DOWN, etc. without prefixing.
  • Initialize modules: pygame.init() — run before using most Pygame features.
  • Create window size variables: width, height = 640, 480.
  • Create the display surface: screen = pygame.display.set_mode((width, height)).
  • Control FPS: set fps = 60 and create a clock with fpsClock = pygame.time.Clock().

Key constants for isometric grid

  • Tile size definitions (example values):
  • TILE_WIDTH = 16 — tile base width in pixels.
  • TILE_WIDTH_HALF = TILE_WIDTH/2 — precomputed half-width (used in formulas).
  • TILE_HEIGHT = 8 — tile height in pixels.
  • TILE_HEIGHT_HALF = TILE_HEIGHT/2 — precomputed half-height.

  • Math (screen conversion helper):

  • \(TILE\_WIDTH\_HALF = TILE\_WIDTH / 2\)
  • \(TILE\_HEIGHT\_HALF = TILE\_HEIGHT / 2\)

Isometric coordinate conversion (core formulas)

  • Convert logical grid coordinates (grid_x, grid_y) to screen pixel coordinates (x,y):
  • \(x = (grid_x - grid_y) * TILE\_WIDTH\_HALF\)
  • \(y = (grid_x + grid_y) * TILE\_HEIGHT\_HALF\)

  • Meaning:

  • Subtracting columns and rows yields the diagonal X offset that produces the isometric horizontal spacing.
  • Adding columns and rows yields the vertical stacking for the isometric perspective.

Player class: structure and responsibilities

  • Declaration: class Player(): — bundles data (position, sprite) and behaviour (update, render).

  • Constructor: def __init__(self, gridx, gridy, image):

  • Stores logical grid coords: self.gridx, self.gridy.
  • Stores the image/sprite self.image (a Pygame Surface).
  • Computes screen coords using conversion formulas and assigns self.x, self.y.
  • Example calculations after init:

    • \(self.x = (self.gridx - self.gridy) * TILE\_WIDTH\_HALF\)
    • \(self.y = (self.gridx + self.gridy) * TILE\_HEIGHT\_HALF\)
  • Attributes to remember:

  • self.gridx, self.gridy — logical grid column and row.
  • self.image — sprite Surface.
  • self.x, self.y — screen pixel coordinates (updated when grid coords change).

Movement: update method and input handling

  • Signature: def update(self, udlr):udlr is a tuple of four booleans: (up, down, left, right).
  • Unpack: u, d, l, r = udlr for clarity.
  • Movement rules (one-axis-per-frame style using if/elif):
  • If u then self.gridy -= 1 (move up on grid).
  • Elif d then self.gridy += 1 (move down on grid).
  • Elif l then self.gridx -= 1 (move left on grid).
  • Elif r then self.gridx += 1 (move right on grid).
  • After changing grid coords, recompute screen position:
  • \(self.x = (self.gridx - self.gridy) * TILE\_WIDTH\_HALF\)
  • \(self.y = (self.gridx + self.gridy) * TILE\_HEIGHT\_HALF\)

  • Notes:

  • Using if/elif enforces a single direction per update; modify logic if diagonal or simultaneous movement is desired.
  • Keep grid coords as integers when the grid is tile-based.

Rendering the player

  • Method: def render(self, screen): — draws the player sprite at the current screen coordinates.
  • Draw call: screen.blit(self.image, (self.x, self.y)) — blits the Surface to the display.
  • Ensure screen is cleared or tiled background drawn before rendering each frame (e.g., screen.fill((30,30,30))).

Game loop: order of operations (one frame)

  1. Event handling: for event in pygame.event.get(): to process events.
  2. Quit event: if event.type == QUIT: then call pygame.quit() and exit() to quit cleanly.
  3. Clear or draw background: screen.fill((30, 30, 30)) or draw tiles.
  4. Poll keyboard state: inputs = pygame.key.get_pressed().
  5. Build directional tuple: inputs_udlr = (inputs[K_UP], inputs[K_DOWN], inputs[K_LEFT], inputs[K_RIGHT]).
  6. Update game objects: player.update(inputs_udlr).
  7. Render objects: player.render(screen) (and other drawing, e.g., map tiles).
  8. Present frame: pygame.display.flip() — updates the entire display.
  9. Cap framerate: fpsClock.tick(fps) — delays so the loop runs at ~fps frames/sec.

Resource loading and optimisation

  • Load a sprite with transparency: player_img = pygame.image.load('player.png').convert_alpha().
  • convert_alpha() optimises blitting and preserves per-pixel alpha.
  • Create objects using loaded assets: player = Player(30, 30, player_img) — starts at grid (30,30).

Quitting and cleanup

  • Proper sequence on quit:
  • Call pygame.quit() to uninitialise Pygame subsystems.
  • Call exit() (or sys.exit()) to stop the Python program.

Tips, common pitfalls, and extensions

  • Tile alignment: ensure your tile image origin matches the coordinates used for blitting (usually tile top or a specific anchor point).
  • Sub-pixel movement: for smooth camera or animated movement, allow fractional screen coords but keep grid indices integral for tile logic.
  • Input smoothing: consider debouncing or continuous movement logic if you want the player to move continuously when a key is held.
  • Drawing order: for isometric scenes, sort drawables by grid_x + grid_y (or y) so closer tiles/sprites render after farther ones.
  • Performance: batch tile draws, minimise per-frame surface conversions, and reuse loaded images.

Minimal example flow (pseudocode)

  • Initialization: imports, pygame.init(), set mode, load images, create Player, create Clock.
  • Loop: handle events -> clear screen -> read keys -> update player -> draw tiles & player -> pygame.display.flip() -> fpsClock.tick(fps).