Website LogoAbbyDev

The Complete Guide to GDScript Fundamentals: Variables, Arrays, Dictionaries, Static Typing & Beyond

GDScript

Learn GDScript from the ground up with this comprehensive guide. Explore variables, data types, scope, arrays, dictionaries, and static typing - all reinforced with practical game development examples, hands-on exercises, and coding challenges.

Introduction

GDScript is Godot's built-in scripting language, designed specifically for game development. With its Python-like syntax and powerful integration with the Godot engine, GDScript makes game programming accessible to developers of all skill levels.

In this comprehensive guide, we'll explore the fundamentals of GDScript, focusing on variables, data types, and essential programming concepts that form the foundation of game development. Whether you're new to programming or transitioning from other languages, this tutorial will give you the solid foundation you need to start creating games with Godot.

What You Will Learn

Transform from a complete beginner to confident GDScript programmer! This comprehensive guide provides hands-on learning with practical exercises, real game examples, and immediate feedback.

Learning Objectives

Master Core Data Types

  • Declare and manipulate integers, floats, strings, and booleans
  • Work with Arrays for inventories, high scores, and game lists
  • Use Dictionaries for player stats, game settings, and complex data
  • Apply proper naming conventions and coding standards

Understand the Type System

  • Choose between dynamic and static typing for different scenarios
  • Implement type hints for better performance and bug prevention
  • Debug type-related errors effectively

Master Variable Scope & Organization

  • Control variable accessibility (global vs local scope)
  • Organize code with proper scoping strategies
  • Avoid common scoping pitfalls in game development

String Formatting and Interpolation

  • Create dynamic UI text and game messages
  • Use different string formatting methods

Problem-Solving Skills

  • Complete 6 hands-on coding challenges
  • Debug and fix common beginner mistakes
  • Write clean, maintainable game code

Prerequisites

  • No Programming Experience Required - We start from absolute zero
  • Godot Engine 4.x - Free download from godotengine.org
  • Growth Mindset - Ready to learn through practice and experimentation

What is GDScript?

GDScript is a high-level, dynamically typed programming language specifically designed for the Godot game engine.

Why GDScript?

  • Game-Focused: Built specifically for game development with features tailored to common game programming patterns
  • Python-like Syntax: Easy to learn and read, especially for beginners
  • Deep Godot Integration: Seamless access to all Godot features and APIs
  • Performance: Optimized for the Godot engine with excellent performance for game logic
  • Simple Deployment: No external dependencies or compilation steps needed

Your First GDScript Program

Let's start with the traditional "Hello, World!" example.

@tool
extends EditorScript
 
func _run() -> void:
	print("Hello, World!")
	print("Welcome to GDScript!")
	print("Ready to create amazing games!")

Code Breakdown:

  • @tool - Tells Godot this script can run in the editor
  • extends EditorScript - Inherits from EditorScript class
  • func _run() -> void: - Main function that executes our code
  • print() - Outputs text to Godot's console

Expected Output:

Hello, World!
Welcome to GDScript!
Ready to create amazing games!

Code Comments - Your Code Documentation

Good code documentation is essential for maintaining and understanding your game code. GDScript supports two types of comments:

# This is a single-line comment - use for quick explanations
print("This line will execute")
 
"""
This is a multi-line comment.
Use it to document:
- Complex game mechanics
- Function purposes
- Algorithm explanations
- Team collaboration notes
"""

Comments - Best Practices

  • ✅ Explain WHY your code does something, not what it does
  • ✅ Document complex game mechanics or formulas
  • ✅ Add context for future developers (including yourself!)
  • ❌ Don't comment obvious things like var health = 100 # set health to 100

Bad vs Good Comments Example:

# ❌ BAD COMMENTS
func calculate_damage(base_damage, armor, critical_hit):
	var damage = base_damage  # Set damage to base damage
	damage = damage - armor   # Subtract armor from damage
	if critical_hit == true:  # Check if critical hit is true
		damage = damage * 2   # Multiply damage by 2
	return damage             # Return the damage
 
# ✅ GOOD COMMENTS
func calculate_damage(base_damage: int, armor: int, is_critical: bool) -> int:
	"""
	Calculate final damage after armor reduction and critical hit bonuses.
	Uses the game's core combat formula: (base - armor) * crit_multiplier
	"""
	var final_damage = base_damage - armor
 
	# Ensure minimum 1 damage even with high armor (prevents invulnerability)
	final_damage = max(1, final_damage)
 
	# Double damage for critical hits (balances with 15% crit chance)
	if is_critical:
		final_damage *= 2
 
	return final_damage

Understanding Variables in GDScript

Think of variables as labeled boxes that store information for your game. Just like you might have a box labeled "Player Health" containing the number 100, variables let you store and organize all your game data.

