Examples of code and personal projects

Password Program
Here’s an example of a password program in C++ I made. Closes right away after doing what’s asked, but it works.

Password Program - Enhanced Edition
I updated the program, so that the user has 3 tries to “guess” the password, plus I added a little reference to Jurassic Park. Believe me or not, it took me hours to succeed at updating it the way I wanted it to be (I had never understood why until recently, but the while loop would consider the condition true even though I thought that numberOfTries=0; in fact, it was all about placing the decrement or “–” at the right places). Now, I feel so retarded, yet intelligent at the same time.

1 Like

The obvious choice: Thrive/src at master · Revolutionary-Games/Thrive · GitHub

Though I suppose I’ll link some of my recent code: Leviathan/Engine/GUI/VideoPlayer.h at develop · hhyyrylainen/Leviathan · GitHub

If you are starting to get into programming, then this is a good early program to make. But, I don’t think this is particularly good code. It has issues like using namespace std should not be used (other than really small learning programs) and most code styles I’ve seen require you to put spaces around operators instead of having no spaces within a line, as that makes reading it much more difficult.

2 Likes

First question : why not using “namespace std”? What problem does it cause?
Second question : Can a code without much spaces be difficult for the machine to read?

1 Like

A ton has been written about this. Here’s what’s on stackoverflow about this:

Code is meant for humans to read. A well made compiler couldn’t care less how you format your code. Formatting is about making code easier for others to read, or even yourself after you come back 6 months later to some piece of code you wrote.

1 Like

Ok. The only thing I still don’t understand is why “using namespace std” is not recommended. I read the Stackoverflow thread, but I still don’t understand somehow.

1 Like

It’s also partially a style thing. In order to write code that other people expect and can read easier, you should not use using namespace std. It can prevent some problems, but that is not the main point. A lot of programming is about making code clean in order to make it easier for other people to understand your code.

1 Like

randomNames Program
Here is a program that makes up random full names based on arrays of strings.

EDIT : I’ve put the first name “Gaston” and the last name “Dreyfus” as an easter egg (reference to UFO : Enemy Unknown in which one of the possible names for the soldiers is “Gaston Dreyfus” [in livestreams rediffusions of the french youtuber “Bob Lennon” on the previously mentioned game, he would always keep Gaston Dreyfus alive and he was the hero of the entire XCOM franchise to him{especially at the end of the game lol}]).

randomNames Program - Enhanced Edition
I updated the program by replacing arrays with vectors.

4 Likes

I have some questions. I have heard about some “dynamic arrays” (vectors). These are my questions:

  1. What does “dynamic” mean actually?
  2. I’ve seen that vectors are based on some object oriented programming results and it scares me. Can someone help me understand what is the concept of an object itself? What is an object? Is it a class? Is it a variable? What the hell is it? How can I use objects? How do I call objects, class and stuff like that. {In brief, tell me how to use object oriented programming and help me understand it.}
  3. When should I use vectors? How do I use them? Is it recommended to use them?
1 Like

The word “dynamic” is used a lot in programming. I suppose the most common definition for it is “not predetermined”.
So for example “dynamic memory” is memory that is allocated based on some runtime parameters. That is in contrast to static memory which is reserved when the program is written (your code examples do this by having static arrays).

Basically always. In modern programming all memory allocations are dynamic. We have so much RAM that basically no one cares if it isn’t used to the fullest potential. If you read through the thrive source code or Leviathan, there’s basically only a handful of cases where statically sized arrays are used. Everything else is vectors or some other dynamically sized data structures (Containers library - cppreference.com).

Reading about programming language theory gets really complicated fast (like this page about objects in C++: Object - cppreference.com I can read that, but only because I have a ton of experience actually coding in C++).
Instead you shouldn’t worry about the exact definitions that much. Instead refer to tutorials on how to use some feature (like vectors).

Here are some examples:

2 Likes

Your first procedural generator :slight_smile: Good work!

2 Likes

