what would be the best way to implement kind of cheat codes in general? I have WinForms application in mind, where a cheat code would unlock an easter egg, but the implementation details are not relevant.
The best approach that comes to my mind is to keep index for each code - let's consider famous DOOM codes - IDDQD and IDKFA, in a fictional C# app.
string[] CheatCodes = { "IDDQD", "IDKFA"};
int[] CheatIndexes = { 0, 0 };
const int CHEAT_COUNT = 2;
void KeyPress(char c)
{
for (int i = 0; i < CHEAT_COUNT; i++) //for each cheat code
{
if (CheatCodes[i][CheatIndexes[i]] == c)
{ //we have hit the next key in sequence
if (++CheatIndexes[i] == CheatCodes[i].Length) //are we in the end?
{
//Do cheat work
MessageBox.Show(CheatCodes[i]);
//reset cheat index so we can enter it next time
CheatIndexes[i] = 0;
}
}
else //mistyped, reset cheat index
CheatIndexes[i] = 0;
}
}
Is this the right way to do it?
Edit: Probably the worst thing I should have done was to include the first cheat codes that came from the top of my head as an example. I really did not want to see Doom's source code or their implementation, but general solution to this problem.
Sometimes, cheat codes are purposefully included in games by the first-party developers who created them. Other times, they're inserted through third-party software after a game's been produced. Moreover, it isn't always intentional. Gamers have discovered unintended “codes” by exploiting bugs in a game's software.
Cheat codes are usually activated by typing secret passwords or pressing controller buttons in a certain sequence. Less common activation methods include entering certain high score names, holding keys or buttons while dying, picking up items in a particular order and otherwise performing unintuitive actions.
Sometimes that can be the case, but most cheat codes are created by video game developers and placed into games on purpose.
Cheat codes were often used on old-school games to get ahead, but some modern games also support cheats. Cheat codes have largely gone away in the modern gaming landscape. With the advent of online multiplayer, achievements, and trophies, getting an advantage by putting in a code seems unfair.
Why not download the DOOM source and see for yourself? =) http://www.doomworld.com/idgames/?id=14576
I think this one's a bit easier to understand, though your original will probably perform better than this one:
using System.Collections.Generic;
void KeyPress(char c)
{
string[] cheatCodes = { "IDDQD", "IDKFA"};
static Queue<char> buffer; //Contains the longest number of characters needed
buffer.Enqueue(c);
if (buffer.Count() > 5) //Replace 5 with whatever your longest cheat code is
buffer.Dequeue();
bufferString = new System.String(buffer.ToArray());
foreach(string code in cheatCodes) {
if (bufferString.EndsWith(code)) {
//Do cheat work
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With