In Games, Variables Store Everything

  • Player stats (health, mana, experience)
  • Game settings (volume, difficulty, graphics quality)
  • Dynamic content (current level, score, time remaining)
  • User input (player name, key bindings)

Variable Declaration - Creating Your Data Containers

Variables are created using the var keyword, followed by a name and an optional value.

@tool
extends EditorScript
 
func _run() -> void:
	# Basic variable declaration using 'var'
	var player_name = "Alex"        # Text/String data
	var player_health = 100         # Whole number data
	var is_alive = true             # True/False data
 
	# Display our variables
	print("Player: ", player_name)
	print("Health: ", player_health)
	print("Alive: ", is_alive)

Expected Output:

Player: Alex
Health: 100
Alive: True

Variable Naming - Best Practices

  • ✅ Use descriptive names: player_health not h
  • ✅ snake_case style: current_level not currentLevel
  • ✅ Start with letter: score1 not 1score
  • ✅ No spaces: high_score not high score
  • ❌ Avoid reserved words: Don't use if, while, func

Challenge 1: Create Your RPG Character

Create variables to represent a fantasy RPG character with all essential stats.

Your Task: Create variables for:

  • Character name (your choice!)
  • Health points (1-100)
  • Magic points (1-50)
  • Is the character currently in combat? (true/false)

Then display all the information in a readable format.

Expected Output:

=== CHARACTER SHEET ===
Name: Elara the Mage
Level: 7
HP: 85
MP: 42
In Combat: False

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
func _run() -> void:
	var character_name = "Elara the Mage"
	var health_points = 85
	var magic_points = 42
	var in_combat = false
 
	print("=== CHARACTER SHEET ===")
	print("Name: ", character_name)
	print("HP: ", health_points)
	print("MP: ", magic_points)
	print("In Combat: ", in_combat)

Constants vs Variables - What Never Changes vs What Can Change

Constants are values that NEVER change during your game - they're permanent rules. Variables can change as your game runs.

@tool
extends EditorScript
 
# Constants: Game rules that never change (declared at top level)
const MAX_HEALTH = 100
const GRAVITY_STRENGTH = 9.8
 
func _run() -> void:
	# Variables: Game state that changes during play
	var current_health = MAX_HEALTH    # Start at full health
 
	# Variables can change as the game progresses
	current_health = 75
 
	print("=== GAME STATUS ===")
	print("Max Health: ", MAX_HEALTH)
	print("Current Health: ", current_health)
 
	# MAX_HEALTH = 150 # This would cause an error - constants cannot change

Expected Output:

=== GAME STATUS ===
Max Health: 100
Current Health: 75

When to Use Each

Use CONSTANTS for:

  • Game rules (max health, speed limits, damage values)
  • Configuration settings (screen size, file paths)
  • Mathematical values (gravity, physics constants)
  • Unchanging text (game title, version number)

Use VARIABLES for:

  • Player stats (current health, score, level)
  • Game state (is paused, current scene)
  • Dynamic content (enemy positions, inventory items)
  • User input (player name, settings)

Challenge 2: Game Configuration System

Create a game configuration system using both constants and variables appropriately.

Your Task: Create a simple game settings system with:

Constants (never change):

  • Game name: "Space Explorer"
  • Max players: 4
  • Base movement speed: 5.0

Variables (can change):

  • Current players online: 2
  • Current volume level: 75 (0-100)
  • Graphics quality: "High" (can be "Low", "Medium", "High")

Expected Output:

=== GAME CONFIGURATION ===
Game: Space Explorer v1.2.3
Players Online: 2/4
Volume: 75%
Graphics: High
Base Speed: 5
Server Status: Online

--- AFTER SETTINGS CHANGE ---
Volume: 85%
Players Online: 3/4

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
# Constants: Core game rules (never change)
const GAME_NAME = "Space Explorer"
const MAX_PLAYERS = 4
const BASE_MOVEMENT_SPEED = 5.0
const VERSION = "1.2.3"
 
func _run() -> void:
	# Variables: Current game state (changes during play)
	var current_players = 2
	var volume_level = 75
	var graphics_quality = "High"
	var server_online = true
 
	# Display game configuration
	print("=== GAME CONFIGURATION ===")
	print("Game: ", GAME_NAME, " v", VERSION)
	print("Players Online: ", current_players, "/", MAX_PLAYERS)
	print("Volume: ", volume_level, "%")
	print("Graphics: ", graphics_quality)
	print("Base Speed: ", BASE_MOVEMENT_SPEED)
	print("Server Status: Online" if server_online else "Offline")
 
	# Simulate settings change
	volume_level = 85  # User adjusted volume
	current_players = 3  # Another player joined
 
	print("\n--- AFTER SETTINGS CHANGE ---")
	print("Volume: ", volume_level, "%")
	print("Players Online: ", current_players, "/", MAX_PLAYERS)

GDScript Data Types - The Building Blocks of Your Game

