Ramya Shankar | 08 Sep, 2023

How to Code a Game: Building a Game From Scratch

Let's talk about how to code a game. Crazy about online games? Have a great idea about a game, but do not know where to start? Fed up of existing games and want to build your own, but don’t know where to start?

After all, I have those types of thoughts all the time! Every time I play a video game, I wonder – what if…!

That's why I put together this guide on how to code a game. I did the research, found out how to make it happen, and compiled everything in one place. This article is the result of that research, and believe me, you can do it, even if you don't consider yourself a programmer.

How to Code a Game: The Main Idea

You already have an idea in your head. You could start by taking an overview course (we recommend Will Wright Teaches Game Design and Theory at MasterClass or any of the specific game design courses at Udemy), or you could dive in head first! Start by writing everything out. It can be gibberish notes or neatly done paragraphs and diagrams. Anything that helps you get the information onto paper. Once you start putting notes, more ideas would form in your head and voila – you get your first draft design!

Here are a few things you can write:

  • What is the objective of the game?
  • Why is your game idea great/unique?
  • Is it one or a multiplayer game? What do(es) the player(s) do?
  • What is the main story? What emotions does it have?
  • What sound effects/graphics/visuals are to be included? It could be based on the genre of the game or a mix and match!
  • What type of audience are you targeting – mobile users, desktop users, or both?

Even if you don’t have any of the above, worry not! We would help you get all the creative and full of ideas! For starters, join or follow a game jam or hackathon where participants build a game in a limited time. There would be loads of other jammers helping you out during the entire time. Global Game Jam and Ludum Dare are some popular jams.

It might also be useful to think of what kind of games you or your friends like to play, or while playing if you ever thought of tweaking something to make it better. Make a list of popular games and genres. A little out-of-the-box thinking works!

Game Engine

Ok, now that we have got the idea, expanded it, and have a good draft, we need to choose a game engine!

For classic 2D games, you can do away with the graphics of IDE, however for more complex and interactive games; you would need a proper engine that takes care of filtering and managing resources to improve overall performance. Look at this simple desktop game similar to DxBall, built using Eclipse IDE (Java). There are other IDE’s like Visual Studio, CodeBlocks, and PyCharm too.

What is a game engine?

The game engine is an environment where you can add different features like collision management, animations, artificial intelligence, and much more without the need for coding any of them. These components can be reused by the developers to build their game framework. Game engines provide a lot of APIs where you can have graphic objects, sound effects, physics objects, and more into one single game object, rather than having a separate package for each component.

Whether you are a programmer or not, using a game engine is going to save you a lot of time and effort. Doing everything from scratch is tempting but can consume much time. Unity is one of the most popular game engines used by many developers. Some other popular game engines are Godot, GameMaker, and Unreal.

If you are still not convinced about using a game engine and have some prior programming knowledge, well, we would not stop you from building your game engine. You can use Java, Python, or C++ to build your game engine. Caution – you would have to do a lot of studying and bear with days when nothing would work! It is also tough to build something better than the already existing complex game engines. However, all of it is worth it if you love algorithms, linear algebra, Design patterns, OpenGL, and more, want something to own, and can wait to put things together for work.

Now that the game engine is ready, we need to start our game design.

A little bit of programming knowledge

This is a simple but essential step. Think about how you want your game to be – 2D/3D? Is it a puzzle, a quest, a board game? You would have figured out most of these things previously, but in this step, you can add more details to your design and keep adding more stuff as you get more ideas and clarity – the earlier, the better!

If you are a programmer, you would know what an IDE is. Certainly, using an IDE would help you get rid of a lot of otherwise hard work! For example, Java has Eclipse IDE, which helps you create a game project and get started on coding.

(Skip the below section if you already know which language you are going to code.)

If you are not a programmer – there is nothing to worry about – it is easy to learn to code – there are plenty of tutorials (which is rather confusing), and that’s why we have selected the right ones for you. Here are some blogs to get you started on coding –

In a nutshell, every programming language would have the following –

1. Variables and Datatypes – Data, as always, is the king. To store data, we need a placeholder – that is a variable. To store different types of data, we need different types of placeholders – those are data types. Here are a few examples.

