Chapter 1.Introduction
1.1. Introduction to Video Games and Game Programming
Video games have become one of the most influential forms of digital media, shaping entertainment, culture, technology, and even education. What began decades ago as simple experiments on early computers has grown into a global industry that blends art, science, mathematics, storytelling, and interactive design. Today, billions of people play games across a vast spectrum of genres and platforms—from arcade cabinets and home consoles to PCs, mobile devices, and virtual reality systems.
This textbook, Practical Game Programming, introduces the foundational concepts, techniques, and technologies behind modern video games. It is designed as an open educational resource (OER) to support learners, educators, and independent developers who wish to understand not only how games work but how they are created.
1.1.1. Why Learn Game Programming?
Game programming is a unique intersection of creativity and computation. A single game integrates:
- Graphics and animation to render characters, scenes, and visual effects
- Input handling for keyboards, mice, joysticks, touchscreens, and controllers
- Sound and music to enhance atmosphere and player feedback
- Physics and simulation to model movement, collisions, and interactions
- Artificial intelligence that drives nonplayer characters (NPCs)
- User interface design to support interaction, navigation, and control
- Software engineering principles for maintainable, scalable game code
Learning how to build games provides hands-on experience with many core areas of computer science. It also fosters problem-solving, creativity, algorithmic thinking, and iterative design.
1.1.2. Our Focus: A Practical, Hands-On Approach
To ensure you can apply what you learn immediately, this textbook focuses on practical game programming using C/C++ and the Allegro 5 library. Allegro 5 is an open-source, cross-platform game programming library that supports:
- • 2D graphics
- • Event handling
- • Keyboard, mouse, and joystick input
- • Sound and audio streaming
- • Timers and animation
- • File operations
- • Add-ons for images, fonts, primitives, and more
You will also learn to set up your development environment using:
- • Visual Studio Code
- • GCC (MinGW or system compiler)
- • CMake
- • Ninja build system
This toolchain works consistently across Windows, Linux, and macOS, making it ideal for students and open-source developers.
1.1.3. What You Will Learn in This Textbook
Throughout the upcoming chapters, you will explore:
- • The history and evolution of video games
- • Major genres and game design principles
- • The structure of game programs
- • Handling input devices
- • Displaying graphics and text
- • Using timers and game loops
- • Working with sound and music
- • Implementing physics and collision detection
- • Building user interfaces
- • Applying AI techniques
- • Developing complete games step-by-step
Examples and exercises in each chapter help reinforce these concepts and gradually build toward more complex projects.
1.1.4. Before We Begin: Understanding Where Games Come From
To build games effectively, it helps to understand the origins of the medium—the technologies, ideas, innovations, and pioneers that shaped the games we play today. The evolution of video games—from early mainframe experiments to modern 3D, online, and mobile experiences—is not just a historical timeline; it is a road map of technological advancement that directly influences how we design and program games today.
With this context in mind, let us explore how video games began and how they have transformed over the decades.
1.2. History of Video Games
The history of video games is fascinating, and its long journey has spanned several decades.
1.2.1. Early Beginnings Between the 1950s and 1960s
Computer scientists and engineers started designing simple games and simulations on minicomputers and mainframes. Some important games developed during this period of time include:
- OXO(1952): Created by British professor A. S. Douglas at the University of Cambridge, this was a tic-tac-toe game developed as part of his doctoral dissertation.
- Tennis for Two(1958): Developed by William Higinbotham at the Brookhaven National Laboratory, this game simulated a tennis match on an oscilloscope screen.
- Spacewar!(1962): Created by Steve Russell and his colleagues at the Massachusetts Institute of Technology (MIT), this was one of the first interactive video games, featuring space combat between two ships.
- The Brown Box(1967): Developed by Ralph Baer and his team at Sanders Associates, this was the prototype for the first multiplayer, multiprogram video game system. It was later licensed to Magnavox and released as the Magnavox Odyssey in 1972.
1.2.2. Birth of Consumer Video Game Hardware in the 1970s
The 1970s were a transformative decade for video games, marking the transition from experimental game projects to mainstream entertainment. Some key developments during the time include the following.
Early Arcade Games
- Computer Space(1971): Created by Nolan Bushnell and Ted Dabney, this was the first commercially sold arcade video game.
- Pong(1972): Developed by Atari, Pong became the first commercially successful arcade game, popularizing video games in arcades.
Home Consoles
- Magnavox Odyssey (1972): The first home video game console, developed by Ralph Baer and his team, featured simple games like table tennis and shooting games.
- Atari 2600 (1977): This console introduced interchangeable game cartridges, allowing players to switch games easily. It became one of the most popular consoles of the era.
Iconic Games
- Space Invaders(1978): Developed by Tomohiro Nishikado, this game became a cultural phenomenon and significantly boosted the arcade industry.
- Asteroids(1979): Created by Atari, this game featured vector graphics and became one of the best-selling arcade games of all time.
Technological Advancements
- Microprocessors: The introduction of microprocessors in the late 1970s allowed for more complex games and better graphics.
- ROM Cartridges: These enabled consoles like the Atari 2600 to offer a variety of games without needing built-in hardware for each one.
1.2.3. Boom and Bust Cycles Between the 1970s and 1980s
The period between the 1970s and 1980s was a pivotal time for the video game industry, marked by the following significant advancements and the emergence of iconic games and consoles:
- Arcade Boom: The late 1970s saw the rise of arcade games, with titles like Space Invaders (1978) by Tomohiro Nishikado becoming a massive hit and sparking the golden age of arcade video games.
- Home Consoles: The Atari 2600 was released in 1977, revolutionizing home gaming with its use of interchangeable cartridges.
- Pac-Man(1980): Created by Namco, Pac-Man became a cultural phenomenon and one of the most famous arcade games of all time.
- Donkey Kong(1981): Developed by Nintendo, this game introduced the world to Mario and became a major success.
- Video Game Crash of 1983: An oversaturation of low-quality games led to a significant downturn in the video game market, particularly in North America.
- Nintendo Entertainment System (NES): Released in 1985, the NES revitalized the home console market and introduced iconic games like Super Mario Bros. and The Legend of Zelda.
- Graphics and Sound: The transition from simple, blocky graphics to more detailed and colourful visuals, along with improved sound capabilities, enhanced the gaming experience.
- Home Computers: The rise of home computers like the Commodore 64 and ZX Spectrum provided new platforms for game development and distribution.
1.2.4. The Video Game Crash and Rebound in 1983
The Video Game Crash of 1983 was a significant event that nearly ended the burgeoning video game industry.
Causes of the Crash
- Market Saturation: By the early 1980s, the market was flooded with numerous consoles and a plethora of low-quality games. This oversaturation confused consumers and led to a decline in interest.
- Poor-Quality Games: Many games released during this period were rushed and poorly made. The infamous E.T. the Extra-Terrestrial game for the Atari 2600 is often cited as a prime example.
- Competition from Personal Computers: The rise of affordable personal computers provided an alternative platform for gaming, drawing consumers away from consoles.
Impact of the Crash
- Financial Losses: The industry saw a dramatic drop in revenue, from around $3.2 billion in 1982 to just $100 million by 1985.
- Bankruptcies: Many companies producing video game consoles and games went bankrupt, and retailers were left with unsold inventory.
- Loss of Consumer Confidence: The crash led to a significant loss of confidence in video games as a viable form of entertainment.
Rebound and Recovery
- Nintendo Entertainment System (NES): The release of the NES in 1985 played a crucial role in revitalizing the industry. Nintendo’s strict quality control and innovative marketing strategies helped restore consumer confidence.
- New Business Models: The industry adopted new business models, including licensing agreements and third-party game development, which helped ensure higher-quality games.
- Technological Advancements: Improved graphics, sound, and gameplay mechanics attracted a new generation of gamers.
The crash and subsequent recovery reshaped the video game industry, leading to the establishment of practices and standards that continue to influence game development today.
1.2.5. Late 1980s and Early 1990s
The period between the late 1980s and early 1990s was a dynamic time for the video game industry, marked by significant technological advancements and the release of many iconic games and consoles.
Late 1980s
- Nintendo Entertainment System (NES): The NES continued to dominate the home console market, with games like Super Mario Bros. 3 (1988) and The Legend of Zelda (1986) becoming massive hits.
- Sega Genesis (1988): Known as the Mega Drive outside North America, the Sega Genesis introduced 16-bit graphics and became a strong competitor to the NES.
- Handheld Gaming: The release of the Game Boy in 1989 by Nintendo revolutionized portable gaming. It came bundled with Tetris, which became a global phenomenon.
Early 1990s
- Super Nintendo Entertainment System (SNES): Released in 1990 in Japan and 1991 in North America, the SNES brought advanced graphics and sound capabilities, with iconic games like Super Mario World and The Legend of Zelda: A Link to the Past.
- Sega Genesis vs. SNES: The early 1990s saw the height of the console wars between Sega and Nintendo, with both companies releasing numerous hit games and marketing campaigns.
- PC Gaming: The early 1990s also saw significant growth in PC gaming, with titles like Doom (1993) and Myst (1993) pushing the boundaries of graphics and gameplay.
Technological Advancements
- 16-bit Graphics: The transition from 8-bit to 16-bit graphics allowed for more detailed and colourful visuals.
- Sound and Music: Improved sound chips enabled more complex and immersive audio experiences in games.
- CD-ROM Technology: The introduction of CD-ROMs provided greater storage capacity, allowing for more extensive and detailed games, and CD-ROMs were incorporated into consoles, impacting Sega and Nintendo.
1.2.6. Late 1990s and Beyond
The late 1990s and beyond saw tremendous growth and innovation in the video game industry.
Late 1990s
- 3D Graphics: The transition from 2D to 3D graphics was a major leap. Games like Super Mario 64 (1996) and The Legend of Zelda: Ocarina of Time (1998) showcased the potential of 3D environments.
- PlayStation (1994): Sony’s PlayStation revolutionized gaming with its CD-ROM format, allowing for larger and more complex games. Titles like Final Fantasy VII (1997) and Metal Gear Solid (1998) became iconic.
- PC Gaming: The late 1990s saw the rise of influential PC games like Half-Life (1998) and StarCraft (1998), which pushed the boundaries of storytelling and multiplayer gaming.
Early 2000s
- Online Gaming: The advent of broadband internet enabled online multiplayer games. World of Warcraft (2004) and Halo 2 (2004) were pivotal in popularizing online gaming.
- New Consoles: The release of the PlayStation 2 (2000), Xbox (2001), and Nintendo GameCube (2001) brought enhanced graphics and new gameplay experiences.
- Mobile Gaming: The early 2000s also saw the rise of mobile gaming with devices like the Game Boy Advance (2001) and the Nintendo DS (2004).
Mid to Late 2000s
- High-Definition Gaming: The Xbox 360 (2005) and PlayStation 3 (2006) introduced high-definition graphics, significantly improving visual fidelity.
- Motion Controls: The Nintendo Wii (2006) popularized motion controls, making gaming more accessible to a broader audience.
- Indie Games: Platforms like Steam and Xbox Live Arcade provided a space for indie developers to thrive, leading to the success of games like Braid (2008) and Minecraft (2009).
2010s and Beyond
- Virtual Reality (VR): The introduction of VR headsets like the Oculus Rift (2016) and PlayStation VR (2016) opened new possibilities for immersive gaming experiences.
- Streaming and Cloud Gaming: Services like Twitch allowed gamers to stream their play sessions online, while Google Stadia let users enjoy high-end games without needing powerful hardware.
- Next-Gen Consoles: The PlayStation 5 (2020) and Xbox Series X (2020) brought even more advanced graphics, faster load times, and new features like ray tracing.
1.2.7. Future of the Video Game Industry
The video game industry is massive and continues to grow rapidly. As of 2024, the global video game market generated approximately US$182.7 billion in revenue, reflecting a year-over-year increase of about 3.2% compared to 2023. Industry analysts forecast steady growth, with global market revenues expected to exceed US$200 billion by 2027, corresponding to a compound annual growth rate (CAGR) of roughly 4–5% in the near term. In terms of audience size, the global gaming population reached approximately 3.32 billion players in 2024 and was projected to grow to around 3.5–3.6 billion gamers by 2025, underscoring the continued expansion of video games as a dominant form of digital entertainment.
The future of the video game industry looks incredibly promising, driven by several key trends and technological advancements:
- Virtual Reality (VR) and Augmented Reality (AR): These technologies are expected to become more mainstream, offering immersive gaming experiences. The VR and AR market is projected to reach $370 billion by 2034.
- Cloud Gaming: Services like Google Stadia and NVIDIA GeForce Now are making high-quality gaming accessible without the need for powerful hardware. This trend is likely to continue, with streaming becoming a major part of the gaming landscape.
- Artificial Intelligence (AI): AI will play a significant role in creating more realistic and responsive game environments. This includes advanced NPC behaviors and personalized gaming experiences.
- Metaverse: The concept of the metaverse, a shared virtual space where users can interact in real time, is gaining traction. Companies are investing heavily in creating these expansive virtual worlds.
- Mobile Gaming: Mobile gaming remains the largest segment of the video game industry, generating approximately US$92–93 billion in revenue in 2024, accounting for nearly half of total global game revenues. Industry forecasts indicated continued growth, with mobile game revenues projected to exceed US$100 billion in 2025, driven by widespread smartphone adoption, free-to-play business models, and global accessibility. The convenience and low barrier to entry of mobile platforms position mobile gaming as a central driver of the industry’s long-term growth.
- E-Sports: Competitive gaming is growing rapidly, with large audiences and significant investment. E-sports tournaments are becoming mainstream entertainment events.
The video game industry is set to continue its expansion, driven by innovation and the increasing integration of gaming into everyday life.
1.3. Types of Video Games
Since we will be learning how to create video games in this course, it is necessary to know what types of games we will learn to program.
1.3.1. Action Games
Action games are a genre that emphasizes physical challenges, such as hand-eye coordination and reaction time. These games often involve combat, exploration, and overcoming obstacles in dynamic and interactive environments.
Key Features of Action Games
- Fast-Paced Gameplay: Action games often involve quick reflexes and fast decision-making. Players must react swiftly to in-game events to succeed.
- Combat and Fighting: Many action games focus on combat, whether it’s hand-to-hand fighting, shooting, or using various weapons. Examples include Street Fighter and Call of Duty.
- Exploration and Adventure: Action games often feature expansive worlds to explore, filled with enemies, obstacles, and hidden secrets. Games like The Legend of Zelda series blend action with adventure elements.
- Platforming: Platformers are a subgenre where players navigate through levels by jumping between platforms and avoiding obstacles. Classic examples include Super Mario Bros. and Sonic the Hedgehog.
- Puzzle-Solving: Some action games incorporate puzzles that require players to think strategically and solve problems to progress. The Tomb Raider and Uncharted series are known for this blend.
Popular Types of Action Games
- First-Person Shooters (FPS): Players experience the game through the eyes of the protagonist, focusing on shooting and combat. Examples—Call of Duty, Halo.
- Third-Person Shooters: Players control a character from a third-person perspective, often with a focus on shooting and cover mechanics. Examples—Gears of War, The Division.
- Beat ’Em Ups: Players fight through waves of enemies using melee combat. Examples—Streets of Rage, Double Dragon.
- Hack and Slash: Focus on melee combat with swords or other weapons, often featuring combo systems. Examples—Devil May Cry, God of War.
- Stealth Action: Emphasize sneaking and avoiding detection rather than direct combat. Examples—Metal Gear Solid, Hitman.
Popular Action Games
- Elden Ring: Known for its challenging combat and expansive open world, blending action with RPG (role-playing game) elements.
- The Legend of Zelda: Breath of the Wild: Combines action, exploration, and puzzle-solving in a vast open world.
- Grand Theft Auto V: Offers a mix of action, driving, and open-world exploration with a compelling storyline.
- Doom Eternal: A fast-paced FPS with intense combat and a focus on movement and strategy.
1.3.2. Adventure Games
Adventure games are a genre where players take on the role of a protagonist in an interactive story, driven by exploration and puzzle-solving. These games often emphasize narrative and character development, allowing players to immerse themselves in a rich, engaging storyline.
Key Features of Adventure Games
- Story-Driven Gameplay: Adventure games often feature deep, engaging narratives that drive the gameplay. Players progress through the story by solving puzzles and interacting with the game world.
- Exploration: Players explore diverse environments, from fantasy realms to real-world locations. The thrill of discovery is a significant part of the experience.
- Puzzle-Solving: Puzzles are a core element, requiring players to think critically and use logic to progress. These can range from simple tasks to complex, multistep challenges.
- Character Interaction: Players interact with various characters, each with their own stories and personalities. Dialogue choices can influence the story and outcomes.
- Inventory Management: Many adventure games involve collecting and using items to solve puzzles and advance the plot.
Popular Types of Adventure Games
- Point-and-Click Adventures: Players use a mouse to interact with the environment and solve puzzles. Examples—Monkey Island series, Grim Fandango.
- Action-Adventure: Combines elements of action games with adventure gameplay. Examples—The Legend of Zelda series, Tomb Raider series.
- Text Adventures: Players input text commands to interact with the game world. Examples—Zork, Hitchhiker’s Guide to the Galaxy.
- Visual Novels: Focus on narrative and character development, often with branching storylines based on player choices. Examples—Phoenix Wright—Ace Attorney, Danganronpa.
- Interactive Fiction: Similar to text adventures but often more focused on storytelling and player choices. Examples—80 Days, Lifeline.
Popular Adventure Games
- The Legend of Zelda: Breath of the Wild: An open-world action-adventure game known for its vast exploration, puzzle-solving, and engaging story.
- The Witcher 3: Wild Hunt: Combines action, exploration, and narrative-driven gameplay in a richly detailed fantasy world.
- Life Is Strange: An episodic adventure game that focuses on narrative and player choices, with a unique time-rewinding mechanic.
- UnchartedSeries: Action-adventure games that blend cinematic storytelling with exploration and puzzle-solving.
- Grim Fandango: A classic point-and-click adventure game with a unique art style and engaging story.
1.3.3. Arcade Games
Arcade games are coin-operated entertainment machines typically found in public places like restaurants, bars, and amusement arcades. These games are designed to be easy to play but challenging to master, often focusing on skill-based gameplay.
Key Features of Arcade Games
- Fast-Paced Gameplay: Arcade games are designed to be quick and engaging, often requiring fast reflexes and quick decision-making.
- Simple Controls: The controls are usually straightforward, making the games easy to pick up and play but challenging to master.
- Increasing Difficulty: As players progress, the difficulty level increases, providing a continuous challenge.
- High Scores: Many arcade games feature a high-score system, encouraging players to compete for the top spot.
- Short Play Sessions: Arcade games are typically designed for short play sessions, making them ideal for quick entertainment.
Popular Types of Arcade Games
- Classic Arcade Games: These include iconic titles from the golden age of arcade gaming, such as Pac-Man, Space Invaders, and Asteroids.
- Platformers: Players navigate characters through levels filled with obstacles and enemies. Examples—Super Mario Bros., Donkey Kong.
- Shoot ’Em Ups: Players control a character or vehicle and shoot at waves of enemies. Examples—Galaga, Gradius.
- Beat ’Em Ups: Players fight through levels filled with enemies using hand-to-hand combat. Examples—Double Dragon, Streets of Rage.
- Puzzle Games: These games challenge players with puzzles that require logic and strategy to solve. Examples—Tetris, Puzzle Bobble.
Popular Arcade Games
- Pac-Man: A classic maze game where players control Pac-Man, eating pellets and avoiding ghosts.
- Space Invaders: A pioneering shoot ’em up game where players defend against waves of descending aliens.
- Street Fighter II: A revolutionary fighting game that popularized the one-on-one fighting genre.
- Galaga: A shoot ’em up game where players control a spaceship and shoot at enemy formations.
- Donkey Kong: A platformer where players control Mario, climbing ladders and avoiding obstacles to rescue a damsel in distress.
- Geometry Dash: A rhythm-based platformer with challenging levels and fast-paced gameplay.
- Crossy Road: A modern take on the classic Frogger, where players navigate characters across busy roads and rivers.
- Fruit Ninja: A game where players swipe to slice fruits while avoiding bombs.
1.3.4. Board Games
Board games are traditionally defined as tabletop games in which players move pieces or tokens on a premarked surface, or board, according to a formal set of rules. These games vary widely in complexity, theme, and mechanics, ranging from simple abstract contests to elaborate strategy-driven systems. Board games are especially valued for fostering social interaction, communication, and shared experiences among players.
Historically, board games represent one of the oldest forms of structured play. Some of the earliest known examples date back thousands of years, such as Senet from ancient Egypt and Go from China. Despite their physical origins, board games are best understood as systems of rules and mechanics, rather than as artifacts tied exclusively to physical components.
Importantly, the core mechanics of board games—turn-based play, discrete state transitions, resource management, probability, and strategic decision-making—lend themselves naturally to digital implementation. As a result, many board games have been successfully adapted into video games, and some modern board games are designed from the outset to integrate digital components. In these cases, video technology may replace tasks traditionally handled by human players, such as rule enforcement, state tracking, randomness generation, or narrative control. This demonstrates that board games are not fundamentally incompatible with video games; rather, they form a genre whose mechanics can be realized in either physical or digital form.
Examples of this convergence include fully digital adaptations of classic board games such as chess, Monopoly, Risk, Catan, and Ticket to Ride, as well as hybrid “video board games” like Mansions of Madness (Second Edition) and XCOM: The Board Game, which combine physical boards with companion apps that manage scenarios, timing, and game events. These examples illustrate that board game designs can function equivalently—or even more effectively—within a video game environment.
Key Features of Board Games
- Social Interaction: Board games are often played with friends or family, fostering social interaction and teamwork.
- Strategy and Skill: Many board games require strategic thinking, planning, and skill to win.
- Well-Defined Rules: Board games typically operate under explicit and deterministic rule systems, making them suitable for algorithmic implementation.
- Variety of Themes: Board games cover a wide range of themes, from fantasy and adventure to economics and history.
- Replayability: Good board games offer high replay value, with different outcomes and strategies each time they are played.
Popular Types of Board Games
- Classic Board Games: These are timeless games that have been enjoyed for generations. Examples—chess, checkers, backgammon, Monopoly, Scrabble.
- Strategy Games: These games require careful planning and strategy to outmaneuver opponents. Examples—Catan, Risk, Ticket to Ride.
- Cooperative Games: Players work together to achieve a common goal. Examples—Pandemic, Forbidden Island, Gloomhaven.
- Party Games: Designed for larger groups, these games are often light-hearted and focus on fun and interaction. Examples—Codenames, Cards Against Humanity, Pictionary.
- Deck-Building Games: Players build their own decks of cards throughout the game to gain advantages. Examples—Dominion, Ascension, Clank!
Popular Board Games
- Catan: A strategy game where players collect resources and build settlements to earn points.
- Pandemic: A cooperative game where players work together to stop global outbreaks of diseases.
- Ticket to Ride: A route-building strategy game in which players connect cities on a map to complete objectives.
- Gloomhaven: A cooperative, campaign-based game with deep storytelling and tactical combat.
- Monopoly: A classic game where players buy, trade, and develop properties to bankrupt their opponents.
- Wingspan: A strategy game about bird collecting, featuring beautiful artwork and engaging gameplay.
- Azul: A tile-placement game where players compete to create the most beautiful patterns.
- Terraforming Mars: A strategy game where players work to terraform the planet Mars by managing resources and projects.
1.3.5. Puzzle Games
Puzzle games are a genre that challenges players’ problem-solving skills, logic, and mental acuity. They come in various forms, each offering unique gameplay experiences.
Key Features of Puzzle Games
- Problem-Solving: Puzzle games require players to solve problems, often through logic, pattern recognition, or strategic thinking.
- Variety of Challenges: These games can include a wide range of challenges, such as jigsaw puzzles, word puzzles, number puzzles, and logic puzzles.
- Increasing Difficulty: Many puzzle games feature levels that increase in difficulty, providing a continuous challenge as players progress.
- Casual and Relaxing: Puzzle games are often designed to be casual and relaxing, making them accessible to players of all ages and skill levels.
Popular Types of Puzzle Games
- Jigsaw Puzzles: Players assemble pieces to form a complete picture. Examples—Jigsaw Planet.
- Word Puzzles: Games that involve forming words from letters or solving crossword puzzles. Examples—Words of Wonders, Word Wipe.
- Number Puzzles: Games that involve numbers. Examples—Sudoku, 2048.
- Logic Puzzles: Games that require logical thinking to solve. Examples—Minesweeper, Flow Free.
- Match-Three Games: Players match three or more items of the same type to clear them from the board. Examples—Candy Crush Saga, Bejeweled.
Popular Puzzle Games
- Tetris: A classic puzzle game where players arrange falling blocks to complete lines.
- Portal: A first-person puzzle game that involves creating portals to solve spatial puzzles.
- The Witness: An open-world puzzle game with a variety of challenging puzzles to solve.
- Monument Valley: A visually stunning puzzle game that involves manipulating impossible architecture to guide a character through levels.
- Baba Is You: A unique puzzle game where players manipulate the rules of the game to solve puzzles.
1.3.6. Role-Playing Games
Role-playing games (RPGs) are a genre where players assume the roles of characters in a fictional setting. Players take control of these characters and guide them through various quests, battles, and storylines.
Key Features of RPGs
- Character Development: Players can customize their characters’ appearance, abilities, and skills. Characters gain experience points (XP) and level up, improving their stats and unlocking new abilities.
- Storylines and Quests: RPGs often feature rich, immersive storylines with multiple quests and side missions. Players make choices that can affect the outcome of the story and the world around them.
- Exploration: RPGs typically offer expansive worlds to explore, filled with towns, dungeons, and hidden secrets. Exploration is often rewarded with loot, new quests, and lore.
- Combat Systems: Combat can be turn-based, real time, or a hybrid of both. Players use a variety of weapons, spells, and tactics to defeat enemies.
- Inventory and Equipment: Managing inventory and equipping characters with the best gear is a crucial part of RPGs. Players can find, buy, or craft weapons, armor, and items.
Popular Types of RPGs
- Action RPGs: Focus on real-time combat and fast-paced gameplay. Examples of action RPGs include The Witcher 3: Wild Hunt, Dark Souls.
- Turn-Based RPGs: Combat is turn-based, allowing players to plan their moves strategically. Examples of turn-based RPGs include the Final Fantasy series, the Persona series.
- MMORPGs (Massively Multiplayer Online RPGs): Feature large, persistent worlds where thousands of players can interact. Examples of MMORPGs include World of Warcraft, Final Fantasy XIV.
- JRPGs (Japanese RPGs): Often feature stylized art, turn-based combat, and linear storylines. Examples of JRPGs (Japanese RPGs) include Dragon Quest series, Tales of series.
- Genre RPGs: Emphasize open-world exploration and player choice in a themed setting. Examples include Red Dead Redemption in a western setting, The Elder Scrolls series in the fantasy realm of Tamriel, and the Fallout series set in a post-nuclear-apocalypse America.
Popular RPG Games
- Elden Ring: Known for its challenging combat and expansive open world.
- The Witcher 3: Wild Hunt: Praised for its storytelling and detailed world.
- Final Fantasy VII Remake: A modern take on a classic JRPG.
1.3.7. Sports Games
Sports games are a genre that simulates the practice of sports. These games can replicate real-life sports or incorporate elements of sports into their gameplay. They often focus on physical and tactical challenges, testing the player’s precision, accuracy, and strategic thinking.
Key Features of Sports Games
- Realism: Many sports games strive to accurately model the athletic characteristics required by the sport, such as speed, strength, and agility.
- Variety: They cover a wide range of sports, including football, basketball, soccer, baseball, and more.
- Multiplayer Options: Players can compete against computer-controlled opponents or other players, either locally or online.
- Career Modes: Some games offer career modes, where players can manage a team or develop a single athlete’s career over multiple seasons.
Popular Types of Sports Games
Sports games come in many forms, each emphasizing different mechanics and styles of play. These are some of the most widely recognized types:
- Team Sports Simulations: These games replicate real-world team sports with a focus on authenticity, licensed teams, and realistic physics. Examples include soccer (e.g., FIFA, eFootball), basketball (e.g., NBA 2K), American football (e.g., Madden NFL), hockey (e.g., NHL series).
- Individual Sports Games: These focus on one-on-one or solo athletic performance. Examples include tennis (Top Spin, Tennis World Tour), golf (PGA Tour 2K, Everybody’s Golf), boxing/MMA (Fight Night, UFC).
- Racing and Motorsports: These involve cars, motorcycles, karts, or futuristic vehicles. Examples include simulation racing (Gran Turismo, Forza Motorsport), arcade racing (Mario Kart, Burnout), rally and off-road (Dirt, WRC).
- Extreme and Action Sports: Games that highlight high-energy, trick-based gameplay. Examples include skateboarding (Tony Hawk’s Pro Skater), snowboarding (SSX), BMX and freestyle sports (Mat Hoffman’s Pro BMX).
- Sports Management and Strategy Games: These emphasize tactics, recruitment, finances, and long-term planning rather than real-time play. Examples include Football Manager, Out of the Park Baseball, Motorsport Manager.
Popular Sports Games
- FIFASeries: Developed by EA Sports, this series is known for its realistic soccer simulation, featuring licensed teams, players, and leagues.
- NBA 2KSeries: A basketball simulation game that offers realistic gameplay, player animations, and a deep career mode.
- Madden NFLSeries: Another EA Sports title, this series focuses on American football, offering realistic gameplay and various modes, including Franchise and Ultimate Team.
- Tony Hawk’s Pro Skater: A classic skateboarding game known for its arcade-style gameplay and iconic soundtrack.
- Rocket League: A unique blend of soccer and vehicular acrobatics, where players control rocket-powered cars to hit a ball into the opponent’s goal.
1.3.8. Strategy Games
Strategy games are a genre of games that emphasizes planning, decision-making, and resource management to achieve victory. These games often require players to think critically and strategically, making choices that will impact the outcome of the game.
Key Features of Strategy Games
- Resource Management: Players must gather and manage resources such as money, materials, and manpower to build and sustain their forces or civilizations.
- Tactical and Strategic Planning: Players need to devise and execute plans to outmaneuver opponents, whether in battle or through economic and diplomatic means.
- Turn-Based vs. Real-Time: In turn-based strategy (TBS) games, players take turns to make their moves. In real-time strategy (RTS) games, gameplay occurs in real time, requiring quick decision-making.
- Single-Player and Multiplayer Modes: In single-player modes, campaigns and scenarios are played against AI opponents. Multiplayer modes involve competitive or cooperative play against other human players.
Popular Types of Strategy Games
- Real-Time Strategy (RTS): Players manage resources, build units, and control armies in real time. Examples include StarCraft and Age of Empires.
- Turn-Based Strategy (TBS): Players take turns making decisions and moves. Examples include Civilization and XCOM.
- 4X (eXplore, eXpand, eXploit, eXterminate) Strategy: These involve exploring, expanding, exploiting, and exterminating. Examples include Sid Meier’s Civilization and Stellaris.
- Grand Strategy: Focuses on managing entire nations or empires over long periods. Examples include Crusader Kings and Europa Universalis.
- Tower Defense Strategy: In such games, players build defensive structures to protect against waves of enemies. Examples include Plants vs. Zombies, Kingdom Rush.
Popular Strategy Games
These are some influential and widely played strategy titles across different subgenres:
Real-Time Strategy (RTS)
- StarCraft II: Known for its competitive multiplayer and asymmetric factions.
- Age of Empires IV: A modern evolution of classic empire-building gameplay.
- Warcraft III: A foundational RTS with strong hero-based mechanics.
Turn-Based Strategy (TBS)
- Civilization VI: Players build and expand civilizations across millennia.
- XCOM 2: A tactical combat strategy game with high-stakes decisions.
- Advance Wars: A turn-based military strategy series known for accessibility and depth.
4X (eXplore, eXpand, eXploit, eXterminate) Strategy
- Stellaris: A space-faring empire builder with dynamic narratives.
- Sid Meier’s Civilization Series: The gold standard for 4X historical strategy.
- Endless Legend: A fantasy-themed 4X with asymmetric factions.
Grand Strategy
- Crusader Kings III: Focuses on dynasties, politics, and medieval intrigue.
- Europa Universalis IV: Deep global strategy spanning centuries.
- Hearts of Iron IV: A WWII-focused grand strategy emphasizing logistics and warfare.
Tower Defense
- Plants vs. Zombies: Accessible and humorous tower defense gameplay.
- Kingdom Rush: Known for its polished mechanics and challenging levels.
- Bloons TDSeries: A long-running, highly popular tower defense franchise.
1.3.9. Utilities Games
Utilities games are a unique category of software available on platforms like Steam that provide functional tools or applications rather than traditional gameplay experiences. These “games” often serve practical purposes, such as creating art, managing tasks, or enhancing the user experience on a computer.
Key Features of Utilities Games
- Productivity Enhancement: Utilities games often include features that help users stay focused and organized. For example, Virtual Cottage provides a cozy virtual environment to set goals and work without distractions.
- Creative Tools: Some utilities games are designed to foster creativity. Aseprite is a pixel-art tool that allows users to create 2D animations and sprites for games.
- System Optimization: Utilities games can also help optimize system performance. CPUCores is a tool that isolates and dedicates central processing unit (CPU) resources to improve gaming performance.
- Customization: Many utilities games offer extensive customization options. Wallpaper Engine allows users to create and animate live wallpapers for their desktops.
Popular Types of Utilities Games
- Creativity and Design Tools: These “games” function as creative suites for artists, designers, and content creators. Examples include Aseprite (pixel-art and sprite-animation tool), Blender (Steam distribution; 3D modeling, animation, and rendering), and RPG Maker Tools (create sprites, maps, and game assets).
- System Enhancement and Personalization Tools: Designed to customize or optimize the user’s computer experience. Examples include Wallpaper Engine (animated desktop backgrounds), CPUCores (CPU optimization for gaming performance), Rainmeter Skins (via Steam tools; desktop information and visualization widgets).
- Productivity and Focus Tools: Applications that create calming or structured environments to support work or study. Examples include Virtual Cottage (a relaxing space to help users stay focused), Lofi Room / Ambient Focus Tools (provide sounds and visual ambience), and other task organizers distributed through Steam utility categories.
- Simulation-Based Utilities: Tools that provide utility through simulated or controlled environments. Examples include PC Building Simulator (both a game and learning tool for PC hardware assembly) and other logic/puzzle toolkits used for teaching circuits and computing concepts.
Popular Utilities Games
- Wallpaper Engine: Allows users to create and use animated wallpapers on their desktops.
- Aseprite: A pixel-art tool for creating 2D animations and sprites.
- Blender: A comprehensive 3D creation suite used for modeling, animation, and rendering.
- Virtual Cottage: Provides a relaxing virtual environment to help users focus and be productive.
These utilities can be incredibly useful for creative projects, productivity, and personalizing your digital workspace.
1.3.10. Game Demos
Game demos are trial versions of video games that allow players to experience a portion of the game before deciding to purchase the full version. They are a great way to try out new titles and get a feel for the gameplay, graphics, and overall experience.
Key Features of Game Demos
- Limited Content: Demos typically include a small portion of the game, such as the first few levels, a specific mission, or a limited-time trial.
- Free to Play: Most game demos are free to download and play, providing a risk-free way to try out new games.
- Showcase Gameplay: Demos are designed to highlight the core mechanics, graphics, and features of the game to entice players to purchase the full version.
- Feedback Opportunity: Developers can use demos to gather feedback from players, which can be valuable for making improvements before the full release.
Game demos are often distributed as shareware, demo discs, or downloadable software.
Popular Platforms for Game Demos
- Steam: Steam offers a wide variety of free game demos that you can download and play. It’s a great platform to explore new titles and try before you buy.
- Xbox: The Microsoft Store on Xbox provides numerous game demos for players to try out. You can find demos for both new and upcoming games.
- Epic Games Store: The Epic Games Store also features a selection of game demos, allowing players to experience a portion of the game before making a purchase.
Examples of Game Demos
- The First Berserker—KhazanDemo: A demo for an action-adventure game where players can experience the initial gameplay and story.
- SWORD ART ONLINE Fractured DaydreamDemo: A demo for a role-playing game based on the popular anime series.
- PowerWash SimulatorDemo: A demo for a simulation game where players can try out the power washing mechanics and complete a few cleaning tasks.
Benefits of Playing Game Demos
- Informed Decisions: Trying a demo helps you make an informed decision about whether to purchase the full game.
- Discover New Games: Demos allow you to explore new genres and titles that you might not have considered otherwise.
- Early Access: Some demos provide early access to upcoming games, giving you a sneak peek before the official release.
1.3.11. Emulators and Video Games
Emulated games are video games run on a platform other than the one they were originally designed for, using software called an emulator. An emulator lets a host device such as a PC, smartphone, or other modern platform mimic the behavior of a different, often older, gaming system so it can run software and games developed for that original system. Emulation is especially useful for preserving and playing retro games on contemporary hardware.
Emulators are also widely used for software development and testing, allowing developers to run and debug applications on multiple platforms without requiring the actual hardware. For example, developers commonly write Android apps on a PC and use an Android emulator to verify how the app functions on a simulated phone.
Key Features of Emulators
- Compatibility: Emulators can run games from various classic gaming systems, including consoles like the NES, SNES, Sega Genesis, Game Boy, PlayStation, and more.
- Preservation: Emulators help preserve classic games that might otherwise be lost because of outdated hardware. They allow new generations of players to experience these games.
- Customization: Many emulators offer features like save states, enhanced graphics, and controller support, which can improve the gaming experience.
- Accessibility: Emulators make it possible to play games on devices that were not originally designed for them, such as playing a Game Boy game on a PC.
- Functionality: Emulators replicate the hardware and software environment of the target system, allowing games and applications to run as if they were on the original hardware.
- Types: There are emulators for various platforms, including classic consoles like the NES, SNES, Sega Genesis, PlayStation, and more.
- Usage: They are popular among retro gaming enthusiasts who want to play old games that are no longer available or supported on modern hardware.
Popular Types of Emulators
- RetroArch: A versatile emulator that supports a wide range of gaming systems through “cores” that can be downloaded and installed.
- Dolphin: A popular emulator for Nintendo GameCube and Wii games, known for its high compatibility and performance.
- PCSX2: An emulator for PlayStation 2 games, offering a range of features to enhance the gaming experience.
- PPSSPP: An emulator for PlayStation Portable (PSP) games, known for its high compatibility and ability to run games at higher resolutions.
- Cemu: An emulator for the Nintendo Wii U, allowing players to enjoy Wii U games on their PCs.
Popular Emulator Games
- Super Mario 64: Originally for the Nintendo 64, this classic platformer can be played on various emulators.
- The Legend of Zelda: Ocarina of Time: Another Nintendo 64 classic that is widely enjoyed through emulation.
- Pokémon FireRed: A Game Boy Advance game that remains popular among emulator users.
- Final Fantasy VII: Originally for the PlayStation, this iconic RPG is often played on emulators.
- Metroid Prime: A GameCube game that is frequently emulated using Dolphin.
Legal Considerations
While emulators themselves are legal, downloading and using game ROMs (the game files) can be legally complex. It’s important to only use ROMs (or the software image file) for games that you own or that are legally available for download. Always respect copyright laws and the rights of game developers.
1.4. Road Map of Game Development
1.4.1. Process of Game Development
In section 1.3, we explored different game genres and their unique characteristics. This section is to help you understand the game development process, including concept ideation, design, implementation, and testing.
Game development is a fascinating and complex process that involves several stages. Here’s a high-level overview of the key steps:
- 1. Concept and Planning
- Idea Generation: Brainstorming and coming up with the game’s concept
- Market Research: Understanding the target audience and market trends
- Game Design Document (GDD): Creating a detailed document outlining the game’s mechanics, story, characters, and more
- 2. Pre-Production
- Prototyping: Developing a basic version of the game to test concepts and gameplay mechanics
- Technical Planning: Deciding on the technology stack, tools, and platforms to be used
- Team Assembly: Gathering a team of developers, artists, designers, and other necessary roles
- 3. Production
- Art and Design: Creating the visual elements, including characters, environments, and user interfaces
- Programming: Writing the code that makes the game function
- Audio Design: Developing sound effects, music, and voice acting
- Level Design: Building the game’s levels and ensuring they are engaging and balanced
- 4. Testing
- Quality Assurance (QA): Identifying and fixing bugs and glitches
- Playtesting: Gathering feedback from players to improve gameplay and balance
- 5. Launch
- Marketing and Promotion: Creating buzz and awareness about the game
- Distribution: Releasing the game on various platforms (e.g., Steam, consoles, mobile)
- 6. Postlaunch
- Updates and Patches: Fixing any issues that arise after launch and adding new content
- Community Engagement: Interacting with players and building a community around the game
Each of these stages requires collaboration and creativity, and the process can vary depending on the size of the team and the scope of the game. Are you interested in any specific part of game development?
1.4.2. Programming Languages and Tools
There are several popular programming languages used in game development, each with its own strengths and applications. Here are some of the most commonly used ones:
- C++: Known for its performance and control over system resources, C++ is widely used in game development, especially for high-performance games. It’s used in many game engines like Unreal Engine.
- C#: This language is popular because of its use in the Unity game engine, which is one of the most widely used game development platforms. C# is known for being relatively easy to learn and use.
- Java: Java is versatile and can be used for both desktop and mobile game development. It’s particularly popular for Android game development.
- Python: While not as common for high-performance games, Python is great for beginners and is used in some game development frameworks like pygame.
- JavaScript: Essential for web-based games, JavaScript works well with HTML5 and CSS3 to create interactive games that run within browsers.
- Lua: Often used as a scripting language in game engines like Unity, Corona SDK, and Roblox, Lua is lightweight and easy to embed.
Each of these languages has its own community and resources, making it easier to find tutorials and support as you learn.
To be an effective game developer, one also needs to be familiar with integrated development environments (IDEs) and game engines.
There are several popular IDEs and game engines that developers use to create games. Here are some of the commonly used ones.
Game Engines
- Unity: One of the most popular game engines, Unity is known for its versatility and ease of use. It supports both 2D and 3D game development and is widely used for mobile, PC, and console games.
- Unreal Engine: Renowned for its high-quality graphics and realistic physics, Unreal Engine is a favorite for AAA game development. It features a visual scripting system called Blueprints, which allows developers to create game logic without extensive coding.
- Godot Engine: An open-source game engine that is gaining popularity, especially among indie developers. Godot offers a powerful 2D and 3D rendering engine and is known for its flexibility and ease of use.
- GameMaker Studio: Ideal for 2D game development, GameMaker Studio is user-friendly and allows developers to create games with minimal coding. It’s popular for indie and mobile games.
IDEs
- Visual Studio: A powerful IDE used by many professional game developers. It supports multiple programming languages and integrates well with popular game engines like Unity and Unreal Engine.
- JetBrains Rider: Known for its robust code analysis and debugging tools, Rider supports multiple languages and integrates with Unity and Unreal Engine.
- MonoDevelop: An open-source IDE that is simple and easy to use. It supports multiple languages and integrates with Unity and Godot Engine.
These tools provide a range of features that help streamline the game development process, from coding and debugging to designing and testing.
1.4.3. Game Design Principles
Game design principles are essential guidelines that help create engaging and enjoyable gaming experiences. Here are some of the key ones:
- Clear Goals and Objectives: Players should always know what they need to achieve. Clear goals provide direction and motivation, keeping players engaged.
- Engaging Core Mechanics: The core mechanics are the fundamental actions players perform in the game. These should be intuitive and enjoyable, forming the backbone of the gameplay experience.
- Balanced Challenge and Skill: Games should balance difficulty to match the player’s skill level. This keeps the game challenging but not frustrating, maintaining a state of “flow,” where players are fully immersed.
- Feedback and Rewards: Providing immediate feedback and rewards for player actions helps reinforce learning and keeps players motivated. This can include points, achievements, or visual and audio cues.
- Immersive Storytelling: A compelling narrative can enhance the gaming experience by providing context and emotional engagement. Good storytelling can make players care about the characters and the world.
- Player Agency: Allowing players to make meaningful choices that affect the game world and outcomes increases engagement and investment in the game.
- Aesthetic and Audio Design: Visual and audio elements should complement the gameplay and enhance the overall experience. Good design can create an immersive atmosphere and evoke emotions.
These principles help ensure that a game not only is fun to play but also provides a satisfying and memorable experience.
1.4.4. Graphics and Animation in Video Games
Graphics and animation are crucial components of games; they enhance the visual appeal and immersive experience of games. These elements work together to create visually stunning and more interactive gaming experiences.
Graphics in Game Development
- 2D and 3D Graphics: Games can feature either 2D or 3D graphics. 2D graphics are often used in simpler, indie games, while 3D graphics are common in more complex, high-budget games. Tools like Adobe Photoshop and GIMP are popular for creating 2D assets, while Blender and Maya are widely used for 3D modeling.
- Rendering: This is the process of generating the final visual output from the game’s assets. Real-time rendering is crucial for games, allowing for dynamic and interactive environments. DirectX and OpenGL are common APIs used for rendering.
- Shaders: Shaders are programs that run on the graphics processing unit (GPU) to control the rendering of graphics. They can create various effects like lighting, shadows, and textures, enhancing the visual quality of the game.
Animation in Game Development
Big or small, most video games have one feature in common—that is, animated graphics and figures. To use animations properly and effectively, one needs to carefully study the following:
- Principles of Animation: Game animation commonly applies multiple classical animation principles, including squash and stretch, anticipation, and timing, to enhance realism and player engagement.
- Rigging and Skinning: Rigging involves creating a skeleton for 3D models, while skinning attaches the model to the skeleton. This allows for realistic movement and deformation of characters.
- Animation Techniques: Techniques like keyframe animation, motion capture, and procedural animation are used to create character movements. Keyframe animation involves manually setting key points of motion, while motion capture records real-life movements for more realistic animations.
- Animation Systems: Modern game engines like Unity and Unreal Engine have built-in animation systems that support complex animations, including blend trees and inverse kinematics.
One may also use some specific tools to produce 2D or 3D animation, such as the following:
- Unity: Offers robust tools for both 2D and 3D animation, including a powerful Animator component.
- Unreal Engine: Known for its high-quality graphics and advanced animation tools, including the use of Blueprints for visual scripting.
- Blender: An open-source tool for 3D modeling and animation, widely used in the industry.
1.4.5. Physics and Simulation
Physics and simulation play a crucial role in creating realistic and immersive experiences in video games.
Physics in Game Development
- Rigid Body Dynamics: This involves simulating the motion and interaction of solid objects. It’s essential for creating realistic collisions and movements. Physics engines like Havok and PhysX are commonly used for these simulations.
- Soft Body Dynamics: Unlike rigid bodies, soft bodies can deform and change shape. This is used for simulating objects like cloth, jelly, or even characters’ skin.
- Fluid Dynamics: Simulating liquids and gases can add a lot of realism to games. This includes water, smoke, fire, and other fluid-like behaviors. Advanced techniques and powerful hardware are often required for these simulations.
- Ragdoll Physics: This technique is used to simulate the natural movement of characters’ limbs when they are knocked down or killed. It enhances realism by allowing characters to react dynamically to forces.
Simulation in Game Development
- Environmental Simulation: This includes weather systems, day-night cycles, and other environmental effects that make the game world feel alive and dynamic.
- AI Simulation: Simulating intelligent behavior in nonplayer characters (NPCs) is crucial for creating engaging and challenging gameplay. This involves pathfinding, decision-making, and learning algorithms.
- Vehicle Simulation: For games involving vehicles, realistic simulation of driving physics—including traction, suspension, and collision—is essential.
1.4.6. User Interface Design
User Interface (UI) design is a critical aspect of game development, as it directly impacts the player’s experience and interaction with the game. It’s not uncommon to read game comments or reviews about how much better a game would be if it weren’t for the badly designed UI. Here are some key principles and tools involved in UI design for games.
Key Principles of UI Design
- Clarity: UI elements should be clear and easy to understand. Players should be able to quickly grasp what each element does without confusion.
- Consistency: Consistent design elements help players learn and predict how the UI will behave. This includes consistent use of colours, fonts, and layouts.
- Simplicity: A simple and uncluttered UI reduces cognitive load, making it easier for players to focus on the game itself.
- Functionality: The UI should be designed with the game’s mechanics in mind, ensuring that it supports and enhances gameplay rather than hindering it.
- Feedback: Providing immediate feedback for player actions helps reinforce learning and keeps players informed about the game’s state.
Tools for UI Design
- Unity: Unity offers robust tools for creating UI elements, including the Unity UI system and the newer UI Toolkit. These tools allow for the creation of complex, scalable, and performant interfaces.
- Unreal Engine: Unreal Engine’s UMG (Unreal Motion Graphics) provides a powerful framework for designing and implementing UI. It supports both visual scripting and traditional coding.
- Adobe XD: This tool is excellent for wireframing and prototyping UI designs. It allows designers to create interactive mock-ups and test navigation flows before implementation.
- Sketch: Another popular tool for UI design, Sketch is known for its ease of use and powerful vector-editing capabilities. It’s widely used for designing game interfaces.
Key Components in Game UI
- Health Bars and HUDs (Heads-Up Displays): These elements provide essential information about the player’s status and game environment.
- Menus and Navigation: Intuitive menus and navigation systems help players access different parts of the game easily.
- Interactive Elements: Buttons, sliders, and other interactive elements should be responsive and provide clear feedback.
Effective UI design enhances the overall gaming experience by making it more intuitive and enjoyable.
1.4.7. Sound Effects with Sound and Music Integration
Sound and music integration are vital for creating immersive and engaging experiences in video games.
Key Aspects of Sound and Music Integration
- Setting the Mood: Music sets the tone and atmosphere of the game, enhancing the emotional experience. For example, a suspenseful soundtrack can heighten tension during critical moments.
- Enhancing Gameplay: Sound effects provide immediate feedback for player actions, making the game more interactive and responsive. This includes sounds for actions like jumping, shooting, or collecting items.
- Creating Immersive Environments: Ambient sounds and background music help create a believable game world. This can include environmental sounds like wind, water, and wildlife.
- Dynamic Audio: Adaptive music systems change the soundtrack based on the player’s actions or game events, ensuring that the audio experience is always relevant and engaging.
Tools for Sound and Music Integration
- FMOD: A popular audio middleware that allows developers to create complex audio behaviors without extensive coding. FMOD integrates well with game engines like Unity and Unreal Engine.
- Wwise: Another powerful audio middleware, Wwise offers advanced features for audio integration, including real-time parameter control and interactive music systems.
- Unity: Unity’s built-in audio tools support a wide range of audio features, from simple sound effects to complex audio environments. Unity also supports integration with FMOD and Wwise.
- Unreal Engine: Known for its high-quality audio capabilities, Unreal Engine provides robust tools for sound design and music integration, including support for spatial audio and real-time audio effects.
Skills Involved
- Sound Design: Creating and implementing sound effects that match the game’s visual and interactive elements.
- Music Composition: Composing original music that enhances the game’s narrative and emotional impact.
- Audio Scripting: Using scripts to control when and how sounds are played, ensuring they align with game events and player actions.
1.4.8. Gameplay Programming
Gameplay programming is a crucial aspect of game development, focusing on creating the interactive elements that make a game enjoyable and engaging.
Key Responsibilities of Gameplay Programming
- Implementing Game Mechanics: Gameplay programmers bring the game design to life by coding the core mechanics, such as character movement, player controls and interaction, combat systems, and puzzle logic, as well as implementing features like scoring systems, power-ups, and enemy behavior.
- Balancing and Tuning: They ensure that the game is fun and challenging by adjusting variables and fine-tuning gameplay elements. This involves playtesting and iterating based on feedback.
- Collaboration: Gameplay programmers work closely with designers, artists, and other developers to integrate various game components seamlessly. Effective communication and teamwork are essential.
- Bug Fixing and Optimization: They identify and fix bugs to ensure a smooth gaming experience. Optimization is also crucial to maintain performance, especially on different hardware platforms.
Tools and Technologies
- Game Engines: Popular game engines like Unity and Unreal Engine provide robust frameworks for gameplay programming. These engines offer tools and libraries that simplify the development process.
- Scripting Languages: Many game engines use scripting languages like C# (Unity) or Blueprints (Unreal Engine) to implement gameplay features. These languages allow for rapid prototyping and iteration.
- Version Control Systems: Tools like Git are essential for managing code changes and collaborating with other team members. They help track progress and revert to previous versions if needed.
Skills and Knowledge
- Programming Proficiency: Strong skills in languages like C++, C#, or Python are essential. Understanding object-oriented programming and design patterns is also important.
- Mathematics and Physics: A good grasp of mathematics and physics helps in implementing realistic game mechanics and simulations.
- Problem-Solving: Gameplay programmers need to be adept at solving complex problems and debugging issues that arise during development.
1.4.9. Artificial Intelligence Techniques for Game Programming
Artificial Intelligence (AI) is a powerful tool in game programming, enhancing the complexity and realism of games.
Key Techniques of AI for Game Development
- Finite State Machines (FSMs): FSMs are used to manage the states and transitions of game entities. They are ideal for simple AI behaviors, such as enemy patrol routes or basic decision-making.
- Behavior Trees: These hierarchical models are used to create complex behaviors by organizing tasks and decisions in a tree structure. They are more flexible than FSMs and are commonly used for NPC behaviors.
- Pathfinding Algorithms: Algorithms like A* (A-star) are used to navigate game environments. They help characters find the shortest path between points, avoiding obstacles and optimizing movement.
- Decision Trees: These are used for making decisions based on a series of conditions. They can be trained to perform classification and regression tasks, making them useful for dynamic decision-making.
- Neural Networks: Deep learning models, such as neural networks, can learn from data to perform tasks like pattern recognition and decision-making. They are used for more advanced AI behaviors, such as adaptive learning and complex strategy.
- Genetic Algorithms: These algorithms simulate the process of natural selection to optimize solutions. They are used for tasks like procedural content generation and evolving game strategies.
- Reinforcement Learning: This technique involves training AI agents to make decisions by rewarding them for desirable actions. It is used for creating adaptive and intelligent behaviors that improve over time.
Practical Applications of AI in Game Programming
- NPC Behavior: AI techniques are used to create realistic and responsive nonplayer characters (NPCs) that can interact with players in meaningful ways.
- Procedural Content Generation: AI can generate game content—such as levels, maps, and quests—dynamically providing a unique experience for each player.
- Adaptive Difficulty: AI can adjust the game’s difficulty based on the player’s skill level, ensuring a balanced and engaging experience.
Tools and Frameworks
- Unity: Supports various AI techniques through built-in tools and third-party plugins.
- Unreal Engine: Offers robust AI tools, including behavior trees and pathfinding systems.
- Python and Pygame: Python is popular for AI game programming because of its simplicity and powerful libraries (like pygame).
AI in game programming is a dynamic field that continues to evolve, offering endless possibilities for creating immersive and engaging gaming experiences.
1.4.10. Game Optimization and Performance
Game optimization is about techniques for optimizing code, reducing memory usage, and improving frame rates, as well as profiling tools and debugging strategies.
These performance improvements are crucial aspects of game development that ensure a smooth and enjoyable experience for players. You can have the best game in the world, but if it crashes randomly or has slow/laggy graphics or responsiveness, people will stop playing it.
Knowledge Areas
Understanding Game Performance Metrics
- Frame Rate (fps): Ensuring a high and stable frame rate for smooth gameplay
- CPU and GPU Usage: Balancing the workload between the CPU and GPU to avoid bottlenecks
- Memory Consumption: Efficiently managing memory to prevent leaks and excessive usage
Optimization Techniques
- Memory Management: Techniques like memory pooling and data structure optimization to reduce overhead
- Asset Streaming: Loading only necessary assets on-the-fly to reduce load times and memory usage
- Frame Rate Stabilization: Using methods like dynamic resolution scaling and optimizing rendering paths
Profiling and Debugging
- Profiling Tools: Using tools to analyze performance metrics and identify bottlenecks
- Debugging Skills: Identifying and fixing performance-related bugs and issues
Skills
Programming Skills
- Efficient Coding: Writing optimized code that runs efficiently on various hardware
- Knowledge of Game Engines: Understanding how to use and optimize popular game engines like Unity and Unreal Engine
Graphics and Rendering
- Shader Optimization: Writing efficient shaders to reduce rendering load
- Level of Detail (LOD): Implementing LOD systems to adjust the detail of models and textures based on their distance from the camera
System Design
- Asynchronous Loading: Implementing asynchronous loading to improve user experience by reducing perceived load times
- Segmentation and Prioritization: Dividing game assets into segments and prioritizing their loading based on the player’s current state
Testing and Quality Assurance
- Playtesting: Gathering feedback from players to identify performance issues
- Automated Testing: Using automated tests to regularly check for performance regressions
Tools
- Profilers: Tools like Unity Profiler, Unreal Engine Profiler, and external tools like NVIDIA Nsight
- Debuggers: Tools like Visual Studio Debugger, GDB, and platform-specific debuggers
Mastering these knowledge areas and skills can significantly enhance your ability to optimize game performance and deliver a seamless gaming experience.
1.4.11. Game Programming Library vs. Game Engines
Libraries and frameworks serve specific and fundamental needs of game programming, whereas a game engine encompasses all the necessary components more directly for creating a complete game experience. Libraries, such as Allegro for game development or FMOD for audio, provide specialized functions that developers can integrate into their projects to build customized solutions. In contrast, game engines like Unity or Unreal Engine offer a comprehensive suite of tools and features, simplifying the development process and often including built-in support for various aspects such as rendering, physics, and sound. While libraries require a deeper understanding and manual integration, game engines offer an all-in-one solution, making them more accessible for rapid development.
Game Development Libraries
A library is a collection of code modules or functions that serve specific purposes. These modules can be used to accomplish tasks like math calculations, file loading, collision detection, rendering, and more. Some libraries concentrate on a specific area; others encompass a variety of functions. Allegro has a variety of game-related functions, including sound handling, while DirectSound only entails sound-specific functions.
The purpose of libraries is to provide building blocks for developers to create their own custom solutions. As noted, some focus on specific functionalities and others are general, but typically they are modular.
Examples of game development libraries include the following:
- • Allegro (for game development)
- • Novodex (for physics)
- • FMOD (for audio)
- • Havok (for physics)
- • Ogre3D (for rendering)
- • BINK (for video playback)
- • Direct3D and OpenGL (for graphics)
- • DirectSound (for audio)
- • XInput (for input handling)
Game Engines
A game engine is an extensive framework specifically designed for creating games. It goes beyond libraries and frameworks by providing a comprehensive solution.
Components of a game engine typically include:
- Rendering Engine: Handles graphics and rendering
- Physics Engine: Manages physical interactions
- Audio System: Deals with sound effects and music
- Input Handling: Captures user input (keyboard, mouse, controllers)
- Networking: Facilitates multiplayer functionality
- Resource Management: Efficiently manages assets (textures, models, sounds)
Examples of game engines include:
- • Unreal Engine
- • Unity Engine
- • Source Engine
- • Quake Engine
- • Reality Engine
Generally speaking, the distinction between a library and an engine lies in the level of abstraction and the scope of functionality.
1.5. Set Up Game Development IDE
Allegro game library is platform independent, and can be used on Windows, Linux, Apple iOS, and Android as well. In this section, we will explain how a game development environment can be set up on Windows, Linux, and MacOS.
The Allegro 5 library serves as a framework for game development, encompassing essential aspects like math, physics, rendering, and audio. It provides a cohesive set of tools, conventions, and patterns to simplify development, offering a solid foundation for building applications or games.
Allegro 5 offers a comprehensive suite of functions that enable developers to manage graphics, handle user input, and incorporate sound effects seamlessly. This framework ensures efficient resource management and supports flow control, providing a structured approach to game development.
We are going to learn game programming with the Allegro 5 game library in C++ in this book. In order to make our game programming more efficient, especially when working on large game projects, we need to have an integrated development environment. There are different ways of setting up an IDE on your chosen computing platform to meet our needs. In this book, however, we will be using the same set of open-source software tools for all three types of computing platforms (Windows, Linux, and MacOS) we cover in this book. The tools in the set are VS Code by Microsoft, GCC by GNU, CMake, and Ninja.
1.5.1. Visual Studio Code with MinGW GCC, CMake, and Ninja
Visual Studio Code
Visual Studio Code (VS Code) is a popular, open-source code editor developed by Microsoft. It’s known for its versatility, ease of use, and extensive features that cater to a wide range of programming needs.
Those features include extensibility, with an integrated terminal, debugging tools, IntelliSense tools for efficient coding, version controls for project development, and customization options for the entire IDE, as well as Live Share, which allows you to collaborate with others across the globe, such as through GitHub.
MinGW GCC
MinGW-w64 is a popular and comprehensive development environment for building native Windows applications. It offers the following key features:
- Complete Runtime Environment: MinGW-w64 provides a complete runtime environment for the GCC (GNU Compiler Collection) to support binaries native to both 32-bit and 64-bit Windows operating systems.
- Wide Compatibility: It supports a wide range of Windows APIs and is compatible with various libraries and tools, making it suitable for developing a broad spectrum of applications.
- Multilib Toolchains: MinGW-w64 supports multilib toolchains, allowing you to build both 32-bit and 64-bit binaries from the same environment.
- Advanced Features: It includes support for native TLS (thread local storage) callbacks, wide-character start-up, and more.
- Cross-Platform Development: MinGW-w64 can be used in conjunction with other projects like Cygwin, MSYS2, and Wine, facilitating cross-platform development.
CMake
CMake is a powerful and widely used open-source tool designed to manage the build process of software projects.
Key Features
Here are some key aspects of CMake:
- Cross-Platform: CMake supports multiple platforms, including Windows, macOS, and Linux, allowing developers to write build scripts that work across different operating systems.
- Out-of-Source Builds: It supports out-of-source builds, which means you can keep your source directory clean by generating build files in a separate directory.
- Single Source Builds: CMake allows you to use a single source tree to build your project on multiple platforms, simplifying the build process.
- Extensive Language Support: It supports a variety of programming languages, including C, C++, Fortran, and more.
- Custom Scripting Language: CMake includes its own scripting language, which allows you to define build configurations, manage dependencies, and customize the build process.
- Integration with IDEs: CMake integrates well with various integrated development environments (IDEs) like Visual Studio, CLion, and Xcode.
How CMake Works
The core of a CMake project is the CMakeLists.txt file, which contains commands and instructions for building the project. This file specifies the source files, build options, and dependencies.
- Configuration and Generation: CMake first configures the project by reading the CMakeLists.txt file and then generates the necessary build files for the chosen build system (e.g., Makefiles, Visual Studio project files).
Here’s a very simple example of CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(MyProject)
set(CMAKE_CXX_STANDARD 17)
add_executable(MyProject main.cpp)
- Configure and Build: Open a terminal, navigate to your project directory, and run:
cmake .
to configure the project.
And then run:
cmake --build .
to build the project.
CMake is a versatile tool that can significantly streamline the build process for complex projects.
Ninja
Ninja is a small, high-speed build system designed to handle the build process for large software projects efficiently.
Key Features
Here are some key aspects of Ninja:
- Speed: Ninja is optimized for speed, making it ideal for large projects that require fast incremental builds. Using it on top of CMake minimizes the time spent on build tasks by focusing on quick dependency checking and parallel execution. It has the following attractive features:
- Simplicity: Ninja uses a minimal build description language, which is not intended to be written by hand. Instead, it relies on higher-level build systems like CMake, GYP, or Meson to generate its build files.
- Efficiency: Ninja is designed to be an “assembler” for build systems, meaning it takes care of the low-level details of the build process, allowing higher-level tools to handle the more complex configuration tasks.
- Cross-Platform: Ninja supports multiple operating systems, including Linux, macOS, and Windows, making it a versatile tool for cross-platform development. Ninja is a powerful tool for developers looking to optimize their build processes.
How Ninja Works
- Build Files: Ninja uses .ninja build files, which are typically generated by higher-level build systems. These files contain the rules and dependencies needed to build the project.
- Incremental Builds: Ninja excels at performing incremental builds, where only the parts of the project that have changed are rebuilt. This significantly reduces build times compared to traditional build systems.
- Parallel Execution: Ninja can execute build tasks in parallel, taking full advantage of multicore processors to speed up the build process.
Using Ninja on Top of CMake
Using Ninja on top of CMake offers several benefits, particularly for large and complex projects. Here are some key reasons why this combination is advantageous.
Speed
- Fast Builds: Ninja is designed for speed, focusing on quick dependency checking and parallel execution. This makes it significantly faster than traditional build systems like Make, especially for incremental builds.
- Efficient Dependency Management: Ninja efficiently handles dependencies, ensuring that only the necessary parts of the project are rebuilt, which further reduces build times.
Simplicity and Automation
- Generated Build Files: Ninja build files are typically generated by higher-level build systems like CMake. This means you don’t have to write Ninja build scripts by hand, simplifying the build process.
- Integration with CMake: CMake can generate Ninja build files, allowing you to leverage CMake’s powerful configuration capabilities while benefiting from Ninja’s fast build performance.
Efficient Cross-Platform Development
CMake supports multiple platforms, and by using Ninja as the build tool, you can ensure consistent and fast builds across different operating systems.
1.5.2. Windows OS: Setting Up IDE for Game Programming with Allegro 5 in C/C++
In this subsection, we will explain how to install MinGW GCC, Visual Studio Code (Code), CMake, and Ninja on Windows and make them work together as an integrated development environment (IDE) for game development.
Setting up Visual Studio Code (VS Code) for game development with MinGW GCC, CMake, and Ninja involves several steps. Here’s a detailed guide to help you get started.
Install Visual Studio Code
- 1. Download Visual Studio Code from the official website (https://code.visualstudio.com/download).
- 2. Run the installer and follow the on-screen instructions to complete the installation.
Install MinGW-w64
GCC can be installed through MinGW installer:
- 1. Download the MinGW-w64 installer from the MSYS2 website.
- 2. Run the installer and follow the steps to install MSYS2.
- 3. Open the MSYS2 terminal and install the MinGW-w64 toolchain by running:
pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain
- 4. Add the path of your MinGW-w64 bin folder to the Windows PATH environment variable:
- • Open Windows Settings and search for “Edit environment variables for your account.”
- • In the User variables section, select the Path variable and click Edit.
- • Add the path to the MinGW-w64 bin folder (e.g., C:\msys64\ucrt64\bin).
Install CMake
- 1. Download CMake from the official website.
- 2. Run the installer and follow the on-screen instructions to complete the installation.
- 3. Add CMake to your system PATH during the installation process.
Install Ninja
Install Ninja on Windows
- 1. Download the binary from the Ninja releases page, or download Ninja from the official GitHub repository.
- 2. Extract the downloaded file.
- 3. Add it to your system PATH.
Generate Ninja Build Files with CMake
- 1. Create a CMakeLists.txt file for your project.
- 2. Run CMake with Ninja as the generator:
cmake -G Ninja.
- 3. Build your project using Ninja:
ninja
Here’s a simple example of a CMakeLists.txt file for a project using Ninja.
Example CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(MyProject)
set(CMAKE_CXX_STANDARD 17)
add_executable(MyProject main.cpp)
Install Allegro 5
- 1. Download Allegro 5
Visit the Allegro 5 download page and download the prebuilt binaries for MinGW.
- 2. Extract Allegro 5
Extract the Allegro 5 archive to a directory of your choice—for example, C:\allegro5.
- 3. Set Up Environment Variables
Add the path to Allegro’s bin directory (e.g., C:\allegro5\bin) to your system’s PATH environment variable.
1.5.3. Linux OS: Setting Up IDE for Game Programming with Allegro 5 in C/C++
Here’s a step-by-step guide to set up Visual Studio Code (VS Code) with GCC, CMake, and Ninja for game programming with Allegro 5 on Linux.
Install Visual Studio Code
- 1. Download VS Code
Go to the Visual Studio Code download page and download the appropriate package for your Linux distribution.
- 2. Install VS Code
- • For Debian-based distributions (e.g., Ubuntu), use:
sudo apt install ./<file>.deb
- • For RedHat-based distributions (e.g., Fedora), use:
sudo rpm -i <file>.rpm
Install GCC
- 1. Update Package Lists
sudo apt update
- 2. Install GCC
sudo apt install build-essential
This command installs GCC, G++, and other essential development tools (https://www.linuxfordevices.com/tutorials/linux/install-cmake-on-linux).
Install CMake
- 1. Install CMake
sudo apt install cmake
Alternatively, you can download the latest version from the CMake website and follow the installation instructions (https://linuxcapable.com/how-to-install-cmake-on-ubuntu-linux/).
Install Ninja
- 1. Install Ninja
sudo apt install ninja-build
Alternatively, you can download the latest version from the Ninja releases page (https://github.com/ninja-build/ninja.git) and follow the installation instructions.
Install Allegro 5
- 1. Install Allegro 5
sudo apt install liballegro5-dev
1.5.4. Apple MacOS: Setting Up IDE for Game Programming with Allegro 5 in C/C++
For the most up-to-date instructions on installing VS Code, GCC/G++, CMake, and Ninja on macOS, please consult an AI assistant. The following guide, validated at the time of writing, is provided to help you get started.
Install Visual Studio Code
- 1. Download VS Code
Go to the Visual Studio Code download page (https://code.visualstudio.com/download) and download the macOS version.
- 2. Install VS Code
Open the downloaded .zip file and drag Visual Studio Code.app to the Applications folder.
Install GCC
- 1. Install Homebrew
Open the Terminal and run the following command to install Homebrew, a package manager for macOS:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- 2. Install GCC
Once Homebrew is installed, run:
brew install gcc
Install CMake
- 1. Install CMake
Use Homebrew to install CMake by running:
brew install cmake
Install Ninja
- 1. Install Ninja
Use Homebrew to install Ninja by running:
brew install ninja
Install Allegro 5
- 1. Install Allegro 5
Use Homebrew to install Allegro 5 by running:
brew install allegro
1.5.5. Configure Visual Studio Code to Make Everything Work Together
After you have all the tools and the Allegro 5 library installed on your platform, you need to start VS Code and make everything work together in the integrated development environment.
Install Extensions
- 1. Open VS Code and go to the Extensions view (⇧⌘X or Ctrl + Shift + X).
- 2. Search and install the following extensions:
- • C/C++ by Microsoft
- • CMake Tools by Microsoft
Test Your IDE by Developing a Simple Project
- 1. Create a project folder with the following structure:
- 2. Open your project folder in VS Code.
- 3. Open the CMakeLists.txt file and add the following to the file and save:
# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(HelloAllegro)
# Set C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# Find Allegro 5 package
find_package(PkgConfig REQUIRED)
pkg_check_modules(ALLEGRO5 REQUIRED allegro-5 allegro_main-5 allegro_image-5 allegro_font-5 allegro_ttf-5 allegro_primitives-5 allegro_audio-5 allegro_acodec-5)
# Include Allegro headers
include_directories(${ALLEGRO5_INCLUDE_DIRS})
# Add executable
add_executable(hello_allegro src/main.cpp)
# Link Allegro libraries
target_link_libraries(hello_allegro ${ALLEGRO5_LIBRARIES})
- 4. Create a main.cpp file in the src directory with the following code:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
int main() {
if (!al_init()) {
return—1;
}
al_init_font_addon();
al_init_ttf_addon();
ALLEGRO_DISPLAY* display = al_create_display(640, 480);
if (!display) {
return—1;
}
ALLEGRO_FONT* font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
al_destroy_display(display);
return—1;
}
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 320, 240, ALLEGRO_ALIGN_CENTER, "Hello, Allegro!");
al_flip_display();
al_rest(2.0);
al_destroy_font(font);
al_destroy_display(display);
return 0;
}
- 5. Configure CMake in VS Code
Within VS Code, open the Command Palette (⇧⌘P or Ctrl + Shift + P) and run CMake: Configure, then select the appropriate kit (e.g., GCC for MinGW-w64) and specify the generator as Ninja.
- 6. Build and Run Your Project
There are two ways to build and run the project. The first one is within a terminal on your computer:
- Step 1. Open a terminal within VS Code, or independent of VS Code on your computer, if you don’t have one already, and navigate to the project directory:
cd HelloAllegro
- Step 2. Generate build files with CMake:
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:/allegro5" .
- Step 3. Build the project with Ninja:
ninja
- Step 4. Run the program.
After building, you should have an executable named hello_allegro in your project directory. Run it from the terminal by typing hello_allegro and then hitting the return key to see the “Hello, Allegro!” message displayed in a window.
Another way is to build from the VS Code Command Palette:
- Step 1. Build your project.
- • Open the Command Palette (⇧⌘P or Ctrl+Shift+P) and run CMake: Configure.
- • Select the appropriate kit (e.g., GCC) and specify the generator as Ninja.
- • Run CMake: Build.
- Step 2. Run your project.
- • Use the CMake: Run command or configure a launch configuration in the launch.json file.
1.6. The Allegro 5 Game Library
One nice thing about modern game libraries is that there are many online resources available to help one use them, and Allegro 5 is no different. As such, in this textbook, you’ll have seen references to online materials, as they can do a fine job of explaining what needs to be known. What follows is a combination of information from the official Allegro 5 website (https://www.allegro.cc/manual/5/getting_started.html) with additional information provided by the authors of this text.
1.6.1. Overview of Allegro 5 Core Libraries and Add-Ons
Allegro 5.0 is divided into a core library and multiple add-ons. The add-ons are bundled together and built at the same time as the core, but they are distinct and kept in separate libraries. The core doesn’t depend on anything in the add-ons, but add-ons may depend on the core and other add-ons and additional third-party libraries.
Implemented in a single library file named allegro.lib on Windows and allegro.so on Linux and MacOS, Allegro core supports the use of the following resources:
- System: The Allegro 5 System library is a core part of the Allegro game programming library. It provides essential functions for initializing and managing the Allegro environment, handling system events, and managing resources. Defined in allegro.h so that no additional header file is needed.
- Display: Used for creating and managing displays (windows) in your applications. Defined in allegro.h.
- Events: Provides a comprehensive event system that allows you to handle various types of events, such as keyboard input, mouse input, timers, and more. allegro5/allegro_native_dialog.h is needed on top of allegro.h and header files for respective input devices to be used.
- File I/O: Provides a robust set of functions for file input and output (I/O), allowing you to read from and write to files in a cross-platform manner. Defined in allegro.h.
- Filesystem: Provides a set of functions for interacting with the filesystem, allowing you to manage files and directories in a cross-platform manner. Defined in allegro.h.
- Fixed-Point Math: Provides a set of functions for working with fixed-point arithmetic, which can be useful for certain types of calculations, especially in environments where floating-point operations are less efficient. Fixed-point numbers in Allegro are represented using a 32-bit integer type called al_fixed, where the high word is used for the integer part and the low word for the fractional part. allegro5/allegro_fixed.h is needed on top of allegro.h.
- Graphics: Provides a robust set of functions for handling graphics, allowing you to create and manipulate images, draw shapes, and manage colours. Only basic operations are defined in allegro5/allegro.h. For operations such as drawing various shapes, allegro5/allegro_primitives.h, an add-on, is needed.
- Joystick: Provides a set of functions for handling joystick input, allowing you to interact with joystick devices in your applications. allegro5/allegro_joystick.h is needed on top of allegro.h.
- Keyboard: Provides a comprehensive set of functions for handling keyboard input. allegro5/allegro_keyboard.h is needed on top of allegro.h.
- Mouse: Provides a comprehensive set of functions for handling mouse input and displaying a mouse cursor. allegro5/allegro_mouse.h is needed in addition to allegro.h.
- Memory: Provides several functions for memory management, allowing you to allocate, reallocate, and free memory in a consistent manner across different platforms. These basic operations on memory will work with only allegro.h.
- Path: Provides functions for manipulating and managing file system paths. This is useful for handling file and directory paths in a cross-platform manner. Defined in allegro.h.
- State: Provides functions to save and restore the state of various Allegro objects. This is useful for managing the state of graphics, transformations, and other settings in your application. Defined in allegro.h.
- Threads: Built on top of Windows threads and POSIX threads (pthreads), the library provides a simple cross-platform threading interface. Defined in allegro.h.
- Time: Provides functions to manage and measure time. Defined in allegro.h.
- Timer: Provides functions to create and manage timers. Defined in allegro.h, and no extra header file is needed.
- Transformations: Provides functions to manipulate and apply transformations to graphics. Defined in allegro.h.
- UTF-8: Provides support for UTF-8 encoded strings, which is essential for handling Unicode text in your applications. Defined in allegro.h.
- Miscellaneous: Includes various utility functions and features that don’t fit neatly into other specific categories. Defined in allegro.h.
- Platform-Specific Libraries: Includes libraries specific to Windows (Direct3D and Native dialogues), Linux (X11 integration and OpenGL integration), macOS (Cocoa integration and OpenGL ES integration), iOS (UIKit Integration and OpenGL ES integration), and Android (JNI integration and OpenGL ES integration).
- Direct3D: Provides integration with Direct3D, allowing you to use Direct3D for hardware-accelerated graphics on Windows. allegro5/allegro_direct3d.h is needed on top of allegro.h.
- OpenGL: Provides integration with OpenGL, allowing you to use OpenGL for hardware-accelerated graphics. allegro5/allegro_opengl.h is needed in addition to allegro.h.
The add-ons and their dependencies of libraries in the core are as follows:
- allegro_main, which depends on allegro
Ensures cross-platform compatibility for your main function. Required on Windows when using main() instead of WinMain().
- allegro_image, which depends on allegro
Provides support for loading and saving bitmap images in common formats such as PNG, JPG, BMP, and so on.
- allegro_primitives, which depends on allegro
Adds drawing functions for basic geometric shapes such as lines, rectangles, circles, polygons, and splines.
- allegro_color, which depends on allegro
Offers functions for working with colours, including conversions of colour spaces (RGB, HSV, HSL, etc.).
- allegro_font, which depends on allegro
Provides a system for loading, creating, and rendering bitmap fonts.
- allegro_ttf, which depends on allegro_font
Adds support for loading and rendering TrueType fonts via the FreeType library.
- allegro_audio, which depends on allegro
Implements an audio playback system, allowing you to play samples, streams, and manage audio voices.
- allegro_acodec, which depends on allegro_audio
Adds audio codecs for loading and saving common audio formats such as OGG, WAV, and FLAC.
- allegro_memfile, which depends on allegro
Provides the ability to treat blocks of memory as if they were file streams, useful for in-memory loading.
- allegro_physfs, which depends on allegro
Integrates PhysicsFS support, allowing Allegro to read from archive formats (ZIP, 7z, etc.) as if they were directories.
- allegro_native_dialog, which depends on allegro
Provides platform-native dialogues, such as file selectors, message boxes, and text log windows.
1.6.2. Fundamental Operations of Video Games with Allegro 5 in C/C++
The header file for the core library is allegro5/allegro.h. The header files for the add-ons are named allegro5/allegro_image.h, allegro5/allegro_font.h, and so on. The allegro_main add-on does not have a header file.
Initialization
Before using Allegro, you must call al_init. Some add-ons have their own initialization: for example, al_init_image_addon, al_init_font_addon, and al_init_ttf_addon.
To receive input, you need to initialize some subsystems like al_install_keyboard, al_install_mouse, and al_install_joystick.
Opening a Window
A call to al_create_display will open a window and return an ALLEGRO_DISPLAY.
To clear the display, call al_clear_to_color. Use al_map_rgba or al_map_rgba_f to obtain an ALLEGRO_COLOR parameter.
Drawing operations are performed on a backbuffer. To make the operations visible, call al_flip_display.
Display an Image
To load an image from disk, you need to have initialized the image I/O add-on with al_init_image_addon. Then use al_load_bitmap, which returns an ALLEGRO_BITMAP.
Use al_draw_bitmap, al_draw_scaled_bitmap, or al_draw_scaled_rotated_bitmap to draw the image to the backbuffer. Remember to call al_flip_display.
Changing the Drawing Target
Notice that al_clear_to_color and al_draw_bitmap didn’t take destination parameters—the destination is implicit. Allegro remembers the current “target bitmap” for the current thread. To change the target bitmap, call al_set_target_bitmap.
The backbuffer of the display is also a bitmap. You can get it with al_get_backbuffer and then restore it as the target bitmap.
Other bitmaps can be created with al_create_bitmap, with options that can be adjusted with al_set_new_bitmap_flags and al_set_new_bitmap_format.
Event Queues and Input
Input comes from multiple sources—keyboard, mouse, joystick, timers, and so on. Event queues aggregate events from all these sources, then you can query the queue for events.
Create an event queue with al_create_event_queue, then tell input sources to place new events into that queue using al_register_event_source. The usual input event sources can be retrieved with al_get_keyboard_event_source, al_get_mouse_event_source, and al_get_joystick_event_source.
Events can be retrieved with al_wait_for_event or al_get_next_event. Check the event type and other fields of ALLEGRO_EVENT to react to the input.
Displays are also event sources, which emit events when they are resized. We will need to set the ALLEGRO_RESIZABLE flag with al_set_new_display_flags before creating the display, then register the display with an event queue. When you get a resize event, call al_acknowledge_resize.
Timers are event sources that “tick” periodically, causing an event to be inserted into the queues that the timer is registered with. Create some with al_create_timer.
al_get_time and al_rest are more direct ways to deal with time.
Displaying Some Text
To display some text, initialize the image and font add-ons with al_init_image_addon and al_init_font_addon, then load a bitmap font with al_load_font. Use al_draw_text or al_draw_textf.
For TrueType fonts, you’ll need to initialize the TTF (TrueType font) add-on with al_init_ttf_addon and load a TTF font with al_load_ttf_font.
Drawing Primitives
The primitives add-on provides some handy routines to draw lines (al_draw_line), rectangles (al_draw_rectangle), circles (al_draw_circle), and so on.
Blending
To draw translucent or tinted images or primitives, change the blender state with al_set_blender.
As with al_set_target_bitmap, this changes Allegro’s internal state (for the current thread). Often, you’ll want to save some part of the state and restore it later. The functions al_store_state and al_restore_state provide a convenient way to do that.
Sound
Use al_install_audio to initialize sound. To load any sample formats, you will need to initialize the acodec add-on with al_init_acodec_addon.
After that, you can simply use al_reserve_samples and pass the number of sound effects typically playing at the same time. Then load your sound effects with al_load_sample and play them with al_play_sample. To stream large pieces of music from disk, you can use al_load_audio_stream so the whole piece will not have to be preloaded into memory.
If this all sounds too simple and you can’t help but think about clipping and latency issues, don’t worry. Allegro gives you full control over how much or little you want its sound system to do. The al_reserve_samples function mentioned here only sets up a default mixer and a number of sample instances, but you don’t need to use it.
Instead, to get a “direct connection” to the sound system, you would use an ALLEGRO_VOICE, but depending on the platform, only one such voice is guaranteed to be available, and it might require a specific format of audio data. Therefore, all sound can be first routed through an ALLEGRO_MIXER that is connected to such a voice (or another mixer) and will mix all sample data fed to it.
You can then directly stream real-time sample data to a mixer or a voice using an ALLEGRO_AUDIO_STREAM or play complete sounds using an ALLEGRO_SAMPLE_INSTANCE. The latter simply points to an ALLEGRO_SAMPLE and will stream it for you.
Code Samples
Text and Font
Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <cstdio>
Initialize Allegro and the font add-ons:
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—;
}
Create a display:
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—;
}
Load a font:
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_display(display);
return—;
}
Draw text to the screen:
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Hello, Allegro!");
al_flip_display();
al_rest(5.0);
Clean up:
al_destroy_font(font);
al_destroy_display(display);
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <cstdio>
int main() {
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—;
}
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—;
}
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_display(display);
return—;
}
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Hello, Allegro!");
al_flip_display();
al_rest(5.0);
al_destroy_font(font);
al_destroy_display(display);
return 0;
}
This example initializes Allegro, sets up the font add-ons, creates a display, loads a TrueType font, and draws text to the screen. It then waits for five seconds before cleaning up and closing the display.
Graphics
Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <cstdio>
Initialize Allegro and the image add-on:
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_init_image_addon()) {
fprintf(stderr, "Failed to initialize image addon!\n");
return—1;
}
Create a display:
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—1;
}
Load an image:
ALLEGRO_BITMAP *image = al_load_bitmap("example.png");
if (!image) {
fprintf(stderr, "Failed to load image!\n");
al_destroy_display(display);
return—1;
}
Draw shapes and the image to the screen:
al_clear_to_color(al_map_rgb(0, 0, 0)); // Clear the screen to black
// Draw a filled rectangle
al_draw_filled_rectangle(00, 00, 200, 200, al_map_rgb(255, 0, 0));
// Draw a circle
al_draw_filled_circle(400, 300, 50, al_map_rgb(0, 255, 0));
// Draw the loaded image
al_draw_bitmap(image, 300, 200, 0);
al_flip_display(); // Display the changes
al_rest(5.0); // Wait for 5 seconds
Clean up:
al_destroy_bitmap(image);
al_destroy_display(display);
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <csdtio>
int main() {
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_init_primitives_addon()) {
fprintf(stderr, "Failed to initialize primitives addon!\n");
return—1;
}
if (!al_init_image_addon()) {
fprintf(stderr, "Failed to initialize image addon!\n");
return—1;
}
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—1;
}
ALLEGRO_BITMAP *image = al_load_bitmap("example.png");
if (!image) {
fprintf(stderr, "Failed to load image!\n");
al_destroy_display(display);
return—1;
}
al_clear_to_color(al_map_rgb(0, 0, 0)); // Clear the screen to black
// Draw a filled rectangle
al_draw_filled_rectangle(00, 00, 200, 200, al_map_rgb(255, 0, 0));
// Draw a circle
al_draw_filled_circle(400, 300, 50, al_map_rgb(0, 255, 0));
// Draw the loaded image
al_draw_bitmap(image, 300, 200, 0);
al_flip_display(); // Display the changes
al_rest(5.0); // Wait for 5 seconds
al_destroy_bitmap(image);
al_destroy_display(display);
return 0;
}
This example initializes Allegro, sets up the image add-on, creates a display, loads an image, and draws both shapes and the image to the screen. It then waits for five seconds before cleaning up and closing the display.
Using a Keyboard
// Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <cstdio>
// Initialize Allegro and the necessary add-ons:
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_keyboard()) {
fprintf(stderr, "Failed to initialize the keyboard!\n");
return—1;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—1;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—1;
}
// Create a display and an event queue:
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—1;
}
ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
if (!event_queue) {
fprintf(stderr, "Failed to create event queue!\n");
al_destroy_display(display);
return—1;
}
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_keyboard_event_source());
// Load a font:
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return—1;
}
// Main loop to handle events:
bool running = true;
ALLEGRO_EVENT ev;
while (running) {
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
running = false;
} else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
switch (ev.keyboard.keycode) {
case ALLEGRO_KEY_ESCAPE:
running = false;
break;
case ALLEGRO_KEY_UP:
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Up Key Pressed");
al_flip_display();
break;
case ALLEGRO_KEY_DOWN:
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Down Key Pressed");
al_flip_display();
break;
// Add more cases for other keys as needed
}
}
}
// Clean up:
al_destroy_font(font);
al_destroy_display(display);
al_destroy_event_queue(event_queue);
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <csdtio>
int main() {
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_keyboard()) {
fprintf(stderr, "Failed to initialize the keyboard!\n");
return—1;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—1;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—1;
} ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—;
}
ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
if (!event_queue) {
fprintf(stderr, "Failed to create event queue!\n");
al_destroy_display(display);
return—1;
}
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_keyboard_event_source());
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return—1;
}
bool running = true;
ALLEGRO_EVENT ev;
while (running) {
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
running = false;
} else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
switch (ev.keyboard.keycode) {
case ALLEGRO_KEY_ESCAPE:
running = false;
break;
case ALLEGRO_KEY_UP:
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Up Key Pressed");
al_flip_display();
break;
case ALLEGRO_KEY_DOWN:
al_clear_to_color(al_map_rgb(0, 0, 0));
al_draw_text(font, al_map_rgb(255, 255, 255), 400, 300, ALLEGRO_ALIGN_CENTRE, "Down Key Pressed");
al_flip_display();
break;
// Add more cases for other keys as needed
}
}
}
al_destroy_font(font);
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return 0;
}
This example initializes Allegro, sets up the keyboard input, creates a display, and handles key-press events to display different messages based on the key pressed. It then waits for the user to close the window or press the Esc key before cleaning up and exiting.
Using a Joystick
// Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_joystick.h>
#include <cstdio>
// Initialize Allegro and the necessary add-ons:
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_joystick()) {
fprintf(stderr, "Failed to initialize the joystick!\n");
return—1;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—1;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—1;
}
//Create a display and an event queue:
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—1;
}
ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
if (!event_queue) {
fprintf(stderr, "Failed to create event queue!\n");
al_destroy_display(display);
return—1;
}
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_joystick_event_source());
// Load a font:
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_display(display);
al_destroy_event_queue(event_queue);
return—1;
}
// Main loop to handle events:
bool running = true;
ALLEGRO_EVENT ev;
while (running) {
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
running = false;
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_AXIS) {
printf("Joystick axis %d moved to %f\n", ev.joystick.axis, ev.joystick.pos);
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN) {
printf("Joystick button %d pressed\n", ev.joystick.button);
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_UP) {
printf("Joystick button %d released\n", ev.joystick.button);
}
}
// Clean up:
al_destroy_font(font);
al_destroy_display(display);
al_destroy_event_queue(event_queue);
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/joystick.h>
#include <cstdio>
int main() {
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_joystick()) {
fprintf(stderr, "Failed to initialize the joystick!\n");
return—1;
}
if (!al_init_font_addon()) {
fprintf(stderr, "Failed to initialize font addon!\n");
return—1;
}
if (!al_init_ttf_addon()) {
fprintf(stderr, "Failed to initialize TTF addon!\n");
return—1;
}
ALLEGRO_DISPLAY *display = al_create_display(800, 600);
if (!display) {
fprintf(stderr, "Failed to create display!\n");
return—1;
}
ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
if (!event_queue) {
fprintf(stderr, "Failed to create event queue!\n");
al_destroy_display(display);
return—1;
}
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_joystick_event_source());
ALLEGRO_FONT *font = al_load_ttf_font("arial.ttf", 36, 0);
if (!font) {
fprintf(stderr, "Could not load 'arial.ttf'.\n");
al_destroy_event_queue(event_queue);
al_destroy_display(display);
return—1;
}
bool running = true;
ALLEGRO_EVENT ev;
while (running) {
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
running = false;
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_AXIS) {
printf("Joystick axis %d moved to %f\n", ev.joystick.axis, ev.joystick.pos);
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN) {
printf("Joystick button %d pressed\n", ev.joystick.button);
} else if (ev.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_UP) {
printf("Joystick button %d released\n", ev.joystick.button);
}
}
// Clean up resources
al_destroy_font(font);
al_destroy_event_queue(event_queue);
al_destroy_display(display);
return 0;
}
This example initializes Allegro, sets up joystick input, creates a display, and handles joystick events such as axis movement and button presses. It then waits for the user to close the window before cleaning up and exiting.
Using Audio
// Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include <cstdio>
//Initialize Allegro and the audio add-ons:
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_audio()) {
fprintf(stderr, "Failed to initialize audio!\n");
return—1;
}
if (!al_init_acodec_addon()) {
fprintf(stderr, "Failed to initialize audio codecs!\n");
return—1;
}
if (!al_reserve_samples()) {
fprintf(stderr, "Failed to reserve samples!\n");
return—1;
}
// Load an audio sample:
ALLEGRO_SAMPLE *sample = al_load_sample("example.wav");
if (!sample) {
fprintf(stderr, "Failed to load sample!\n");
return—1;
}
// Play the audio sample:
if (!al_play_sample(sample, .0, 0.0, .0, ALLEGRO_PLAYMODE_ONCE, NULL)) {
fprintf(stderr, "Failed to play sample!\n");
al_destroy_sample(sample);
return—1;
}
// Wait for the sample to finish playing:
al_rest(5.0); // Wait for 5 seconds to ensure the sample plays completely
// Clean up:
al_destroy_sample(sample);
al_uninstall_audio();
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include <cstdio>
int main() {
if (!al_init()) {
fprintf(stderr, "Failed to initialize Allegro!\n");
return—1;
}
if (!al_install_audio()) {
fprintf(stderr, "Failed to initialize audio!\n");
return—1;
}
if (!al_init_acodec_addon()) {
fprintf(stderr, "Failed to initialize audio codecs!\n");
return—1;
}
if (!al_reserve_samples(1)) {
fprintf(stderr, "Failed to reserve samples!\n");
return—1;
}
ALLEGRO_SAMPLE *sample = al_load_sample("example.wav");
if (!sample) {
fprintf(stderr, "Failed to load sample!\n");
return—1;
}
if (!al_play_sample(sample, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL)) {
fprintf(stderr, "Failed to play sample!\n");
al_destroy_sample(sample);
return—1;
}
al_rest(5.0); // Wait for 5 seconds so the sound can play
al_destroy_sample(sample);
al_uninstall_audio();
return 0;
}
This example initializes Allegro, sets up the audio add-ons, loads an audio sample, plays it, and then waits for five seconds to ensure the sample plays completely before cleaning up and exiting.
Using Files
// Include the necessary headers:
#include <allegro5/allegro.h>
#include <allegro5/allegro_native_dialog.h>
#include <cstring>
#include <cstdio>
// Initialize Allegro:
if (!al_init()) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to initialize Allegro!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
// Open a file for writing:
ALLEGRO_FILE *file = al_fopen("example.txt", "w");
if (!file) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to open file for writing!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
// Write to the file:
const char *text = "Hello, Allegro File I/O!";
al_fwrite(file, text, strlen(text));
// Close the file:
al_fclose(file);
// Open the file for reading:
file = al_fopen("example.txt", "r");
if (!file) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to open file for reading!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
// Read from the file:
char buffer;
al_fread(file, buffer, sizeof(buffer)—1);
buffer[sizeof(buffer)—1 ] = '\0'; // Ensure null-termination
printf("Read from file—%s\n", buffer);
// Close the file:
al_fclose(file);
Here’s the complete code put together:
#include <allegro5/allegro.h>
#include <allegro5/allegro_native_dialog.h>
#include <cstring>
#include <cstdio>
int main() {
if (!al_init()) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to initialize Allegro!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
// Initialize native dialog addon
al_init_native_dialog_addon();
ALLEGRO_FILE *file = al_fopen("example.txt", "w");
if (!file) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to open file for writing!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
const char *text = "Hello, Allegro File I/O!";
al_fwrite(file, text, strlen(text));
al_fclose(file);
file = al_fopen("example.txt", "r");
if (!file) {
al_show_native_message_box(NULL, "Error", "Error", "Failed to open file for reading!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
return—1;
}
// Read up to 255 bytes and null-terminate
char buffer[256] = {0}; // initialize to zero
size_t bytesRead = al_fread(file, buffer, sizeof(buffer)—1);
buffer[bytesRead] = '\0'; // ensure null termination
printf("Read from file—%s\n", buffer);
al_fclose(file);
return 0;
}
This example initializes Allegro, opens a file for writing, writes a string to the file, closes it, then reopens the file for reading, reads the content, and prints it to the console. It also includes error handling to display messages if any operation fails.
Exercises, Homework Questions, and Projects
Some projects in this section of each chapter, including those using axis-aligned bounding boxes (AABB), extend slightly beyond the textbook’s core coverage. They are included to introduce widely used techniques in practical game development and to provide learners with opportunities for further exploration.
Beginner Projects (Setup and Basics)
- 1. IDE Setup Assignment
Set up Allegro 5 with Visual Studio Code, CMake, and Ninja on your operating system (Windows/Linux/macOS). Submit screenshots of a successful “Hello, Allegro!” program.
- 2. First Game Window
Create a windowed application using Allegro 5 that displays a coloured background and closes when the user presses the Esc key.
- 3. Event Handling
Write a program that prints keyboard input (e.g., “A pressed”) to the console and exits when the window is closed.
- 4. Simple Animation
Draw a bouncing ball using Allegro primitives (circle) that moves horizontally across the screen and reverses direction at the edges.
Intermediate Projects (Game Mechanics)
- 5. Pong Clone
Implement a two-player Pong game with paddles, a moving ball, and score tracking. Use keyboard input for controls.
- 6. Memory-Matching Game
Create a grid of cards (rectangles) that flip on click. Players must match pairs. Track time and moves.
- 7. Platformer Movement
Design a player sprite that can jump, move left/right, and collide with platforms (rectangles). Use gravity for realistic jumps.
- 8. Tile-Based Map
Load a CSV file representing a tile map (e.g., 0 = grass, 1 = water) and render it using Allegro bitmaps.
- 9. Collision Detection
Implement axis-aligned bounding box (AABB) collision detection between a player sprite and obstacles. Display collision feedback (e.g., colour change).
- 10. Simple RPG Inventory
Create an inventory system where players can collect items (displayed as icons) and toggle visibility with the I key.
- 11. Alarm Clock with Graphical User Interface (GUI)
Build a digital clock with start/stop/reset buttons. Use Allegro’s timer and font modules to display time.
Advanced Projects (Complex Systems)
- 12. Top-Down Shooter
Develop a game where a player-controlled spaceship shoots projectiles at enemies. Include health bars and sound effects.
- 13. Procedural Level Generation
Generate random platformer levels using algorithms (e.g., Perlin noise) and render them with Allegro.
- 14. Pathfinding AI
Implement A* pathfinding for an NPC to navigate a grid-based maze. Visualize the path with coloured tiles.
- 15. Particle System
Create a fire or explosion effect using particles with varying velocity, size, and transparency.
- 16. Multiplayer Quiz Game
Use networking (optional: local sockets) to let two players answer trivia questions. Track scores in real time.
- 17. Save/Load System
Save player progress (e.g., position, inventory) to a file and reload it on start-up. Use Allegro’s file I/O functions.
- 18. Dynamic UI
Design a main menu with clickable buttons (e.g., Play, Settings, Exit). Add hover effects and transitions.
- 19. Music Sequencer
Build a drum machine with interactive buttons that trigger sound samples. Include a tempo slider.
Theoretical and Research Assignments
- 20. Game Design Document
Write a GDD for an original game, detailing mechanics, story, target audience, and technical requirements.
- 21. History of Allegro
Research and present the evolution of the Allegro library. Compare versions 4 and 5.
- 22. Optimization Report
Profile a slow Allegro project (e.g., particle system) and propose fixes (e.g., batch rendering, memory pooling).
- 23. AI Behavior Analysis
Compare finite state machines and behavior trees. Implement an NPC patrol/attack system using one method.
- 24. Cross-Platform Challenges
Discuss the difficulties of porting Allegro 5 games between Windows, Linux, and macOS. Test a sample project on two OS.
Creative Challenges
- 25. Interactive Art Tool
Build a pixel-art editor with tools (e.g., brush, colour picker) and save/load functionality.
- 26. Procedural Music Visualizer
Analyze audio input (e.g., microphone) and generate real-time visual effects (e.g., bars, particles) synchronized to the beat.
- 27. Physics-Based Puzzle Game
Create a game where players stack objects to reach a goal. Use Allegro’s physics primitives or implement basic rigid body dynamics.
- 28. Roguelike Prototype
Design a procedurally generated dungeon crawler with permadeath, loot, and enemy AI. Use turn-based movement.
- 29. 3D Rendering Experiment
Use Allegro’s OpenGL integration to render a rotating 3D cube. Add texture mapping and lighting.
- 30. Final Project: Complete Game
Develop a polished game (e.g., platformer, puzzle, RPG) with menus, sound, scoring, and at least three levels. Present a demo and submit source code.