Gordon  Matlala

Gordon Matlala

1669983720

How Implement The Konami Keystroke Cheat Code in A Unity Game

Remember all the cheat codes you could use in old-school games back in the day? Remember the Konami cheat code? Ever wonder how you could add cheat codes to your own games?

Adding cheat codes to your game is a great way to leave your imprint. Think easter eggs, but even more secretive.

In this tutorial we’re going to see how to add keystroke driven cheat codes to a game built with Unity and C#. While the Konami cheat code will be the basis of this example, a lot of the logic and ideas can be applied to other aspects of your game.

To get an idea of what we want to accomplish, take a look at the following animated image:

Konami Cheat Code in Unity Game

In the above image, each keystroke is added to the history of keystrokes and displayed on the screen. If we happen to press the key combination “up, up, down, down, left, right, left, right, b, a” the Konami cheat code will be triggered. In our example it doesn’t do anything other than display on the screen, but you could do something like increasing the score, giving more lives, or something else.

There are a few ways to accomplish this task in Unity, but I’m going to demonstrate two different ways as well as their advantages or disadvantages.

Capturing Keystroke Information in Unity with the OnGUI Method

We’re first going to take a look at the OnGUI method that is baked into Unity. If you’ve never seen it, the method would look something like this:

void OnGUI() {
    Event e = Event.current;
    if(e.isKey && e.type == EventType.KeyUp) {
        Debug.Log(e.keyCode.ToString());
    }
}

You can add the above method to any script that extends MonoBehaviour and in the above example the keycode will be printed assuming that it is a KeyUp event and that it is a key and not a mouse click or something else.

While it is super convenient to be able to determine which key was pressed in only a few lines of code using the OnGUI method, it’s not without potential problems. The largest of the problems being that the OnGUI method could be executed up to two times per frame. This is not good for us because it means that numerous events could be registered even if we only intended on one.

To be clear, there are scenarios where if you push the “UpArrow” key, it could get registered as you pushing it twice. In the example of cheat codes where the key combination is important, having this variable amount of keystrokes per frame won’t work.

Using a Simple Loop to Capture Keystroke Information in Unity

Let’s take a look at another way to capture specifically which keys were pressed by the user. In this alternative, we’ll be making use of the Update method and some loops.

Let’s look at the function we can use for detecting which key was pressed:

private KeyCode DetectKeyPressed() {
    foreach(KeyCode key in Enum.GetValues(typeof(KeyCode))) {
        if(Input.GetKeyDown(key)) {
            return key;
        }
    }
    return KeyCode.None;
}

When executed, the DetectKeyPressed function will loop through all of the potential key codes to see if you’re pressing one of them. If you are, return the keycode for the next step in our pipeline.

So the problem with this is that you have to loop through all the potential keycodes every frame. There aren’t too many of them to stress out modern computers and devices, but it could become a bottleneck in your game if you’re not careful.

With the information and the DetectKeyPressed function in mind, we can use it in our Update method like this:

void Update() {
    KeyCode keyPressed = DetectKeyPressed();
    Debug.Log(keyPressed);
}

From a code length and readability perspective, this way of detecting user input isn’t too different from the OnGUI way. You just have to evaluate which of the tradeoffs and benefits work the best for your use-case.

Building a Game Scene with the Konami Cheat Code Implemented

Now that we have a way to capture keystrokes from the user, we can use that information to implement cheat codes in our game.

I won’t be going into a deep-dive on how to develop with Unity, so make sure you have the following in your scene for this example to be successful:

  • Camera
  • Canvas
    • KeyStrokeText
    • CheatCodeText
  • Controller

We’ll use game objects with the Text component to show our keystroke history or the cheat code that was entered into the game. The Controller game object will be empty with the exception that it contains a script attached to it.

Example Unity Scene for Konami Cheat Code

So now that we have our basic game objects with various components attached to them in our scene, let’s create a script that will be our controller for the scene. Create a new C# script named Controller.cs with the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;

public class Controller : MonoBehaviour {

    public Text keyStrokeText;
    public Text cheatCodeText;

    private List<string> _keyStrokeHistory;

    void Awake() {
        _keyStrokeHistory = new List<string>();
    }

    void Update() {
        KeyCode keyPressed = DetectKeyPressed();
        AddKeyStrokeToHistory(keyPressed.ToString());
        keyStrokeText.text = "HISTORY: " + GetKeyStrokeHistory();
        if(GetKeyStrokeHistory().Equals("UpArrow,UpArrow,DownArrow,DownArrow,LeftArrow,RightArrow,LeftArrow,RightArrow,B,A")) {
            cheatCodeText.text = "KONAMI CHEAT CODE DETECTED!";
            ClearKeyStrokeHistory();
        }
    }