This one is in Java:

String name = “hackr”;

and this one is in C#:

int sum = 0;

int refers to an integer data type. Currently, the value assigned to this variable ‘sum’ is 0. It can be changed later based on some inputs and results. Same way, String is a data type used to store letters and text. As we see, the value of the variable ‘name’ is hackr.

2. Conditions – Nothing is free in this world. Everything has a condition attached. For example, if you want to drink milk you have to pay money and buy the packet, else you don’t get the packet; if you want to be healthy, you should exercise, else you have to face the consequences. The same conditions work for code as well. If/else is similar to the conditions in a flowchart, the flow will go based on whether it meets the condition. Here is a simple example in JavaScript:

if (marks < 35) {
    setGrade("F");
} else if (marks < 55) {
    setGrade("D");
} else if (marks < 75) {
    setGrade("B");
} else {
    setGrade("A");
}

As we see, in this example, specific grades are assigned based on whether if the condition is true or not, where ‘marks’ is a variable whose value can be either obtained from the user or a backend system. Also, ‘set grade’ is a method that stores the value of the ‘grade’ (another variable). Storing variable values in methods make the object accessible anywhere throughout the application.

3. Loops – Loops are important to check for some conditions, and until the condition is true, the application would continue doing ‘something.’ For example, in a game, if you have three lives left, you can continue playing, so a loop can be written as simple:

while(life counter >0)
//let the player play

In the same way, if a player has boost ups in the game, till all of them are exhausted, the player can continue to have special powers.

for(int i=0; i< maxboostup;i++)
//keep the special powers

In the above code, ‘i’ is a counter that compares the number of boost ups starting from 0. Upon each execution, i++ would increase the counter value after the execution of the loop. So, when the value of "i" reaches maxboostup, the loop won’t be executed anymore.

4. Data structures – We have variables and data types to store individual data. But, how about loads of data that needs to be tracked. For example, sign-in information of a user points collected by him in the last game and the entire game data. This complex set of data needs to be structured and put in a proper way to be retrieved later. We use data structures like queues, lists, maps, sets, and more for easy manipulation and retrieval.

You can also follow structured data science courses at DataCamp. They offer project-based modules and certifications for data professionals.

5. API – Once you choose a game engine, you need to familiarize yourself with its API. API would make your tasks simpler. There are plenty of example projects that come as part of a game engine which you should see and understand before you start building your project.

6. Object orientation, language-specific naming conventions and design patterns.

As much as you might be scared of seeing this big paragraph on coding, believe us, it is simple, and once you start coding and things start working – you would have the best moments of your life!

Next thing – the creative part!

The Art and The Design

If you are not the creative and artistic types, well, you would certainly want to become one after seeing how magical the already existing visual tools are. A useful UI is the first thing that attracts a player, and it has to be unique in color, pattern, shape, and font. Most games need at least some graphics.

There are some snapshots from the Unreal engine where you can select different shapes, materials, patterns, and much more. Unreal comes with a gun and is excellent for shooting games.

You can add everything like a movement, artificial intelligence, navigation, collision, and more using various options present in the UI.

The best option for creating amazing UI and 2D assets for your game is Adobe Photoshop. The sketch is another option you can use for UI. You can create beautiful frames, designs, and structures very quickly and can instantly see how changing the values of different properties changes the designs.

For 3D modeling and assets, you can use Blender. A few drag and drops, and you can see some fantastic creations where your game character can do movement animations like running, turning, and action animations like attacking, waving, shooting at the same time. It is easy to learn Blender, and you would love playing around with it.

So, we got the engine, the visuals, and the code well what a game is without its sound effects?

Audio

Appropriate music and sound effects would set the mood for gamers to play the game and be engrossed. Though adding audio adds up memory too, it is up to you to decide – depending on the type of your game. For example, for puzzles or farm games, you may not need great sound effects, whereas quests, shooting games, and more may need good sound effects. Some of the best audio content can be found from Indie Game Music, Audacity, Unity’s Asset Store, and Freesound.

Tada!

You are done, or are you?

Testing