Data types are like different kinds of containers for different kinds of information. Just like you wouldn't store water in a cardboard box, different types of data need different types of containers.

Game Development Data Types Overview

  • Integers - Whole numbers (score, lives, level)
  • Floats - Decimal numbers (speed, damage multiplier, time)
  • Strings - Text data (player names, dialogue, UI text)
  • Booleans - True/False values (is alive, game paused, has key)
  • Arrays - Lists of items (inventory, high scores)
  • Dictionaries - Complex data with labels (player stats, settings)

Basic Data Types for Every Game

1. Integers (int) - Counting and Scoring

Integers are whole numbers without decimal points - perfect for things you count.

@tool
extends EditorScript
 
func _run() -> void:
	# Game stats using integers
	var score = 1500
	var lives = 3
 
	print("=== PLAYER STATISTICS ===")
	print("Score: ", score)
	print("Lives: ", lives)

Perfect for Integers

  • Scores, points, currency
  • Lives, attempts, tries remaining
  • Levels, rounds, waves

2. Floating-Point Numbers (float) - Precision and Movement

Floats are numbers with decimal points - essential for smooth movement, precise timing, and realistic physics.

@tool
extends EditorScript
 
func _run() -> void:
	var player_speed = 5.5        # Units per second
	var damage_multiplier = 1.75  # Critical hit multiplier
 
	var distance_traveled = player_speed * 10.0
	var critical_damage = 20 * damage_multiplier
 
	print("Distance in 10s: ", distance_traveled, " units")
	print("Critical Damage: ", critical_damage, " HP")

Perfect for Floats

  • Movement speed, acceleration, velocity, physics values
  • Time values (seconds, duration, cooldowns)
  • Multipliers (damage, experience, speed boosts)

3. Strings - Text, Dialogue, and UI Messages

Strings store text - everything your players read in your game comes from strings.

@tool
extends EditorScript
 
func _run() -> void:
	# Game text using strings
	var player_name = "DragonSlayer42"
	var guild_name = "The Crimson Knights"
	var welcome_message = "Welcome to the adventure!"
 
	# String operations for dynamic messages
	var full_greeting = welcome_message + " " + player_name
	var guild_announcement = player_name + " has joined " + guild_name + "!"
 
	# Multi-line strings for stories/dialogue
	var quest_dialogue = """
	The old wizard strokes his beard thoughtfully...
 
	'Ah, brave adventurer! I have been expecting you.
	The kingdom faces a terrible threat, and only
	you can save us from the approaching darkness.'
	"""
	print(quest_dialogue)

Expected Output:

=== GAME MESSAGES ===
Welcome to the adventure! DragonSlayer42
DragonSlayer42 has joined The Crimson Knights!

	The old wizard strokes his beard thoughtfully...

	'Ah, brave adventurer! I have been expecting you.
	The kingdom faces a terrible threat, and only
	you can save us from the approaching darkness.'

Perfect for Strings

  • Player names, character names, item names
  • Dialogue, story text, descriptions
  • UI text (buttons, menus, instructions)

Challenge 3: Dynamic Dialogue System

Create a dialogue system that builds personalized messages for different players.

Your Task: Create a character greeting system that:

  • Takes a player name and character class
  • Builds a welcome message with their info
  • Shows their status in all caps for dramatic effect
  • Counts the total characters in their full title

Expected Output:

=== CHARACTER INTRODUCTION ===
ZARA THE FIRE MAGE HAS ARRIVED!
Greetings, Elite Zara the Fire Mage! Welcome to the magical academy.
Title length: 23 characters
Whispered name: zara

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
func _run() -> void:
	# Player information
	var player_name = "Zara"
	var character_class = "Fire Mage"
	var guild_rank = "Elite"
 
	# Build dynamic dialogue
	var character_title = player_name + " the " + character_class
	var full_title = guild_rank + " " + character_title
	var dramatic_entrance = character_title.to_upper() + " HAS ARRIVED!"
	var welcome_message = "Greetings, " + full_title + "! Welcome to the magical academy."
 
	# Character info display
	print("=== CHARACTER INTRODUCTION ===")
	print(dramatic_entrance)
	print(welcome_message)
	print("Title length: ", len(full_title), " characters")
	print("Whispered name: ", player_name.to_lower())

4. Booleans (bool) - Game State and Conditions

Booleans are like switches - they're either ON (true) or OFF (false). Perfect for tracking game states and making decisions.

@tool
extends EditorScript
 
func _run() -> void:
	# Game state tracking with booleans
	var player_has_key = true
	var boss_defeated = false
	var game_paused = false
 
	# Boolean logic for game mechanics
	var can_enter_castle = player_has_key and boss_defeated
	var game_is_active = not game_paused
 
	print("Boss Defeated: ", boss_defeated)
	print("Game Active: ", game_is_active)
	print("Can Enter Castle: ", can_enter_castle)