I just wrote these template methods:

    template<class T>
    bool ImportAndSaveFile(const std::string& file, const std::string& target, bool compress,
        bs::SPtr<typename OptionsCreator<T>::OptionsType> options =
            OptionsCreator<T>::Create())
    {
        auto resource = bs::gImporter().import<T>(file.c_str(), options);

        if(resource) {

            bs::gResources().save(resource, target.c_str(), true, compress);
            return true;
        }

        return false;
    }

    template<class T>
    bool MultiResourceSaveSingle(const bs::Vector<bs::SubResource>& resources,
        size_t& resourceCounter, const std::vector<std::string>& targets, bool compress)
    {
        if(resourceCounter >= resources.size()) {
            LOG_ERROR("Importer: ran out of resources in multi resource import");
            return false;
        }

        if(resourceCounter >= targets.size()) {
            LOG_ERROR("Importer: ran out of targets in multi resource import");
            return false;
        }

        auto resource = bs::static_resource_cast<T>(resources[resourceCounter].value);

        if(resource) {

            bs::gResources().save(resource, targets[resourceCounter].c_str(), true, compress);

        } else {
            LOG_ERROR("Importer: converting multi import resource failed, index: " +
                      std::to_string(resourceCounter) +
                      ", name: " + resources[resourceCounter].name.c_str());
            return false;
        }

        ++resourceCounter;
        return true;
    }

    template<class T>
    bool MultiResourceSaveHelper(const bs::Vector<bs::SubResource>& resources,
        size_t& resourceCounter, const std::vector<std::string>& targets, bool compress)
    {
        if(resourceCounter + 1 < targets.size()) {
            LOG_WARNING("Importer: excess targets provided for multi resource import");
        }

        return MultiResourceSaveSingle<T>(resources, resourceCounter, targets, compress);
    }

    template<class T, class SecondT, class... ExtraT>
    bool MultiResourceSaveHelper(const bs::Vector<bs::SubResource>& resources,
        size_t& resourceCounter, const std::vector<std::string>& targets, bool compress)
    {
        if(!MultiResourceSaveSingle<T>(resources, resourceCounter, targets, compress))
            return false;

        return MultiResourceSaveHelper<SecondT, ExtraT...>(
            resources, resourceCounter, targets, compress);
    }

    template<class T, class... AdditionalTypes>
    bool ImportMultiResource(const std::string& file, const std::vector<std::string>& targets,
        bool compress, bs::SPtr<typename OptionsCreator<T>::OptionsType> options)
    {
        auto resources = bs::gImporter().importAll(file.c_str(), options);

        if(resources->entries.size() == 0)
            return false;

        size_t resourceCounter = 0;

        return MultiResourceSaveHelper<T, AdditionalTypes...>(
            resources->entries, resourceCounter, targets, compress);
    }

    template<class T>
    bool ImportAndSaveWithOptions(const std::string& file, const std::string& target,
        bool compress, const Json::Value& options)
    {
        auto importOptions = OptionsCreator<T>::Create();

        std::vector<std::string> targets;
        targets.push_back(target);

        // Check for options and perform multi-imports
        if constexpr(std::is_same_v<T, bs::Mesh>) {
            if(options["animation"]) {

                importOptions->importAnimation = true;
                bool valid = false;

                for(const auto& animation : options["animation"]) {

                    // TODO: error checking
                    const auto type = animation["type"].asString();
                    const auto target = Importer::GetTargetWithoutSingleCheck(
                        animation["target"].asString(), Importer::FileType::Model);

                    targets.push_back(target);

                    if(type == "skin") {
                        importOptions->importSkin = true;

                    } else {
                        LOG_ERROR("Importer: unknown animation type: " + type);
                        return false;
                    }

                    // importOptions->setImportBlendShapes(true);

                    LOG_INFO("Animation target is '" + target + "'");
                    valid = true;
                }


                if(!valid) {
                    LOG_ERROR("Importer: animation definition is invalid");
                    return false;
                }

                return ImportMultiResource<T, bs::AnimationClip>(
                    file, targets, compress, importOptions);
            }
        }

        // Non-multi import
        return ImportAndSaveFile<T>(file, target, compress, importOptions);
    }

Is this about Thrive? Because if it is, I’m really happy (it’s about save files, right?)!

It is related to thrive. It isn’t about save files. It is about importing resource files

Speaking of resource files, I recently tried to extract files from a PAC file of some sort (dev resource from thrive i think) with a program called “GCFScape” I think. However, it wouldn’t recognize the file, even though it’s supposed to. Know what’s the problem?

Which file was it? I’m pretty sure there are no PAC files used in Thrive.

1 Like

bin\devtools_resources.pak

1 Like

Oh those pak files. They are from chromium. A quick search brought up this about their format:

1 Like

I’ll keep up the tradition of posting really arcane template stuff here:

if constexpr (std::is_pointer_v<CurrentT>) {

  IncrementRefCountIfRefCountedType(current);

  r = scriptcontext->SetArgAddress(
      i, const_cast<std::add_pointer_t<
             std::remove_const_t<std::remove_pointer_t<CurrentT>>>>(current));
} else if constexpr (std::is_lvalue_reference_v<CurrentT>) {

  IncrementRefCountIfRefCountedType(&current);

  r = scriptcontext->SetArgAddress(
      i, &const_cast<std::remove_const_t<std::remove_reference_t<CurrentT>>>(
             current));
}

This is in Leviathan, and this code seems to work and do what I want, which was surprising even to me.

oof, necropost! You really thought this thread would end like that to never be opened again? XD

Hey, I uploaded my two mini-programs on GitHub just to try it out!

With that first sample you should consider how you could reduce code duplication. You first check if the guess is right, and if it is wrong you go into a loop where the prompt is printed again and the answer checked. You should consider if you could reduce that code duplication.

1 Like