    private KeyCode DetectKeyPressed() {
        foreach(KeyCode key in Enum.GetValues(typeof(KeyCode))) {
            if(Input.GetKeyDown(key)) {
                return key;
            }
        }
        return KeyCode.None;
    }

    private void AddKeyStrokeToHistory(string keyStroke) {
        if(!keyStroke.Equals("None")) {
            _keyStrokeHistory.Add(keyStroke);
            if(_keyStrokeHistory.Count > 10) {
                _keyStrokeHistory.RemoveAt(0);
            }
        }
    }

    private string GetKeyStrokeHistory() {
        return String.Join(",", _keyStrokeHistory.ToArray());
    }

    private void ClearKeyStrokeHistory() {
        _keyStrokeHistory.Clear();
    }

}

In the above example I am choosing to not use the OnGUI approach as I didn’t get the results I was looking for.

So let’s break down what’s happening, starting with the Awake method:

void Awake() {
    _keyStrokeHistory = new List<string>();
}

For most cheat codes to be successful, we need to be able to track any number of keystrokes made. For this example, we’re going to store every keystroke in a List variable. The reality is that we aren’t going to store every keystroke, but we could if we wanted to.

We’ve already seen the DetectKeyPressed method, but we haven’t seen how to add the keystrokes to our history. This is where the AddKeyStrokeToHistory method comes in:

private void AddKeyStrokeToHistory(string keyStroke) {
    if(!keyStroke.Equals("None")) {
        _keyStrokeHistory.Add(keyStroke);
        if(_keyStrokeHistory.Count > 10) {
            _keyStrokeHistory.RemoveAt(0);
        }
    }
}

When we attempt to add to the history we check to make sure it isn’t the None keystroke which pops up occasionally. If it’s not, we push the keystroke into the list and then check to see our list size. If our size exceeds our magic number, then we start removing history from the front of the list which represents the oldest keystrokes.

We’re going to need to be able to check what our keystroke history looks like, so we can do that with the GetKeyStrokeHistory method:

private string GetKeyStrokeHistory() {
    return String.Join(",", _keyStrokeHistory.ToArray());
}

Rather than doing something complicated, I just convert the list into a string delimited by the comma character. This dumps the entire list, but your logic might be different if your cheat codes have various combination sizes. In your circumstance you might want to return the first few keystrokes or the last few keystrokes.

If you look back at the Update method we can compare the keystroke history with a cheat code and if it matches, we can do something magical!

Conclusion

You just saw two of many possible ways to implement cheat codes into your Unity game. While the premise of this example was cheat codes, the keystroke capturing logic can be applied to different scenarios as well.

To keep your cheat code logic isolated from player logic, enemy logic, or something else, I find it best to keep the logic in the controller for your scene. You don’t have to do it this way, but I personally find it to keep things clean and organized.

You can find a video version of this tutorial below:

Original article source at: https://www.thepolyglotdeveloper.com/

#cheating #unity #game 

What is GEEK

Buddha Community

How Implement The Konami Keystroke Cheat Code in A Unity Game
Gordon  Matlala

Gordon Matlala

1669983720

How Implement The Konami Keystroke Cheat Code in A Unity Game

Remember all the cheat codes you could use in old-school games back in the day? Remember the Konami cheat code? Ever wonder how you could add cheat codes to your own games?

Adding cheat codes to your game is a great way to leave your imprint. Think easter eggs, but even more secretive.

In this tutorial we’re going to see how to add keystroke driven cheat codes to a game built with Unity and C#. While the Konami cheat code will be the basis of this example, a lot of the logic and ideas can be applied to other aspects of your game.

To get an idea of what we want to accomplish, take a look at the following animated image:

Konami Cheat Code in Unity Game

In the above image, each keystroke is added to the history of keystrokes and displayed on the screen. If we happen to press the key combination “up, up, down, down, left, right, left, right, b, a” the Konami cheat code will be triggered. In our example it doesn’t do anything other than display on the screen, but you could do something like increasing the score, giving more lives, or something else.

There are a few ways to accomplish this task in Unity, but I’m going to demonstrate two different ways as well as their advantages or disadvantages.

Capturing Keystroke Information in Unity with the OnGUI Method

We’re first going to take a look at the OnGUI method that is baked into Unity. If you’ve never seen it, the method would look something like this:

