Consica Labs

Consica Labs
Chapter 12

Simple Game Logic

Building collider bounds and point loops

Definition

Game logic combines events, motion, loops, variable updates, and sensing checks to build playable interactive mechanics. Key concepts include Hat Block.

Think of Simple Game Logic as:

Director script
Grid movements
Trigger alarms
Costume racks

Just as an actor changes costume or walks across the theater grid on cue, Simple Game Logic dictates sprite behavior.

Real-Life Example

Just as you coordinate actions in real life, Simple Game Logic works by structuring logic commands in sequence:

  1. 1 Register the trigger event block.
  2. 2 Run calculations or movements within a continuous control block.
  3. 3 Update values or graphics on the stage viewport.

Key Highlights:

  • Trigger event
  • Logic evaluation
  • Visual update

Interactive Diagram

Launch the interactive diagram to see this in action.

Open Interactive Diagram

The interactive diagram for this chapter demonstrates Simple Game Logic. It shows a simple game example showing scoring, lives, collision detection, and win/lose conditions.

What to explore:

  • play the mini-game; watch the score update; trigger a collision; see the game over screen appear
  • games use a combination of loops, conditions, variables, and events to create interactive experiences with rules and goals

Introduction

Every game needs rules. What happens when the player collects a coin? When does the game end? How do enemies behave? Game logic is the set of rules and systems that make a game work. It determines how sprites interact, how scoring works, how levels progress, and when the player wins or loses. Without game logic, you just have sprites moving around with no purpose.

Game logic in Scratch combines all the concepts you have learned — events, loops, conditions, variables, and broadcasts — into a working game system. The most important pattern is the game loop: a 'forever' loop that runs constantly, checking for input, updating positions, detecting collisions, and evaluating win/loss conditions. This loop runs approximately 30 times per second, creating the feeling of a responsive, living world.

In this chapter, you will learn how to design and build game logic systems in Scratch. You will explore common game patterns including scoring, lives, level progression, collision handling, and win/loss conditions. By the end, you will be able to design your own game logic for any type of game.

How It Works

The core of any game is the game loop. In Scratch, this is typically a 'forever' loop inside a 'when green flag clicked' script. Each iteration of the loop (each frame) does three things: read input (check which keys are pressed or where the mouse is), update state (move sprites, change variables, check collisions), and render (the stage automatically updates to show the new state). This read-update-render cycle is the foundation of all video games.

Scoring is implemented with variables. Create a 'score' variable (for all sprites), then use 'change score by (10)' whenever the player achieves something (collecting a coin, defeating an enemy, reaching a goal). Display the score on stage using the variable monitor. To implement a high score, compare the current score to a 'high score' variable and update if the current score is greater.

Household Object Analogy

Think of game logic like a referee in a sports game. The referee (game loop) constantly watches the game. When a player scores (condition), the referee adds points to the scoreboard (variable) and checks if the game is over (win condition). The referee enforces the rules (game logic) and responds to events (goals, fouls, timeouts) as they happen. Without the referee, there would be chaos.

Deeper Dive

Lives systems are another common game logic pattern. Create a 'lives' variable starting at 3 (or whatever number). When the player collides with a hazard, subtract 1 from lives. After losing a life, give the player a brief invincibility period (use a 'wait' block or a timer variable) to prevent instant death from multiple collisions. When lives reach 0, broadcast 'game over'. This pattern is used in countless games from Mario to Sonic to modern platformers.

Level progression involves multiple levels or stages. Use a 'level' variable that increments when the player reaches a goal. The 'level' variable can control enemy speed (enemies move faster at higher levels), number of obstacles, target score to advance, or which backdrop is shown. Each level can be harder than the last. The level transition typically involves resetting player position, clearing hazards, and setting up the new level's parameters.

Collision detection in Scratch uses the 'touching' blocks. These check for pixel-perfect overlap between sprites, sprite-edge boundaries, or sprite-color matches. For performance, you can optimize by only checking collisions that are likely. For example, before using the 'touching' block, first check if sprites are roughly near each other using x/y distance calculations. This is called broad-phase collision detection.

Key Insight

Good game logic separates 'what happens' from 'how it looks'. Keep score, lives, and game state in variables (the model). Use broadcasts to signal game events (the controller). Let sprites respond to broadcasts with visual and sound effects (the view). This model-view-controller (MVC) pattern makes your code easier to debug and modify.

Advanced

State machines are a powerful way to organize game logic. A state machine defines distinct states (like 'menu', 'playing', 'paused', 'game over') and rules for transitioning between them. Use a 'gameState' variable that stores the current state. Each frame, an 'if-else' chain checks the state and runs the appropriate logic. For example: if gameState = 'playing', check input and update positions. If gameState = 'paused', show pause menu and skip updates.

Difficulty scaling adjusts game parameters based on player performance. If the player is doing well (high score, many lives remaining), increase difficulty by making enemies faster or more numerous. If the player is struggling, reduce difficulty. This keeps the game challenging but not frustrating. Implement difficulty scaling with formulas: enemySpeed = baseSpeed + (level * speedIncrease).

Timers add time pressure to games. Use a 'timer' variable that counts down from a starting value. Each frame, decrease timer by the time since the last frame (use the 'timer' Sensing Block). When timer reaches 0, the game ends. Alternatively, use a count-up timer for speedrun-style games where the goal is to complete the level as fast as possible. Display the timer prominently on the stage.

Vocabulary Table

Term Definition
Simple Game LogicThe primary technological concept explaining how components interact within the context of Scratch Programming.
Coordinate GridThe X and Y plane representing the Stage layout coordinates.
Hat BlockA block with a rounded top that registers events to launch scripts.
Sensing BlockA block that checks for collisions, touch parameters, or mouse pointer coordinates.

Fun Facts

The game loop pattern (read-input, update-state, render) has been the foundation of video game programming since the earliest arcade games in the 1970s.

The first video game to use a scoring system was 'Spacewar!' in 1962. It displayed the score as a numeric counter on the screen.

Scratch's 30 FPS frame rate matches the standard frame rate of many animated cartoons and early video game consoles.

The concept of 'lives' in video games was popularized by 'Space Invaders' (1978), which gave the player 3 ships before game over.

The 'reset timer' block in Sensing resets Scratch's built-in timer to 0, which is useful for measuring elapsed time in games.

Common Misconceptions

Misconception: Game logic must be complex to be fun.

Truth: Many successful games have very simple logic. The first 'Flappy Bird' was created in a few days with basic collision and scoring logic. Simple mechanics executed well create engaging gameplay.

Misconception: More sprites always make a better game.

Truth: Each sprite adds complexity to your game logic and potential performance issues. Focus on making a few well-designed sprites with solid interactions rather than many sprites with simple behavior.

Misconception: Collision detection is perfect and instant.

Truth: Scratch collisions are checked once per frame (every ~33ms). At high speeds, a sprite can pass through an obstacle between frames. This is called 'tunneling' and is a known challenge in all game engines, not just Scratch.

Misconception: A game is finished when it has no bugs.

Truth: A game is finished when the game loop is complete, all win/loss conditions work, and the experience is fun. Occasional minor bugs are acceptable in finished games, especially for learning projects.

Knowledge Check

1. What is the main role of Simple Game Logic?

Answer: To orchestrate behaviors and controls visually

2. Which block shape starts a script stack in Scratch?

Answer: Hat block (curved top)

3. What is the maximum X coordinate limit on the stage?

Answer: 240