Your game, as you would expect, may or may not work correctly in the first run. You may have to do a little or many changes to make things work. But before you get onto publishing mode, your game has to be thoroughly tested – not just by you – but by your friends or acquaintances – who may find some bugs knowingly or unknowingly! Try to break your game and find out how users may try to do it. Get it on as many platforms as possible – Linux, Android – each version may give you something unexpected!

Exceptions and errors are common and fixable unless you are exhausted and sleepy. Put as many log statements and check the full stack trace to find the root cause. However, do not handle too many exceptions in your production code else your game performance could be impacted. Rather, look for ones that are most likely to occur and include those during your testing phase. Some common exceptions could be NullPointerException or NullReferenceException, where you are trying to act on a ‘null’ value or a value that doesn’t exist. For example,

String name;
if(name.length > 5) //This line will throw NullPointerException because we are trying to do a ‘.’ (dot) operation on a null object.

To avoid this type of exception, adding a check would be enough –

if (name != null) // now the next line of code will execute only if this condition is true.

Sometimes, there are differences in the way symbols are displayed in different editors. The most common is the double quotes (“). You might have seen this problem if you have a piece of code on a word document and try to copy-paste it to an IDE. IDE would accept only dumb quotes, thus resulting in a syntax error. These errors can be caught during compile time.

It is also possible that you are not typecasting the Graphic classes properly; for example, you are using Graphic2D and Graphic object interchangeably without adding a cast. It could result in rendering issues.

Performance and memory testing

Same way, you should perform load and memory testing. If there are any leaks or performance issues, perform some optimization for different platforms – desktop, mobile, and more. Having a game engine would help with this, as they have some measures to optimize memory and performance issues. Here are some tips to follow for code optimization.

After this, you are all set up to roll your game to the real audience. You can advertise on various platforms, the most popular nowadays being social media, YouTube, Instagram, and google ranking. You can also get influential people to write something about the game before you release it. Find your contacts and references, spread the message! Get an email address or contact number of tech magazines that would be interested in writing about your genre and game. Marketing your game is as important as building it. You would learn a lot if you do the marketing yourself. Some popular game press names that you can approach are IndieGames, Siliconera, EuroGamer, FreeGamesPlanet, and more.

Programming Design Patterns For Unity - Write Better Code

How to Build a Game: Full Example

Alright, we've talked about how to build a game. You're ready to see a full example. Just remember, game design is a vast field. You may choose to program your game in a number of languages and use all sorts of different features. We wanted to create a very simple game, so we went with a number guessing game in Python. It's actually a pretty popular Python project, too.

Here's the Python code for our number guessing game.

import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Initialize the number of attempts
attempts = 0

# Maximum number of attempts allowed
max_attempts = 5

print("Welcome to the Number Guessing Game!")
print(f"Ready to play? Guess my number (between 1 and 100). You have {max_attempts} attempts.")

while attempts < max_attempts:
    try:
        # Get the player's guess
        guess = int(input("What's your guess? "))
        
        # Check if the guess is within the valid range
        if guess < 1 or guess > 100:
            print("Please enter a number between 1 and 100.")
            continue
        
        # Increment the number of attempts
        attempts += 1
        
        # Check if the guess is correct
        if guess == secret_number:
            print(f"That's it! You guessed my number, {secret_number}, in {attempts} attempts.")
            break
        elif guess < secret_number:
            print("Guess higher!")
        else:
            print("Guess lower!")
        
        # Check if the player has used all attempts
        if attempts == max_attempts:
            print(f"That's all, folks! You've used all your attempts. The correct number was {secret_number}.")
    except ValueError:
        print("Invalid input. Please enter a valid number.")

print("Game over. Thanks for playing the simple number guessing game at Hackr.io!")

Conclusion

Game development needs a lot of patience and hard work. There are new things to learn every day, new challenges to accept, and new excitements. You should be able to embrace happiness and disappointment alike. Whether your game gets the due marketing and recognition or not from the public, it is still a great achievement because building a game is not easy – it is an overwhelming process meant to test your limits.

Be firm, be patient, and you would rock! Start your journey and learn game design right now!

People are also reading:

By Ramya Shankar

A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

Thanks for subscribing! Look out for our welcome email to verify your email and get our free newsletters.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments

Jenna Sakka

im learning how

3 years ago