Young Shung's avatar

Young Shung



5 Aug 2021

Reviewing my old code

While I’ve always thought that my first programming project is a C++ BMI Calculator, there’s one time that I’ve remembered a while back that technically my first time that I code was when I tried modding Minecraft. I’m not really sure if I had done anything prior to that, but if I remember correctly, Minecraft mod is the first thing I’ve played around on. Not Hello World, not C++, it’s a Java mod.

I remember quite well what the tutorial website looks like (I tried digging it up but couldn’t find it), at that time I just copied and pasted the code and experimented with it. I was quite happy and excited that I wrote something custom into Minecraft. But that was it. Still, I’m quite surprised that middle school me was able to successfully create a custom mod in Java which I rarely use right now, albeit that I just copied and pasted code…

Here comes C++

C++ was my first programming language that I learned seriously. It’s around the end of 2015 that I picked up on it, downloaded Code::Blocks and some tutorials on YouTube and started my two-year journey on it. There are around 80 C::B projects that I’ve created including those that are used for testing/learning purposes and are abandoned. I’ll highlight some that are interesting.

My first program (Aug 2015)

void calculate() {
    calc = height / weight;
    remain = height % weight;
    cout << "Your total average is " << calc << "." << remain << "."  << endl;

    tellAvg();
}

Well the original Hello C++ output was already overwritten, and it is replaced with a… person body mass calculator? I thought it’s a BMI calculator at first glance but it’s actually an “average body calculator”, weird I would’ve said. At that time I also thought that the remainder value is the fraction. Well that is quite embarrassing to look at. I don’t think I’m aware of this error until now.

Also I really liked function back in the day. There’s 4 functions, which are askUser(), calculate(), tellAvg() and useAgain(). They’re all pretty self-explanatory.

void askUser() {
    cout << "YOU MUST ENTER CORRECTLY!" << endl;
    cout << "Enter your height. (cm)" << endl;
    cin >> height;  cout << endl;

    cout << "Enter your weight (kg)" << endl;
    cin >> weight; cout << endl;

    calculate();
}

It’s funny looking back at all these programs and a lot of them contains these ”Enter correctly!!” and I didn’t bother sanitizing the input at all. The missing dot after “weight” kinda bothers me too.

void tellAvg() {
    if (calc > 3) {
        cout << "You are a small person, right? \n" << endl;
    }

    if (calc < 3) {
        cout << "Looks like you are a bit heavy! \n" << endl;
    }

    if (calc == 3) {
        cout << "You are an average person, good job! \n" << endl;
    }

    useAgain();
}

void useAgain() {
    cout << "Do you want to use it again? (Y=1)" << endl;
    cin >> askAgain;

    if (askAgain == 1) {
        cout << endl;
        askUser();
    } else {
        cout << "\nThanks for using!\n" << endl;
        system("PAUSE");
    }
}

Here’s the code that tell whether you’re an average person. And to be average by definition of the written code above, you need to have around the height to weight ratio of 3… I also want to note that all of the variables are all integers. So integer division causes the average to skew slightly to taller and/or lighter people. Good job me!

I think one of the thing that programming fascinated and inspired me is that you can tell the computer to calculate anything you want based on any kind of input and it will spit out it’s output in mere milliseconds.

Cringe Valley

I wrote a short text-based Minecraft interactive story game that is very cringe-worthy. I’m just gonna leave this code below and say nothing.

void kill() {
    for (;;) {
        cout << "Do you have a diamond sword? (Y/N)" << endl;
        cin >> sword;

        cout << "Is your PvP skills good enough?" << endl;
        cin >> skills;

        transform(sword.begin(), sword.end(), sword.begin(), ::toupper);
        transform(skills.begin(), skills.end(), skills.begin(), ::toupper);

        if ((sword != "Y" && sword != "N") || (skills != "Y" && skills != "N")){
            cout << endl << "Oops! Something's wrong!" << endl;
            continue;
        }

        if (sword == "Y" && skills == "Y") {
            cout << "KILL THEM ALL!!!! 360 NOSCOPE OMGGGGGG" << endl;
            break;
        } else if (sword == "Y" || skills == "Y") {
            cout << "You may lost a lot of heart. Prepare your GApple!" << endl;
            break;
        } else {
            cout << "You're the bravest man/woman I've ever seen all day." << endl;
            break;
        }
    }
    askR();
}

I would say it’s the good ol’ days?

Enter Sound Library

Maybe because the program felt silent, I decided to introduce sounds to my C++ programs. That’s when I learned about external libraries and decided to use irrKlang. It’s really intuitive to use and you can easily play sound with just 4 lines of code.

#include <irrKlang.h>

irrklang::ISoundEngine* engine = irrklang::createIrrKlangDevice();

int main() {
    engine->play2D("click.wav");
    engine->drop();
    return 0;
}

Since it’s so basic, I’ve used it for almost all of the programs after I discovered it. The most-used audio file is probably click.wav which I downloaded somewhere on the Internet. Almost every key entered by the user will play the sound effect and I felt quite proud adding additional sound in my programs at that time.