Expected Output:

Boss Defeated: false
Game Active: true
Can Enter Castle: false

Boolean Logic Operators

  • and - Both conditions must be true
  • or - At least one condition must be true
  • not - Flips true to false, false to true

Perfect for Booleans

  • Game states (paused, game over, level complete)
  • Player abilities (can jump, has weapon, is invincible)
  • Item ownership (has key, owns upgrade, unlocked level)

Advanced Data Types for Game Development

Arrays - Lists and Collections

Arrays are like containers that hold multiple items in order. Perfect for inventories, high score lists, and any collection of similar items.

@tool
extends EditorScript
 
func _run() -> void:
	# Different types of game arrays
	var player_inventory = ["Iron Sword", "Health Potion", "Magic Key", "Gold Coins"]
	var high_scores = [2500, 2100, 1800, 1500, 1200]
 
	print("=== PLAYER DATA ===")
	print("Inventory: ", player_inventory)
	print("Inventory Size: ", player_inventory.size(), " items")
	print("First Item: ", player_inventory[0])
	print("Last Item: ", player_inventory[-1])  # -1 gets the last item
 
	# Array operations - modifying the list
	player_inventory.append("Fire Scroll")        # Add to end
	player_inventory.insert(1, "Shield")          # Add at position 1
	var removed_item = player_inventory.pop_back() # Remove and return last item
 
	print("\nAfter modifications:")
	print("Updated Inventory: ", player_inventory)
	print("Removed item: ", removed_item)
 
	# Checking for items
	if "Magic Key" in player_inventory:
		print("✅ Player can unlock secret doors!")
 
	if "Poison Antidote" in player_inventory:
		print("✅ Player is protected from poison")
	else:
		print("⚠️  Player vulnerable to poison attacks")
 
	print("=== Looping the Arrays ===")
	var player_inventory_2 = ["val1", "val2", 100, 9.8]
	for i in range(player_inventory_2.size()):
		var value = player_inventory_2[i]
		print(value)

Expected Output:

=== PLAYER DATA ===
Inventory: [Iron Sword, Health Potion, Magic Key, Gold Coins]
Inventory Size: 4 items
First Item: Iron Sword
Last Item: Gold Coins

After modifications:
Updated Inventory: [Iron Sword, Shield, Health Potion, Magic Key, Gold Coins]
Removed item: Fire Scroll

✅ Player can unlock secret doors!
⚠️  Player vulnerable to poison attacks

=== Looping the Arrays ===
val1
val2
100
9.8

Perfect for Arrays:

  • Inventories and item collections
  • High scores and leaderboards
  • Enemy lists and spawn queues

Challenge 4: Inventory Management System

Create an RPG inventory system that manages different types of items with full functionality.

Your Task: Build an inventory system with:

  • Starting items: ["Health Potion", "Rusty Sword", "Bread"]
  • Add a "Magic Ring" to the inventory
  • Remove "Bread" from the inventory
  • Check if player has "Health Potion"
  • Display final inventory count and contents

Expected Output:

=== INVENTORY MANAGEMENT ===
Starting inventory: [Health Potion, Rusty Sword, Bread]
Items: 3/10

✅ Added Magic Ring
✅ Consumed Bread

Healing available: True

=== FINAL INVENTORY ===
Items: 3/10
Contents: [Health Potion, Rusty Sword, Magic Ring]
1. Health Potion
2. Rusty Sword
3. Magic Ring

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
func _run() -> void:
	# Starting inventory
	var inventory = ["Health Potion", "Rusty Sword", "Bread"]
	var max_inventory_size = 10
 
	print("=== INVENTORY MANAGEMENT ===")
	print("Starting inventory: ", inventory)
	print("Items: ", inventory.size(), "/", max_inventory_size)
 
	# Add new item
	inventory.append("Magic Ring")
	print("\n✅ Added Magic Ring")
 
	# Remove unwanted item
	if "Bread" in inventory:
		inventory.erase("Bread")  # Remove first occurrence
		print("✅ Consumed Bread")
 
	# Check for healing items
	var has_healing = "Health Potion" in inventory
	print("\nHealing available: ", has_healing)
 
	# Display final state
	print("\n=== FINAL INVENTORY ===")
	print("Items: ", inventory.size(), "/", max_inventory_size)
	print("Contents: ", inventory)
 
	# Show each item with index
	for i in range(inventory.size()):
		print(str(i + 1) + ". " + inventory[i])

Dictionaries - Complex Game Data

Dictionaries store information with labels (keys) instead of positions. Perfect for complex game data like character stats, settings, and save files.

@tool
extends EditorScript
 
