r/badcode • • Jan 10 '21

c# Throwback to my college graded unit

730 Upvotes

75 comments sorted by

73

u/[deleted] Jan 10 '21

I don't see an alternative, at least in Monogame/XNA? I've written similar code in an older version of my game engine too. Or I'm living under a stone?

22

u/Revelation2106 Jan 10 '21 edited Jan 10 '21

Yeah I think you're probably right, I've not touched XNA in years though.

That function was just a bonus, anyway. The real crème de la crème here is me at the tender age of 17 - with no prior programming knowledge at all - deciding to make a game using a single .cs file and a dream...

Here's some more snippets of my code, starting with how I handled dialogue:

#region Day1
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1Intro.txt"))
{
    string allText = stream.ReadToEnd();
    day1Intro = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1BarTalk.txt"))
{
    string allText = stream.ReadToEnd();
    day1BarTalk = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1BarRandy.txt"))
{
    string allText = stream.ReadToEnd();
    day1BarRandy = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1OutlandsTalk.txt"))
{
    string allText = stream.ReadToEnd();
    day1OutlandsTalk = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1RuinsTalk.txt"))
{
    string allText = stream.ReadToEnd();
    day1RuinsTalk = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1ShopQuestion.txt"))
{
    string allText = stream.ReadToEnd();
    day1ShopQuestion = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1ShopTalk.txt"))
{
    string allText = stream.ReadToEnd();
    day1ShopTalk = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1ShopWork.txt"))
{
    string allText = stream.ReadToEnd();
    day1ShopWork = allText.Split(separator, StringSplitOptions.None);
}
using (StreamReader stream = new StreamReader(Content.RootDirectory + "//Day1Cutscene.txt"))
{
    string allText = stream.ReadToEnd();
    day1Cutscene = allText.Split(separator, StringSplitOptions.None);
}
#endregion

And here's some draw() code:

GraphicsDevice.Clear(Color.Black);
#region Switch
switch (CurrentState)
{
    #region MenuCode
    #region MainMenu
    case GameState.MainMenu:
        spriteBatch.Begin();
        spriteBatch.Draw(mainMenuImage, ScreenDimmensions, Color.White);
        spriteBatch.End();

        #region Controls
        if (menuPosition == 0)
        {
            DrawTexture.DrawTextures(spriteBatch, startGameSelected.graphic, startGameSelected.rect, startGameSelected.rotation, startGameSelected.origin);
            DrawTexture.DrawTextures(spriteBatch, options.graphic, options.rect, options.rotation, options.origin);
            DrawTexture.DrawTextures(spriteBatch, credits.graphic, credits.rect, credits.rotation, credits.origin);
            DrawTexture.DrawTextures(spriteBatch, exitGame.graphic, exitGame.rect, exitGame.rotation, exitGame.origin);
        }
        if (menuPosition == 1)
        {
            DrawTexture.DrawTextures(spriteBatch, startGame.graphic, startGame.rect, startGame.rotation, startGame.origin);
            DrawTexture.DrawTextures(spriteBatch, optionsSelected.graphic, optionsSelected.rect, optionsSelected.rotation, optionsSelected.origin);
            DrawTexture.DrawTextures(spriteBatch, credits.graphic, credits.rect, credits.rotation, credits.origin);
            DrawTexture.DrawTextures(spriteBatch, exitGame.graphic, exitGame.rect, exitGame.rotation, exitGame.origin);
        }
        if (menuPosition == 2)
        {
             DrawTexture.DrawTextures(spriteBatch, startGame.graphic, startGame.rect, startGame.rotation, startGame.origin);
             DrawTexture.DrawTextures(spriteBatch, options.graphic, options.rect, options.rotation, options.origin);
             DrawTexture.DrawTextures(spriteBatch, creditsSelected.graphic, creditsSelected.rect, creditsSelected.rotation, creditsSelected.origin);
             DrawTexture.DrawTextures(spriteBatch, exitGame.graphic, exitGame.rect, exitGame.rotation, exitGame.origin);
        }
        if (menuPosition == 3)
        {
            DrawTexture.DrawTextures(spriteBatch, startGame.graphic, startGame.rect, startGame.rotation, startGame.origin);
            DrawTexture.DrawTextures(spriteBatch, options.graphic, options.rect, options.rotation, options.origin);
            DrawTexture.DrawTextures(spriteBatch, credits.graphic, credits.rect, credits.rotation, credits.origin);
            DrawTexture.DrawTextures(spriteBatch, exitGameSelected.graphic, exitGameSelected.rect, exitGameSelected.rotation, exitGameSelected.origin);
        }
    #endregion
    break;
#endregion

And finally, here's a look at my code to handle memory deallocation:

protected override void UnloadContent()
{

}

Shoutout to West College Scotland for thinking that was acceptable enough to allow me to move on to uni, where I quickly discovered how wrong they were. Also that they really should've taught us C++ instead...

Edit: formatting

13

u/[deleted] Jan 10 '21 edited Jan 10 '21

1.) Honestly, being taught C# isn't really bad at all. It's the reverse, I wish I could learn C# at high school instead of C++. They only teach basic stuff (syntax, functions, recursion, algorithms, and that's it). In the C# lectures they teach OOP,WinForms, and databases (more interesting, atleast in my opinion).

2.)In Monogame, you don't often have to deallocate memory. Maybe only deallocate the this.Content field. It's C#'s GC that does that. Related to other memoty leaks, they should be cleaned by the OS (if we are talking about a small project). I know that Mouse.GetState() or Keyboard.GetState() was (propably still is) culprit for small native memory leaks.

3.) (Perhaps a continuation of #1) If I'm staying here to think about programming lessons, I think they did a good decision teaching Monogame/XNA (if that's the case) because, as far as I know, MG/XNA is the easiest to learn framework over there. C++ offers more complex stuff( for example DirectX's API double pointers, low level draw calls, or WINAPI's pointer play (HWND, HMENU, LPVOID, LPWSTR, et cetera). These being the main differences, the main deal is that in programming, you don't care about the language, you care about the problem you're solving (sorting numbers, drawing to a Render-Target, calculating the integral of a given function using a algorithm, the rendering equation written in a HLSL/GLSL shader).

4.) The code itself, it might have bad points but, after all, I think you're kinda new in the world of programming. The most important part here, is that you're learning. Keep learning - that's my advice. You'll discover and get used to more standard/better coding practices, understand and use more APIs and libraries, get to know people passionate in web developing, reverse engineering, you name it.

Multiple edits: Extra stuff written.

Edit #4-ish. Since you were 17, how much time did pass since the code? Just being curious (And I realized argument #4 is useless.)

7

u/Revelation2106 Jan 10 '21

I think you're kinda new in the world of programming

I was at the time, yeah. I didn't take any computing courses in high school because I hadn't decided what I wanted to do with myself at that point. So I went into that course with 0 knowledge of programming languages or techniques. That mess of a code was the result lol

Since you were 17, how much time did pass since the code?

I turn 26 at the end of January so it's been nearly 9 years. I ended up dropping out of uni when I was 18 because the pressure of not knowing enough about C++ got to me, along with some other family stuff. It all worked out eventually, I'm back at uni now and in year 3 of my 4 year honours degree

I wish I could learn C# at high school instead of C++

The lecturer who taught me at college was convinced that the majority of the games industry would be moving over to C# fairly soon (lol) and that was why he decided to teach it over C++.

When I got to uni and they told me that C++ was and is still the standard, I essentially had to teach myself the language to catch up with the other students. As I mentioned, that really hit me hard.

Both languages are obviously very similar, but I really struggled with the concept of pointers since they weren't really a thing in C#. Manual memory deallocation also tripped me up a bit too.

I think if I could go back and learn C++ initially I'd do it just so that I could be introduced to pointers sooner. I guess it could just be a case of the grass always being greener on the other side, though. Maybe your initial experiences with C# were just as bad as me with C++.

2

u/recycle4science Jan 11 '21

Jesus, man, for somebody with absolutely zero experience, this could have been way worse!

2

u/MaxPlay Jan 10 '21

To be fair: UnloadContent makes not much sense in some scenarios of XNA. Unloading is not supported by the content manager, so this method is useless, if you don't hold on to handles to anything outside of the content manager, which you probably won't.

Also: As someone who taught students in university to write game code, I've seen (and written) worse in the past. Your approaches may not be using OOP or could optimized, but at least your code looks like you tried to make it readable and somewhat maintainable.

0

u/[deleted] Jan 10 '21

[deleted]

1

u/Revelation2106 Jan 10 '21

City of Glasgow? Don't know much about it but it can't be worse than WCS. My favourite WCS memory was a lecturer "teaching" us Unreal Engine by reading out a tutorial from a textbook because she didn't know herself

Good times

63

u/Beach-Devil i++++; Jan 10 '21

Or maybe just put it in a dictionary/hashmap

22

u/[deleted] Jan 10 '21

Yeah, but aren't dictionaries and hashmaps a little slower than a good ol' switch case?

This being just a guess, since string checking is O(n) and dictionary looping is O(n). Both happen at the same time, resulting in an overall complexity of O(n^2). While a switch-case is an O(n) complexity.

44

u/Beach-Devil i++++; Jan 10 '21

Dictionaries are fast because they have O(1) access time complexity. I’m pretty sure they operate in the same way switch cases do. Hashing the key and jumping to that value/block

0

u/[deleted] Jan 10 '21

Ohhh, that's a nice C# implementation from .NET :D

29

u/RFC793 Jan 11 '21

Not really, that’s just a fact. A hash-based dictionary is O(1) and a tree based one is O(log n). The hash one is somewhat misleading though since the time to calculate the hash has been amortized.

I’m not familiar with this coding environment, but if those Keys constants are basically integers, I’d consider indexing into a list/array instead. O(1) and no hash calculation.

0

u/ArdiMaster Jan 11 '21

The hash one is somewhat misleading though since the time to calculate the hash has been amortized.

Why? Calculating the hash of one element doesn't depend on how many elements are in the dictionary.

5

u/RFC793 Jan 11 '21

Right, that’s why I say it is amortized. For small sets, the hash calculation could be more costly than an if/else chain

2

u/ArdiMaster Jan 11 '21

"Amortised" in this sense usually means that sometimes the operation will take much longer, but it's such a rare occasion that you just sort of ignore it. E.g. a C++ vector needs to be resized (copied) if you add too many elements to it, but that doesn't happen very often, so adding to a vector is considered to have "O(1) amortised" complexity.

You're right that calculating the hash might take too long in a small set, but that's not a matter time complexity.

2

u/RFC793 Jan 11 '21

True. I intended to mention at the end of my last comment: this is me speaking from the angle of practical implementation, and this is independent of any Big-O complexity analysis.

One also needs to consider the time to construct the dictionary (will it be used enough to warrant the cost, etc). Basically the same argument for not using regex when a simple substring search would suffice, etc.

1

u/Astrokiwi Jan 11 '21 edited Jan 11 '21

That's the same for a switch statement. You are still checking a string of length L against (up to) N strings, so an O(LN) complexity.

Edit: My brain farted. I'd either do a hashmap with ints as keys, or just loop straight through a list of objects.

3

u/[deleted] Jan 11 '21

Not really, in the switch statement, he's comparing numbers, not strings. Enums are implemented using numbers.

2

u/Astrokiwi Jan 11 '21

ugh yeah brainfart. Here I might loop through a list rather than using a hash lookup, because integer comparisons are really fast, and there's not many keys to check. Sometimes a quick O(N) is better than a slow O(1).

1

u/[deleted] Jan 11 '21

It happens sometimes, don't worry :D

Edit: Forgot to mention that a switch case is O(1) since the input size is fixed.

0

u/Astrokiwi Jan 11 '21

Yeah, the problem here is that it's hard-coding data into the program. It's mostly just three lists - one of KEY IDs, one of lower case characters, one of upper case characters. I would store those inside a configuration file that gets read at launch, and use a hashmap or whatever to do the conversion in the code. In addition to having simpler and more concise code, then you can change keyboard layouts for international support, or have user-configurable keyboard layouts, all without recompiling the code each time.

4

u/Beach-Devil i++++; Jan 11 '21

Yea I agree hardcoding something like this is bad and bloats up your program. I don’t know if C# has a built in module but you could probably store this as a json or a config file whichever one is more convenient

4

u/[deleted] Jan 10 '21 edited Jan 11 '21

They could replace it with a dictionary/hashmap, or use a switch expression instead of a switch statement.

1

u/obiwac Jan 11 '21

I think he was highlighting the line numbers

1

u/Not_Sugden Jan 11 '21

there is probably a built in function for this, i would imagine so anyway since there are different keyboard layouts, for example in the code in pictures the @ symbol is returned when shift + 2 is pressed, keyboards here in the UK return a " not an @

15

u/MCKoleman Jan 11 '21

Why are the functions 4000+ lines of code? Are there really no helper functions in there?

14

u/Revelation2106 Jan 11 '21

Nope, none at all haha

244

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 10 '21 edited Jan 11 '21

Image Transcription: Code


[This post has two code snippets in separate images.]


[The first snippet is as follows (the two functions are both condensed, showing them to be around 4000 lines long each):]

protected override void Update(GameTime gameTime)
{

protected override void Draw(GameTime gameTime)
{

[The second snippet is as follows:]

        protected override void Draw(GameTime gameTime)
        {
        
        public void UpdatePlayerPosition()
        
        public string ConvertKeyToChar(Keys[] key, bool shift)
        {
            foreach (Keys 1 in key)
            {
                Keys currentKey = q;
                
                if (previousKG.IsKeyUp(q) && currentKG.IsKeyDown(q)
                {
                    switch (q)
                    {
                        case Keys.Space: return " ";
                        
                        // Escape Sequences
                        case Keys.Enter: return "\n";                                    // Create a new line
                        case Keys.Tab: return "\t";                                      // Tab to the right
                        
                        // D-Numerics (strip above the alphabet)
                        case Keys.D0: return shift ? ")" : "0";
                        case Keys.D1: return shift ? "!" : "1";
                        case Keys.D2: return shift ? "@" : "2";
                        case Keys.D3: return shift ? "#" : "3";
                        case Keys.D4: return shift ? "$" : "4";
                        case Keys.D5: return shift ? "%" : "5";
                        case Keys.D6: return shift ? "^" : "6";
                        case Keys.D7: return shift ? "&" : "7";
                        case Keys.D8: return shift ? "*" : "8";
                        case Keys.D9: return shift ? "(" : "9";
                        
                        // Numpad
                        case Keys.NumPad0: return "0";
                        case Keys.NumPad1: return "1";
                        case Keys.NumPad2: return "2";
                        case Keys.NumPad3: return "3";
                        case Keys.NumPad4: return "4";
                        case Keys.NumPad5: return "5";
                        case Keys.NumPad6: return "6";
                        case Keys.NumPad7: return "7";
                        case Keys.NumPad8: return "8";
                        case Keys.NumPad9: return "9";
                        case Keys.Add: return "+";
                        case Keys.Subtract: return "-";
                        case Keys.Multiply: return "*";
                        case Keys.Divide: return "/";
                        case Keys.Decimal: return ".";
                        
                        // Alphabet
                        case Keys.A return shift ? "A" : "a";
                        case Keys.B return shift ? "B" : "b";
                        case Keys.C return shift ? "C" : "c";
                        case Keys.D return shift ? "D" : "d";
                        case Keys.E return shift ? "E" : "e";
                        case Keys.F return shift ? "F" : "f";
                        case Keys.G return shift ? "G" : "g";
                        case Keys.H return shift ? "H" : "h";
                        case Keys.I return shift ? "I" : "i";
                        case Keys.J return shift ? "J" : "j";
                        case Keys.K return shift ? "K" : "k";
                        case Keys.L return shift ? "L" : "l";
                        case Keys.M return shift ? "M" : "m";
                        case Keys.N return shift ? "N" : "n";
                        case Keys.O return shift ? "O" : "o";
                        case Keys.P return shift ? "P" : "p";
                        case Keys.Q return shift ? "Q" : "q";
                        case Keys.R return shift ? "R" : "r";
                        case Keys.S return shift ? "S" : "s";
                        case Keys.T return shift ? "T" : "t";
                        case Keys.U return shift ? "U" : "u";
                        case Keys.V return shift ? "V" : "v";
                        case Keys.W return shift ? "W" : "w";
                        case Keys.X return shift ? "X" : "x";
                        case Keys.Y return shift ? "Y" : "y";
                        case Keys.Z return shift ? "Z" : "z";
                        
                        // Oem
                        case Keys.OemOpenBrackets: return shift ? "{" : "[";
                        case Keys.OemCloseBrackets: return shift ? "}" : "]";
                        case Keys.OemComma: return shift ? "<" : ",";
                        case Keys.OemPeriod: return shift ? ">" : ".";
                        case Keys.OemMinus: return shift ? "_" : "-";
                        case Keys.OemPlus: return shift ? "+" : "=";
                        case Keys.OemQuestion: return shift ? "?" : "/";
                        case Keys.OemSemicolon: return shift ? ":" : ";";
                        case Keys.OemQuotes: return shift ? "\" : "'";
                        case Keys.OemPipe: return shift ? "|" : "\\";
                        case Keys.OemTilde: return shift ? "~" : "`";
                    }
                }
            }
            
            return string.Empty;
        }
    }
}

This is an unofficial transcription. Our bot doesn't currently pick up gallery posts, so I'm doing this in an unofficial capacity. If you're interested in why I've done this, feel free to message me!

111

u/Galse22 Jan 10 '21

Good human. Wow.

44

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 10 '21

Thanks! :D

61

u/OrganicBid Jan 10 '21

No reason to punish yourself like that even if it is to help other people.

49

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 10 '21

Lol, how do you know? Maybe I've done terrible things, such as ignoring my alarm...

11

u/ywBBxNqW Jan 11 '21

I set three in a row just in case.

3

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Good idea. I'll try that.

4

u/OrganicBid Jan 11 '21

I also recommend Alarm Clock Xtreme (Android). Having to solve arithmetic in the morning to turn off the alarm is effective.

1

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Will give that a try as well! Thank you!

2

u/literallyfabian Jan 11 '21

honestly, i'm feeling pretty sure these posts gets requested to be transcribed just to troll

20

u/IsaGoodFriend Jan 10 '21

My god, this is an insane amount of work

20

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 10 '21

It wasn't too much, but those characters were annoying to update after the copypaste finished. Didn't help that the configuration isn't the one I'm used to.

12

u/Beloncio Jan 10 '21

I hate being the one to point this after your awesome work but... You misspelled the first 'protected'

14

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

It's good to point out the mistakes! I want the transcription to be as accurate as possible. I'll fix that as soon as I get back to my PC. :)

2

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Fixed now I may have forgotten about it and gone to bed last night, thanks again for pointing out!

5

u/vasilescur Jan 10 '21

Please tell me you used OCR for this...

13

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Since the bot can't find it, I can't show you what its attempt would have been, but it wouldn't have been pretty.

We have pretty much the best OCR not behind a huge paywall, and one of the many, many things that mess it completely is code. It drops formatting, loses characters and even whole lines, splits lines halfway through, and generally just has a bad time.

So because both the bot can't see it and the bit can't do it, nope, I didn't use OCR.

5

u/PC__LOAD__LETTER Jan 11 '21

Oh dear. I think I’m missing something - why?

7

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Usually the transcriptions are to aid blind/otherwise-visually-impaired people who rely on screen readers to browse Reddit, since that technology generally can't reliably read text from images.

I think few people would want to listen to this, though, so in this case it's probably more helpful for people whose internet or client can't load the image, and anyone wanting to copy-paste it.

5

u/alex_hawks Jan 11 '21

I'm the description of the first snippet, you say characters, I think you mean lines

2

u/EishLekker Jan 11 '21

Hello the description of the first snippet, I'm dad!

3

u/alex_hawks Jan 11 '21

Leaving that error for the the sake of this joke

1

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Oh shoot yeah. I'd gone to bed. I'll fix that once the PC's booted up.

1

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Fixed. Thanks for pointing out.

4

u/matjojo1000 Jan 11 '21

Btw, the methods aren't 4000 characters but 4000 lines long

3

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Thanks. I'll fix it once I boot up the PC. Trying to edit these on mobile is hell.

2

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Fixed now. Thanks again for pointing out.

3

u/matjojo1000 Jan 11 '21

No problem at all haha, thanks for transcribing that massive thing.

2

u/TheOnlyTails Jan 11 '21

Love you Murdo! You're the best!

2

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Aw, thanks! <3

2

u/cnprof Jan 11 '21

Ok, this is amazing.

1

u/shcanthinkofusername Jan 11 '21

do you get paid for this to transcribe?

1

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 11 '21

Nope, I'm a volunteer. The main wiki page at r/TranscribersOfReddit explains more (I'd link the specific page but I'm on mobile).

81

u/Thenderick Jan 11 '21

convertToChar

Converts to a string

LIKE A BOSS

16

u/roycohen2005 Jan 10 '21

The best part is that it returns a string and not a char as suggested by the name.

16

u/tangerinelion Jan 10 '21

I liked

foreach (Key q in keys)

for the excellent and obvious variable name.

14

u/prettyfuzzy Jan 11 '21

You didn't know quey is the singular of keys?

10

u/lightheat Jan 11 '21

technically "quay," but I like where your head's at

9

u/Kidknudi Jan 11 '21

This is a good r/badcode submission simply for having been written in npp

11

u/lightheat Jan 11 '21

A fancy IDE does not a good coder make.

3

u/mcp613 Jan 11 '21

Yeah, but it makes a faster one.

1

u/MADH95 Jan 17 '21

I go to uni with him and suggested he upload it here.

It wasn't written in npp it was written in visual studio it just wouldn't open in the latest version so he had to improvise.

3

u/mtizim Jan 11 '21

Also it converts Key[ ] to String with a run-once forEach lol

4

u/[deleted] Jan 10 '21

aaaaaAAAAA

2

u/Not_Sugden Jan 11 '21

case Keys.D2: return shift ? "@" : "2"

because only the american keyboard exists you know, its not like any other keyboards actually have the " as shift+2

1

u/MADH95 Jan 17 '21

What's funny is that he's Scottish, not American lmao