void OnGUI() {
    Event e = Event.current;
    if(e.isKey && e.type == EventType.KeyUp) {
        Debug.Log(e.keyCode.ToString());
    }
}

You can add the above method to any script that extends MonoBehaviour and in the above example the keycode will be printed assuming that it is a KeyUp event and that it is a key and not a mouse click or something else.

While it is super convenient to be able to determine which key was pressed in only a few lines of code using the OnGUI method, it’s not without potential problems. The largest of the problems being that the OnGUI method could be executed up to two times per frame. This is not good for us because it means that numerous events could be registered even if we only intended on one.

To be clear, there are scenarios where if you push the “UpArrow” key, it could get registered as you pushing it twice. In the example of cheat codes where the key combination is important, having this variable amount of keystrokes per frame won’t work.

Using a Simple Loop to Capture Keystroke Information in Unity

Let’s take a look at another way to capture specifically which keys were pressed by the user. In this alternative, we’ll be making use of the Update method and some loops.

Let’s look at the function we can use for detecting which key was pressed:

private KeyCode DetectKeyPressed() {
    foreach(KeyCode key in Enum.GetValues(typeof(KeyCode))) {
        if(Input.GetKeyDown(key)) {
            return key;
        }
    }
    return KeyCode.None;
}

When executed, the DetectKeyPressed function will loop through all of the potential key codes to see if you’re pressing one of them. If you are, return the keycode for the next step in our pipeline.

So the problem with this is that you have to loop through all the potential keycodes every frame. There aren’t too many of them to stress out modern computers and devices, but it could become a bottleneck in your game if you’re not careful.

With the information and the DetectKeyPressed function in mind, we can use it in our Update method like this:

void Update() {
    KeyCode keyPressed = DetectKeyPressed();
    Debug.Log(keyPressed);
}

From a code length and readability perspective, this way of detecting user input isn’t too different from the OnGUI way. You just have to evaluate which of the tradeoffs and benefits work the best for your use-case.

Building a Game Scene with the Konami Cheat Code Implemented

Now that we have a way to capture keystrokes from the user, we can use that information to implement cheat codes in our game.

I won’t be going into a deep-dive on how to develop with Unity, so make sure you have the following in your scene for this example to be successful:

  • Camera
  • Canvas
    • KeyStrokeText
    • CheatCodeText
  • Controller

We’ll use game objects with the Text component to show our keystroke history or the cheat code that was entered into the game. The Controller game object will be empty with the exception that it contains a script attached to it.

Example Unity Scene for Konami Cheat Code

So now that we have our basic game objects with various components attached to them in our scene, let’s create a script that will be our controller for the scene. Create a new C# script named Controller.cs with the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;

public class Controller : MonoBehaviour {

    public Text keyStrokeText;
    public Text cheatCodeText;

    private List<string> _keyStrokeHistory;

    void Awake() {
        _keyStrokeHistory = new List<string>();
    }

    void Update() {
        KeyCode keyPressed = DetectKeyPressed();
        AddKeyStrokeToHistory(keyPressed.ToString());
        keyStrokeText.text = "HISTORY: " + GetKeyStrokeHistory();
        if(GetKeyStrokeHistory().Equals("UpArrow,UpArrow,DownArrow,DownArrow,LeftArrow,RightArrow,LeftArrow,RightArrow,B,A")) {
            cheatCodeText.text = "KONAMI CHEAT CODE DETECTED!";
            ClearKeyStrokeHistory();
        }
    }

    private KeyCode DetectKeyPressed() {
        foreach(KeyCode key in Enum.GetValues(typeof(KeyCode))) {
            if(Input.GetKeyDown(key)) {
                return key;
            }
        }
        return KeyCode.None;
    }

    private void AddKeyStrokeToHistory(string keyStroke) {
        if(!keyStroke.Equals("None")) {
            _keyStrokeHistory.Add(keyStroke);
            if(_keyStrokeHistory.Count > 10) {
                _keyStrokeHistory.RemoveAt(0);
            }
        }
    }

    private string GetKeyStrokeHistory() {
        return String.Join(",", _keyStrokeHistory.ToArray());
    }

    private void ClearKeyStrokeHistory() {
        _keyStrokeHistory.Clear();
    }

}

In the above example I am choosing to not use the OnGUI approach as I didn’t get the results I was looking for.

So let’s break down what’s happening, starting with the Awake method:

void Awake() {
    _keyStrokeHistory = new List<string>();
}

For most cheat codes to be successful, we need to be able to track any number of keystrokes made. For this example, we’re going to store every keystroke in a List variable. The reality is that we aren’t going to store every keystroke, but we could if we wanted to.