func _run() -> void:
	# Complex player character data
	var player_character = {
		"name": "Zara the Brave",
		"class": "Paladin",
		"level": 12,
		"health": 85,
		"max_health": 100,
		"mana": 45,
		"max_mana": 60,
		"stats": {
			"strength": 18,
			"defense": 15,
			"magic": 12,
			"speed": 14
		},
		"equipment": {
			"weapon": "Holy Sword +2",
			"armor": "Blessed Plate Mail",
			"accessory": "Ring of Protection"
		},
		"inventory_gold": 1250,
		"experience": 34750,
		"location": "Crystal Cave - Level 3"
	}
 
	print("=== CHARACTER PROFILE ===")
	print("Name: ", player_character["name"])
	print("Class: ", player_character["class"], " (Level ", player_character["level"], ")")
	print("Location: ", player_character["location"])
 
	print("\n=== COMBAT STATS ===")
	print("Health: ", player_character["health"], "/", player_character["max_health"])
	print("Mana: ", player_character["mana"], "/", player_character["max_mana"])
	print("Strength: ", player_character["stats"]["strength"])
	print("Defense: ", player_character["stats"]["defense"])
 
	print("\n=== EQUIPMENT ===")
	print("Weapon: ", player_character["equipment"]["weapon"])
	print("Armor: ", player_character["equipment"]["armor"])
 
	print("\n=== RESOURCES ===")
	print("Gold: ", player_character["inventory_gold"], " coins")
	print("Experience: ", player_character["experience"], " XP")
 
	# Modify character data (level up!)
	player_character["level"] += 1
	player_character["max_health"] += 5
	player_character["health"] = player_character["max_health"]  # Full heal on level up
	player_character["stats"]["strength"] += 1
 
	print("\n🎉 LEVEL UP! 🎉")
	print("New Level: ", player_character["level"])
	print("New Max Health: ", player_character["max_health"])
	print("New Strength: ", player_character["stats"]["strength"])

Expected Output:

=== CHARACTER PROFILE ===
Name: Zara the Brave
Class: Paladin (Level 12)
Location: Crystal Cave - Level 3

=== COMBAT STATS ===
Health: 85/100
Mana: 45/60
Strength: 18
Defense: 15

=== EQUIPMENT ===
Weapon: Holy Sword +2
Armor: Blessed Plate Mail

=== RESOURCES ===
Gold: 1250 coins
Experience: 34750 XP

🎉 LEVEL UP! 🎉
New Level: 13
New Max Health: 105
New Strength: 19

Perfect for Dictionaries:

  • Character stats and attributes
  • Game settings and configuration
  • Save game data and progress

Challenge 5: Character Stats Management

Create a complete character management system using dictionaries to handle complex player data.

Your Task: Build a character system that:

  • Stores player info (name, class, level, stats, equipment)
  • Updates health after taking 20 damage
  • Adds 150 experience points
  • Upgrades weapon from "Iron Sword" to "Steel Sword"
  • Shows before and after comparison

Expected Output:

=== BEFORE ADVENTURE ===
Thorin the Warrior
Health: 95/100
Experience: 2450 XP
Weapon: Iron Sword

=== AFTER ADVENTURE ===
Health: 75/100
Experience: 2600 XP
Weapon: Steel Sword

✅ Adventure completed successfully!

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
func _run() -> void:
	# Complete character data structure
	var character = {
		"name": "Thorin",
		"class": "Warrior",
		"level": 8,
		"health": 95,
		"max_health": 100,
		"experience": 2450,
		"stats": {
			"strength": 16,
			"defense": 12,
			"agility": 10
		},
		"equipment": {
			"weapon": "Iron Sword",
			"armor": "Chain Mail",
			"shield": "Wooden Shield"
		}
	}
 
	print("=== BEFORE ADVENTURE ===")
	print(character["name"], " the ", character["class"])
	print("Health: ", character["health"], "/", character["max_health"])
	print("Experience: ", character["experience"], " XP")
	print("Weapon: ", character["equipment"]["weapon"])
 
	# Adventure events!
	character["health"] -= 20  # Took damage in battle
	character["experience"] += 150  # Gained XP from victory
	character["equipment"]["weapon"] = "Steel Sword"  # Found upgrade
 
	print("\n=== AFTER ADVENTURE ===")
	print("Health: ", character["health"], "/", character["max_health"])
	print("Experience: ", character["experience"], " XP")
	print("Weapon: ", character["equipment"]["weapon"])
	print("\n✅ Adventure completed successfully!")

Type Hints and Static Typing - Writing Safer Game Code

One of GDScript's most powerful features is the ability to choose between dynamic (flexible) and static (strict) typing. Understanding when to use each approach will make your games more reliable and performant.

Think of it like this

  • Dynamic typing = "Any box can hold anything" (flexible but potentially confusing)
  • Static typing = "This box ONLY holds numbers" (strict but prevents mistakes)

Dynamic Typing - Flexibility with Risks

