Overview
TheGame class is the core class of Serenity Valley, responsible for initializing Pygame, managing the game loop, handling events, and rendering the game world.
Class Constants
The following constants are defined at the class level:Path to the background tile image
Path to the button background image
Width of the game screen in pixels
Height of the game screen in pixels
Size of each grid cell in pixels
Dimensions of the game field (width, height)
Constructor
__init__()
Initializes the Game instance, setting up Pygame, the screen, background, widgets, buttons, and game objects.- Initializes Pygame
- Sets up the screen display
- Loads the background tile image
- Creates UI widgets (message boards, buttons, text entries)
- Initializes the game clock and world objects
- Sets up the grid configuration
- Configures game options
Methods
xy2coord()
Converts a pixel coordinate (x, y) to a grid coordinate (row, column).A tuple containing the (x, y) pixel position
(nrow, ncol) representing the grid coordinate
coord2xy_mid()
Converts a grid coordinate (row, column) to a pixel position (x, y) at the center of that grid cell.A tuple containing the (nrow, ncol) grid coordinate
(x, y) representing the pixel position at the center of the grid cell
get_field_rect()
Returns the internal field rectangle, excluding borders.pygame.Rect object representing the internal game field
draw_background()
Draws the tiled background image across the entire screen.draw_grid()
Draws the grid lines on the game field.GRID_SIZE, grid_nrows, and grid_ncols.
draw()
The main drawing method that renders the entire game state.- Draws the background
- Draws the grid (if enabled in options)
- Draws the message board
- Draws all objects in the world
run()
The main game loop that handles events, updates game state, and renders frames.- Limits the frame rate to 30 FPS
- Processes user input events (keyboard, mouse)
- Handles pause/unpause functionality
- Updates game entities
- Calls the draw method
- Flips the display buffer
SPACE: Toggle pauseG: Toggle grid visibility
quit()
Exits the game application.sys.exit() to terminate the program.