Ever wondered how games actually work behind the scenes? In this beginner-friendly guide, we'll break down the fundamental structure of a game and how all the pieces fit together.
The Basic Game Structure
At its core, every game follows a similar structure with these key components:
- Game States - Different modes your game can be in
- Game Objects - The characters, items, and elements in your game
- Game Loop - The heartbeat of your game that keeps everything running
- Input Handling - How your game responds to player actions
- Rendering - Drawing everything to the screen
Game States
Games typically have different states that control what is happening at any given moment:
- LOADING - When the game is loading assets
- MENU - The main menu where players select options
- PLAYING - The actual gameplay
- PAUSED - When the game is temporarily stopped
- GAME_OVER - When the player has lost
- WIN - When the player has won
Here's a simple example of how game states might be implemented:
// Define game states as constants
const GameState = {
LOADING: 0,
MENU: 1,
PLAYING: 2,
PAUSED: 3,
GAME_OVER: 4,
WIN: 5
};
// Current state of the game
let currentState = GameState.MENU;
// Function to change game state
function changeGameState(newState) {
currentState = newState;
// Do something based on the new state
switch(currentState) {
case GameState.MENU:
showMainMenu();
break;
case GameState.PLAYING:
startGameplay();
break;
case GameState.GAME_OVER:
showGameOverScreen();
break;
}
}
Game Objects
Game objects are the entities that exist in your game world. Each object typically has:
- Position - Where the object is located (x, y coordinates)
- Size - How big the object is (width, height)
- Appearance - How the object looks (image, color, etc.)
- Behavior - What the object does (moves, collides, etc.)
Here's a simple example of a player object:
// A simple player object
const player = {
x: 100, // x position
y: 200, // y position
width: 32, // width in pixels
height: 48, // height in pixels
speed: 5, // movement speed
health: 100, // player health
isJumping: false, // jumping state
// Update the player's position
update: function() {
// Move player based on input
if (keyIsPressed.right) {
this.x += this.speed;
}
if (keyIsPressed.left) {
this.x -= this.speed;
}
// Apply gravity if jumping
if (this.isJumping) {
// Jumping physics code here
}
},
// Draw the player on screen
draw: function(ctx) {
ctx.fillStyle = "blue";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
The Game Loop
The game loop is the heart of any game. It continuously runs and performs these steps:
- Process Input - Check for player input (keyboard, mouse, etc.)
- Update Game State - Update positions, check collisions, etc.
- Render - Draw everything to the screen
- Repeat - Do it all again!
Here's a simple game loop implementation:
// Get the canvas and context
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
// Game objects
const gameObjects = [];
gameObjects.push(player);
// Last time the loop was run
let lastTime = 0;
// The main game loop
function gameLoop(timestamp) {
// Calculate delta time (time since last frame)
const deltaTime = timestamp - lastTime;
lastTime = timestamp;
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Only run game logic if we're in PLAYING state
if (currentState === GameState.PLAYING) {
// Update all game objects
for (let obj of gameObjects) {
obj.update(deltaTime);
}
// Check for collisions
checkCollisions();
}
// Draw all game objects
for (let obj of gameObjects) {
obj.draw(ctx);
}
// Draw UI elements based on game state
drawUI();
// Request the next frame
requestAnimationFrame(gameLoop);
}
// Start the game loop
requestAnimationFrame(gameLoop);
Input Handling
Games need to respond to player input. Here's a simple way to track keyboard input:
// Object to track which keys are pressed
const keyIsPressed = {
up: false,
down: false,
left: false,
right: false,
space: false
};
// Set up event listeners for keyboard input
window.addEventListener("keydown", function(e) {
switch(e.key) {
case "ArrowUp":
keyIsPressed.up = true;
break;
case "ArrowDown":
keyIsPressed.down = true;
break;
case "ArrowLeft":
keyIsPressed.left = true;
break;
case "ArrowRight":
keyIsPressed.right = true;
break;
case " ":
keyIsPressed.space = true;
break;
}
});
window.addEventListener("keyup", function(e) {
switch(e.key) {
case "ArrowUp":
keyIsPressed.up = false;
break;
case "ArrowDown":
keyIsPressed.down = false;
break;
case "ArrowLeft":
keyIsPressed.left = false;
break;
case "ArrowRight":
keyIsPressed.right = false;
break;
case " ":
keyIsPressed.space = false;
break;
}
});
Collision Detection
Detecting when game objects collide is a fundamental part of most games. Here's a simple example of collision detection between rectangles:
// Check if two rectangles are colliding
function isColliding(objA, objB) {
return objA.x < objB.x + objB.width &&
objA.x + objA.width > objB.x &&
objA.y < objB.y + objB.height &&
objA.y + objA.height > objB.y;
}
// Check all game objects for collisions
function checkCollisions() {
// Example: Check if player is colliding with any enemies
for (let enemy of enemies) {
if (isColliding(player, enemy)) {
// Handle collision (e.g., player takes damage)
player.health -= 10;
// Check if player died
if (player.health <= 0) {
changeGameState(GameState.GAME_OVER);
}
}
}
}
Putting It All Together
When you combine all these elements, you have the basic structure of a game! Here's what the flow looks like:
- Initialize the game (set up canvas, load assets, create objects)
- Start in the MENU state
- When player starts the game, change to PLAYING state
- Game loop runs continuously:
- Process player input
- Update all game objects
- Check for collisions
- Draw everything to the screen
- If player wins or loses, change to WIN or GAME_OVER state
- Allow player to restart or return to menu
Next Steps
Now that you understand the basics, try creating a simple game yourself! Start with something small like a basic platformer or a simple shooting game. Remember, every complex game is built on these same fundamental principles.
Happy coding and game creating!