Dynamic typing lets variables change their type during runtime. It's flexible but can lead to unexpected bugs.

@tool
extends EditorScript
 
func _run() -> void:
	# Dynamic variable can be anything!
	var game_value = "Player Name"
	print("Text: ", game_value)  # Output: Player Name
 
	game_value = 42
	print("Number: ", game_value)  # Output: 42
 
	game_value = true
	print("Boolean: ", game_value)  # Output: True
 
	# This flexibility can cause bugs!
	var player_health = "100"  # Oops! Should be a number
	var damage = 25
 
	# This won't work as expected - it concatenates strings!
	var result = player_health + damage  # Result: "10025" not 125
	print("Unexpected result: ", result)
 
	# This is what we wanted:
	var correct_health = 100  # Number, not string
	var correct_result = correct_health - damage
	print("Correct result: ", correct_result)

Common Dynamic Typing Mistakes

  • Mixing strings and numbers accidentally
  • Forgetting what type a variable should be
  • Runtime errors that could be prevented at compile time

Static Typing - Safety and Performance

Static typing specifies exactly what type of data a variable can hold. This prevents bugs before they happen and makes your game run faster.

@tool
extends EditorScript
 
func _run() -> void:
	# Type-hinted variables - each variable has a specific type
	var player_name: String = "Hero of Light"
	var player_health: int = 100
	var movement_speed: float = 5.75
	var is_invincible: bool = false
	var inventory: Array[String] = ["Sword", "Potion"]
	var stats: Dictionary = {"strength": 15, "defense": 12}
 
	print("=== CHARACTER DATA (STATIC TYPING) ===")
	print("Name: ", player_name)
	print("Health: ", player_health, " HP")
	print("Speed: ", movement_speed, " units/sec")
	print("Invincible: ", is_invincible)
	print("Inventory: ", inventory)
	print("Stats: ", stats)
 
	# The compiler prevents type errors:
	# player_health = "wounded"  # ❌ ERROR: Cannot assign String to int
	# movement_speed = true      # ❌ ERROR: Cannot assign bool to float
 
	# But you can still update values correctly:
	player_health = 85           # ✅ OK: int to int
	movement_speed = 6.2         # ✅ OK: float to float
	is_invincible = true         # ✅ OK: bool to bool
	inventory.append("Shield")   # ✅ OK: adding String to Array[String]
 
	print("\n=== AFTER UPDATES ===")
	print("Health: ", player_health, " HP")
	print("Speed: ", movement_speed, " units/sec")
	print("Invincible: ", is_invincible)
	print("Inventory: ", inventory)

Benefits of Static Typing

  • Catches errors early - Problems found before your game runs
  • Better performance - Godot can optimize the code better
  • Clearer code - Other developers (and you!) know exactly what each variable should contain
  • Better IDE support - Code completion and hints work better

Professional Game Development with Static Typing

Here's how professional game developers use static typing to build reliable games.

extends CharacterBody2D
 
# Basic stats
var max_health: int = 100
var current_health: int = max_health
var movement_speed: float = 200.0
var inventory: Array[String] = []
var is_alive: bool = true
 
# Apply damage, return true if character dies
func take_damage(damage: int) -> bool:
	current_health = max(0, current_health - damage)
	is_alive = current_health > 0
	return not is_alive
 
# Add item if space, return true if added
func add_item(item: String) -> bool:
	if inventory.size() < 20:
		inventory.append(item)
		return true
	return false
 
# Return health percentage
func get_health_percentage() -> float:
	return float(current_health) / max_health * 100.0
 
# Heal up to max health
func heal(amount: int) -> void:
	current_health = min(max_health, current_health + amount)

Challenge 6: Type-Safe Combat System

Create a combat system using static typing to prevent common bugs and ensure reliable gameplay.

Your Task: Build a combat system with static typing that:

  • Creates a player with 120 max health, 8 armor, 25 attack damage
  • Creates an enemy with 80 health and 15 attack damage
  • Simulates 3 rounds of combat (player attacks, then enemy attacks)
  • Calculates damage reduction based on armor (damage - armor, minimum 1)
  • Shows health status after each round

Expected Output:

=== COMBAT BEGINS ===
Player: 120/120 HP, 8 armor, 25 attack
Enemy: 80/80 HP, 15 attack

--- ROUND 1 ---
Player deals 25 damage to enemy!
Enemy health: 55/80
Enemy attacks for 7 damage (15 base - 8 armor)!
Player health: 113/120

--- ROUND 2 ---
Player deals 25 damage to enemy!
Enemy health: 30/80
Enemy attacks for 7 damage (15 base - 8 armor)!
Player health: 106/120

--- ROUND 3 ---
Player deals 25 damage to enemy!
Enemy health: 5/80
Enemy attacks for 7 damage (15 base - 8 armor)!
Player health: 99/120