Minecraft again! (Nov 2015)

Continuing my past obsession with Minecraft, in the past I had always wanted to play around with the server part of Minecraft. But with a 2010s computer and 1Mbps internet connectivity that’s not bound to happen. That’s when I came across this website: Can I host a Minecraft Server?

At that time I’m quite interested in how it’s able to estimate the total player that can be on the server with the Internet speed and total memory on the computer. So I dug into the script used to calculate it (at that time I had learnt about web development for a bit including JS) and translated its entirety to C++ code. There’s also more than 10 additional options for users to fine tune the final estimation.

  1. Minecraft PC or PE
  2. Server operating system
  3. Upload and download speed
  4. Total RAM allocated
  5. CPU architecture..?
  6. Private or public server
  7. Amount of plugins
  8. World type
  9. Nether enabled
  10. Type of spawning entities
  11. Map difficulty
  12. Idle timeout
  13. Server view distance
  14. How much lag generator (in the scale of 1 to 10)
  15. Storage type (HDD or SSD)
  16. Use of RAMDisks (huh…)

Well that’s a lot for just estimating how much a Minecraft server can handle players. I had gone out of the way to think of multiple factors for it. But to be honest, in the process I just wing it and write down what I think is appropriate for the estimation algorithm, which resulted in quite a jumble of code that I couldn’t understand well.

For those who might be interested of how the code looks like, here’s the gist. Felt weird that this is one of the projects that I’m proud of.

Programs for my studies

QuestionABCD (Nov 2015)

I think this is one of the programs that I had more care and attention on. That’s why it has an excess amount of logging, crash prevention and sound effects so there’s a total of 378 lines of code in it.

The program is actually very simple. Users can enter the 4 MCQ choices (A, B, C, D) for each question manually or use a text file named “input.txt”. Then, the program will clear the screen and now test the user’s answers. There’s sound effects for both the correct answer and wrong answer. After all questions are completed, the program will output the total correct/incorrect answers and their marks. The whole process is logged as well:

Running...

Question 1: A
Question 2: B
Question 3: C
Question 4: D
Question 5: Hello
Question 6: World

Ended question at question 6
ABCDHelloWorld
Question 1: Right answer! (A)
Question 2: Wrong answer! (You input C but it is B)
Question 3: Wrong answer! (You input B but it is C)
Question 4: Right answer! (D)
Question 5: Wrong answer! (You input Hi but it is Hello)
Question 6: Right answer! (World)
Question ended!

You got 50% marks!
50/50!

Total questions: 6
Questions answered right: 3
Questions answered wrong: 3

Total questions of: 
A: 1 B: 1 C: 1 D: 1

The program also works with normal text but is more focused on MCQ as it will record them and text file input won’t work with it. Still I’m quite impressed by what I have done. Though the code might be a bit convoluted, the program itself is quite complete and has a potential to be expanded with more features.

QuestionMarking (May 2016)

This is the exact same code with QuestionABCD, except with the sound library… wait what? I’m not really sure why there’s two version of the same program, and this “new” one is versioned 3.6exp and the others 3.6.110.

Let’s not think too much about it.

QuestionPick (May 2016)

One of the shorter programs that I think it’s more practical for students. It reads a list of text from a file, and then asks the users to write out all of the texts (order not important). Quite cool that the texts I used to quiz myself are still there. I’ll put down the full code since it’s quite short.

// FREAKING UNSTABLE
// Will be reprogrammed.

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

vector <string> questions;
vector <string> correct;
ifstream question("question.txt");
ofstream log("logs.txt");
unsigned int qline = 0;
unsigned int qyet = 0;
bool tempB;
unsigned int err = 0;
unsigned int tries = 0;

void func() {
    err = 0;
    string tempS;
    while (!question.eof()) {
        getline(question, tempS);
        questions.push_back(tempS);
    }
    qline = questions.size();
    log << "Loaded.\n\n";

    string input;
    while (qline > qyet) {
        tries++;
        tempB = false;
        cout << qline-qyet << "/" << qline << " left!\n";
        log << qline-qyet << "/" << qline << " left.";
        getline (cin, input);
        if (input == "quit") {
            log << "Quitted.\n\n";
            break;
        }

        for (unsigned int x=0; x<=qline-qyet; x++) {
                if (input == questions[x]) {
                tempB = true;
                cout << "Correct! (" << x+1 << ". " << questions[x] << ")\n\n";
                log << " Correct: " << x+1 << ". " << questions[x] << "\n";
                correct.push_back(questions[x]);
                qyet++;
                break;
            }
        }
        if (!tempB) {
            cout << "This answer was not included in the list.\n\n";
            err++;
            log << " Error " << err << " (" << input << ")\n";
        }
        log << "Looped.\n\n";
    }
    for (unsigned int x=0; x<=qline; x++) {
        if (l[x] == correct[x]) {
            cout << questions[x] << "\n";
        }
    }
    log << "____________________________________________\n";
    log << "Tries: " << tries;
    log << "\nQuestion: " << qline;
}