We’ve already seen the DetectKeyPressed method, but we haven’t seen how to add the keystrokes to our history. This is where the AddKeyStrokeToHistory method comes in:

private void AddKeyStrokeToHistory(string keyStroke) {
    if(!keyStroke.Equals("None")) {
        _keyStrokeHistory.Add(keyStroke);
        if(_keyStrokeHistory.Count > 10) {
            _keyStrokeHistory.RemoveAt(0);
        }
    }
}

When we attempt to add to the history we check to make sure it isn’t the None keystroke which pops up occasionally. If it’s not, we push the keystroke into the list and then check to see our list size. If our size exceeds our magic number, then we start removing history from the front of the list which represents the oldest keystrokes.

We’re going to need to be able to check what our keystroke history looks like, so we can do that with the GetKeyStrokeHistory method:

private string GetKeyStrokeHistory() {
    return String.Join(",", _keyStrokeHistory.ToArray());
}

Rather than doing something complicated, I just convert the list into a string delimited by the comma character. This dumps the entire list, but your logic might be different if your cheat codes have various combination sizes. In your circumstance you might want to return the first few keystrokes or the last few keystrokes.

If you look back at the Update method we can compare the keystroke history with a cheat code and if it matches, we can do something magical!

Conclusion

You just saw two of many possible ways to implement cheat codes into your Unity game. While the premise of this example was cheat codes, the keystroke capturing logic can be applied to different scenarios as well.

To keep your cheat code logic isolated from player logic, enemy logic, or something else, I find it best to keep the logic in the controller for your scene. You don’t have to do it this way, but I personally find it to keep things clean and organized.

You can find a video version of this tutorial below:

Original article source at: https://www.thepolyglotdeveloper.com/

#cheating #unity #game 

Autumn  Blick

Autumn Blick

1602565700

Game Development with .NET

We’ve launched a new Game Development with .NET section on our site. It’s designed for current .NET developers to explore all the choices available to them when developing games. It’s also designed for new developers trying to learn how to use .NET by making games. We’ve also launched a new game development Learn portal for .NET filled with tutorials, videos, and documentation provided by Microsoft and others in the .NET game development community. Finally, we launched a step-by-step Unity get-started tutorial that will get you started with Unity and writing C## scripts for it in no time. We are excited to show you what .NET has to offer to you when making games. .NET is also part of Microsoft Game Stack, a comprehensive suite of tools and services just for game development.

A picture of a game controller

.NET for game developers

.NET is cross-platform. With .NET you can target over 25+ different platforms with a single code base. You can make games for, but not limited to, Windows, macOS, Linux, Android, iOS, Xbox, PlayStation, Nintendo, and mixed reality devices.

C## is the most popular programming language in game development. The wider .NET community is also big. There is no lack of expertise and support you can find from individuals and user groups, locally or online.

.NET does not just cover building your game. You can also use it to build your game’s website with ASP.NET, your mobile app using Xamarin, and even do remote rendering with Microsoft Azure. Your skills will transfer across the entire game development pipeline.

logos of some gaming platforms supported by .NET

Available game engines

The first step to developing games in .NET is to choose a game engine. You can think of engines as the frameworks and tools you use for developing your game. There are many game engines that use .NET and they differ widely. Some of the engines are commercial and some are completely royalty free and open source. I am excited to see some of them planning to adopt .NET 5 soon. Just choose the engine that better works for you and your game. Would you like to read a blog post to help you learn about .NET game engines, and which one would be best for you?

#.net #.net core #azure #c# #game development #azure #cryengine #game developers #game development #game development with .net #game engines #games #monogame #playfab #stride #unity #visual studio #waveengine

lakshya world

lakshya world

1664775764

How to Create a Successful Gaming App?

How to create a game app is a comprehensive guide, explaining the entire process of creating and publishing games for iOS and Android. Covering all the essential information a budding game developer needs to know.

 

Read More - https://www.brsoftech.com/blog/how-to-create-a-game-app/

 

#game-engine  #game-development  #game  #games  #gaming 

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

The  NineHertz

The NineHertz

1613126944

Unity Game Development Company | Hire Unity Developers

Hire Unity developers who are highly experienced to develop fantastic games and impress the user with their outstanding graphics. With the great and innovative imagination, we create rich gaming applications for all types of categories. From 2D to 3D games, our team has numerous game developers who provide error-free and unbeatable game applications for our clients.

#unity game development #unity mobile app development #unity development services #unity game development company