--- ROUND 4 ---
Player deals 25 damage to enemy!
Enemy health: 0/80
🎉 Enemy defeated! Player wins!

Note: I advise you to try every challenge first before looking at the solution. This will help you train yourself to solve problems and experiment on your own. If you really can’t solve the challenge, it’s okay to check the solution but make sure you understand how and why it works.

Solution:

@tool
extends EditorScript
 
func _run() -> void:
	# Type-safe combat system
	var player_health: int = 120
	var player_max_health: int = 120
	var player_armor: int = 8
	var player_attack: int = 25
 
	var enemy_health: int = 80
	var enemy_max_health: int = 80
	var enemy_attack: int = 15
 
	print("=== COMBAT BEGINS ===")
	print("Player: %d/%d HP, %d armor, %d attack" % [player_health, player_max_health, player_armor, player_attack])
	print("Enemy: %d/%d HP, %d attack" % [enemy_health, enemy_max_health, enemy_attack])
	print()
 
	# Combat simulation - 3 rounds max
	for round in range(1, 4):
		print("--- ROUND %d ---" % round)
 
		# Player attacks enemy
		var player_damage: int = player_attack
		enemy_health -= player_damage
		enemy_health = max(0, enemy_health)  # Don't go below 0
		print("Player deals %d damage to enemy!" % player_damage)
		print("Enemy health: %d/%d" % [enemy_health, enemy_max_health])
 
		# Check if enemy died
		if enemy_health <= 0:
			print("🎉 Enemy defeated! Player wins!")
			break
 
		# Enemy attacks player (with armor reduction)
		var enemy_damage_dealt: int = max(1, enemy_attack - player_armor)  # Minimum 1 damage
		player_health -= enemy_damage_dealt
		player_health = max(0, player_health)  # Don't go below 0
		print("Enemy attacks for %d damage (%d base - %d armor)!" % [enemy_damage_dealt, enemy_attack, player_armor])
		print("Player health: %d/%d" % [player_health, player_max_health])
 
		# Check if player died
		if player_health <= 0:
			print("💀 Player defeated! Enemy wins!")
			break
 
		print()

Variable Scope and Code Blocks - Understanding Variable Visibility

Scope determines where in your code you can access variables. Think of scope like rooms in a house - some rooms are private, some are shared, and some are accessible from anywhere.

Scope Hierarchy:

  • Global Scope - Variables accessible from anywhere (like the main lobby)
  • Function Scope - Variables only accessible within a specific function (like a private room)
  • Block Scope - Variables only accessible within if/while/for blocks (like a closet in a room)

Global vs Local Scope

Global variables are shared across your entire game, while local variables are private to specific functions.

@tool
extends EditorScript
 
# GLOBAL VARIABLES - Accessible from anywhere in this script
var global_score: int = 0        # Game score - needs to persist
var player_level: int = 1        # Player level - used across functions
var game_difficulty: String = "Normal"  # Affects multiple systems
 
func _run() -> void:
	# LOCAL VARIABLES - Only accessible within this function
	var welcome_message: String = "Adventure begins!"  # Only needed here
	var temp_calculation: int = player_level * 10      # Temporary value
 
	print("=== GAME INITIALIZATION ===")
	print(welcome_message)
	print("Starting level: ", player_level)
	print("Difficulty: ", game_difficulty)
 
	# Call other functions - they can access global but not local variables
	increase_score(100)
	level_up()
	check_difficulty()
 
	# welcome_message is still accessible here (same function)
	print("Setup complete: ", welcome_message)
 
func increase_score(points: int) -> void:
	# This function can access global variables
	global_score += points
	var score_message: String = "Score increased!"  # Local to this function
 
	print(score_message, " +", points, " = ", global_score)
 
	# Cannot access welcome_message from _run() - it's local to that function
	# print(welcome_message)  # ❌ ERROR: welcome_message not accessible here
 
func level_up() -> void:
	# Access and modify global variables
	player_level += 1
	var level_bonus: int = player_level * 50  # Local variable
	global_score += level_bonus
 
	print("🎉 LEVEL UP! Now level ", player_level)
	print("Bonus points: ", level_bonus)
 
	# level_bonus disappears when this function ends
 
func check_difficulty() -> void:
	# Access global variable to determine game behavior
	var enemy_multiplier: float = 1.0  # Local variable
 
	if game_difficulty == "Easy":
		enemy_multiplier = 0.75
	elif game_difficulty == "Hard":
		enemy_multiplier = 1.5
	elif game_difficulty == "Nightmare":
		enemy_multiplier = 2.0
 
	print("Enemy strength multiplier: ", enemy_multiplier)
	# enemy_multiplier is destroyed when function ends

When to Use Each

Use GLOBAL variables for:

  • Player stats (health, score, level)
  • Game settings (difficulty, volume)
  • Persistent data (inventory, unlocked content)
  • System states (paused, current scene)