int main() {
    cout << "Written by Young Shung!\n\n";
    func();
    cout << "Press Enter to continue.";
    cin.get();
    return 0;
}

Huh, I really liked logging things. I think one of the reasons I wrote that first line of comment was probably how not feature-rich it is. Not sure why I wrote “freaking unusable” there but I think it’s quite usable for the most part and there’s no need for sophisticated code to achieve simple things. Remove the logging, optimize how it handles the texts and it would’ve been a simple and concise quiz program.

GameplayTime / TimeOrganizer (Mac 2016)

This is the largest project that I have done to date. The program acts as a pomodoro timer. It includes exciting new feature such as:

  • Text printing out one by one
  • Text centering
  • Colorful texts
  • More logging
  • More sound effects which are customizable
  • Inspirational quotes that I copied from somewhere
  • Includes configuration file
  • Many error catching statement
  • Goto statement… oh god

There’s around 900 lines of code in the main program which is the longest one yet. All of the functions compressed down into the single file so one can imagine how hard it is to understand the program, even for myself. I really liked to do that because 900 lines of code in one file sounds cooler than 900 lines spanning in multiple files. Furthermore I don’t comment on the code regularly, so it’s really a pain to read through all of it, especially for the variables-naming part.

/***/
void newCFG();
void addFile();
void getSettings();
void setSettings();
void manualSettings();
void menuScreen();
void startMain();
void inStart();
void restStart();
void exitP();
void midVerse();
inline bool fileExists(const string& name);
/***/

// Logging (stream)
ifstream quotes("quotes.txt");
ifstream rest("restquotes.txt");

// Holy Variables
// [GENERAL]
int inTime = 30;
int restTime = 5;
int skip = 0; // Skip midverse
int timeOut = 120; // 5min

// [Not in-app]
int logging = 1;
int intro = 1;
string notification = "audio/defnotification.mp3";
const char* notificationcc;
string alarm = "audio/defalarm.mp3";
const char* alarmcc;
int repAlarm = 10;
string spR = "0";
const char* spRcc;
string sp = "0";
const char* spcc;

// [DEV]
int errExit = 0;
int errCode = 0;
void resetCFG();
int resetCFGb = 0;

// TEMP
char tempC;
bool tempB;
string tempS;
double tempD;
int tempI;
int tempI2;
unsigned int begTime;
unsigned int elapsed;
const char* tempCCH;
unsigned int tempUI;

vector <string> quotesV;
vector <string> restV;
int quotesLine;
int restLine;

unsigned int focus = 0;
unsigned int rests = 0;
unsigned int middl = 0;

// STATS
int cycle = 0;

One of the TODO in the program is to “clean up the code”. Looking through the code I can imagine myself giving up. The code is really linear and there’s only a few reusability functions. Also I had wrote my own custom library to handle some of the features mentioned above.

Files of the program

This is the first program that I “released”, where I have all the necessary files in the folder and the program completed in the beta phase. I’m actually quite proud of it because it have the functionality of the program I had in mind, with colourful text, inspiration quotes and usable UI. But same as with the other programs, I rarely use it even though I wrote it to help myself become more productive.

Honourable Mentions

Here’s a list of C++ console projects that I have done.

  • GPA calculator (for my school’s co-curriculum program)
  • GPM calculator
  • Console calculator (4 arithmetic and comparison)
  • Program that generates random 0 and 1 in a file…
  • Calculate total file size based on the current percentage and downloaded size
  • Coin flipper + Yes or No + Random number generator
  • Game testing with your timing skills
  • Game testing with your typing skills
  • Guess the number game (with statistics!)
  • Rock Paper Scissors! (with more game statistics)
  • Tic Tac Toe (which the bot randomly picking a tile)
  • Nyan cat player - Minecraft Noteblock edition
  • Program that output random guitar chords to practice on
  • A proper BMI calculator
  • Incomplete Pong with SFML

Conclusion

It’s quite nostalgic looking back at all the code I had written while I’m still new to programming. Even though there’s a hefty amount of bad code practices, there’s also quite an amount of creativity manifested in the code themselves. I had always gone out of the way to write extended features for a project and had interesting projects that I would’ve not thought of now.

Also this blog post is not really serious and more towards a story time video on YouTube. I’ve thought of recording one but with my current equipment and environment I can’t really cut it.

Still, we always start somewhere throughout our journey in programming, whether through a college/university course, a YouTube video or a Udemy course; whether the first language is Python, C++ or Java. Interest and motivation to always push ourselves forward and learn something new every day goes a long way.

Website is launched again!

In the past I’ve always felt incertain publishing my content. I changed the theme of my website a few times, published on BitBalloon and Netlify hosting site and took it down a few days later. In June 2021 I had decided to rework my website writing the new Jekyll theme and published it on my new domain.

I’m excited for what is to come in the future. Currently I’m learning Android Jetpack Compose which just launched as stable and writing my new application which I may in the blog.

Thanks for reading and stay safe!