Use LOCAL variables for:

  • Temporary calculations
  • Function-specific data
  • Values that don't need to persist
  • Loop counters and temporary storage

Code Block Scoping - Variables in if/for/while blocks

Variables created inside code blocks (if statements, loops, etc.) are only accessible within that block.

@tool
extends EditorScript
 
func _run() -> void:
	var function_level_var: String = "I'm accessible throughout this function"
	var player_health: int = 100
 
	print("=== BLOCK SCOPING DEMONSTRATION ===")
	print("Function start: ", function_level_var)
 
	# IF BLOCK SCOPING
	if player_health > 50:
		var health_status: String = "Healthy!"  # Only exists in this if block
		var bonus_points: int = 25              # Only exists in this if block
 
		print("Inside if block: ", health_status)
		print("Function variable accessible: ", function_level_var)  # ✅ Can access
		print("Bonus points: ", bonus_points)
	# health_status and bonus_points are destroyed when if block ends
 
	# This would cause an error:
	# print(health_status)  # ❌ ERROR: health_status doesn't exist here
 
	# LOOP SCOPING
	print("\n--- Loop Scoping ---")
	for round in range(3):
		var round_message: String = "Round %d in progress" % round
		var damage_dealt: int = round * 10
 
		print(round_message, " - Damage: ", damage_dealt)
		# round_message and damage_dealt only exist within this loop iteration
 
	# These would cause errors:
	# print(round_message)  # ❌ ERROR: round_message doesn't exist here
	# print(damage_dealt)   # ❌ ERROR: damage_dealt doesn't exist here
	# print(round)          # ❌ ERROR: round doesn't exist here
 
	# WHILE LOOP SCOPING
	var countdown: int = 3
	while countdown > 0:
		var countdown_msg: String = "Countdown: %d" % countdown
		print(countdown_msg)
		countdown -= 1
		# countdown_msg is recreated each loop iteration
 
	print("Function end: ", function_level_var)  # ✅ Still accessible

String Formatting and Interpolation

When making games, you often need to show text with variables inside strings — like player names, scores, or health values. Godot gives us a few ways to do this.

1. Concatenation (Basic Way)

You can join strings with the + operator, but you must convert numbers using str().

@tool
extends EditorScript
	var player: String = "Hero"
	var score: int = 120
 
	print(player + " scored " + str(score) + " points")
	# Output: Hero scored 120 points

Works, but can get messy when you have many variables.

2. % Formatting (Cleaner)

Similar to C/Python style. Use placeholders like %s (string), %d (integer), %f (float).

@tool
extends EditorScript
	var name: String = "Hero"
	var hp: int = 80
	var max_hp: int = 100
 
	print("%s has %d/%d HP" % [name, hp, max_hp])
	# Output: Hero has 80/100 HP

Easier to read than concatenation.

3. format() with Named Values (Flexible)

This lets you use names inside braces {}, then pass a dictionary.

@tool
extends EditorScript
	var data = {
		"name": "Hero",
		"hp": 80,
		"max": 100,
		"gold": 250
	}
 
	print("{name} has {hp}/{max} HP and {gold} gold".format(data))
	# Output: Hero has 80/100 HP and 250 gold

Best when you have many variables.

Best Practices and Tips

1. Naming Conventions

# Use snake_case for variables and functions
var player_health: int = 100
var movement_speed: float = 5.0
 
# Use UPPER_CASE for constants
const MAX_PLAYERS: int = 4
const GRAVITY_FORCE: float = 9.8
 
# Use PascalCase for classes and enums
class_name PlayerController
enum WeaponType { SWORD, BOW, STAFF }

2. Type Safety

# Always use type hints for better performance and error catching
var position: Vector2 = Vector2.ZERO
var inventory: Array[String] = []
var player_stats: Dictionary = {}
 
func calculate_damage(base_damage: int, multiplier: float) -> int:
	return int(base_damage * multiplier)

3. Initialize Variables Properly

extends CharacterBody2D
 
# Initialize with meaningful defaults
var health: int = 100
var max_health: int = 100
var speed: float = 200.0
var inventory: Array[String] = []
var is_alive: bool = true
 
# Avoid uninitialized variables that could cause errors
# var uninitialized_var  # Don't do this

Conclusion

Congratulations! You've successfully mastered the fundamentals of GDScript programming and built a solid foundation for game development in Godot. You now have:

  • ✅ A complete understanding of GDScript variables and data types
  • ✅ Practical experience with arrays, dictionaries, and complex data structures
  • ✅ Knowledge of static vs dynamic typing and when to use each
  • ✅ Mastery of variable scope and code organization
  • ✅ String formatting skills for dynamic game UI and messages
  • ✅ Professional coding practices and naming conventions
  • ✅ Hands-on experience from multiple coding challenges

Resources for Further Learning

Happy game developing!