Staredit Network > Forums > Technology & Computers > Topic: Cecil's Game Programming Blog Discussion
Cecil's Game Programming Blog Discussion
Nov 2 2010, 2:33 am
By: CecilSunkure  

Nov 2 2010, 2:33 am CecilSunkure Post #1



Cecil's Game Programming Blog Discussion!



This topic was created to stimulate discussion and hopefully to get my blog more active, as well as serving the purpose of having a convenient area of discussion with my fellow SENers. I'll be bumping this topic periodically with updates about posts and other links of interest.

For those of you who don't know, I'm attending DigiPen next year and aspire to become a professional game programmer. Recently I moved next to the DigiPen campus, and as such have a great wealth of resources that aren't accessible to anyone that doesn't attend the school. I'm going to be sharing these resources with everyone that reads my blog posts! You should expect to see a high frequency of very interesting and valuable links provided throughout all my posts, with both hard to find and extremely useful resources.

My blog has two goals: A) Chronicle what it is like to go from no programming experience to becoming a successful professional game programmer in an industry leading company; B) Solidify my understanding of the topics I study and blog about. I'll be covering a very broad range of topics that fall into the genres of Game Design, Computer Science, and Mathematics (as well as physics).

Comment about specific posts, ask questions, provide feedback about the blog in general, ask questions related to Game Design, Computer Science, or Mathematics, anything!

Post has been edited 3 time(s), last time on Nov 2 2010, 2:40 am by CecilSunkure.



None.

Nov 2 2010, 2:48 am CecilSunkure Post #2



The other day I wrote a post about installing cygwin and practicing C. One of those programs I wrote to practice my coding, was a prime finding program.

This program finds all prime numbers between a range of integers (like 1 and 100):
PrimeFind.exe
#include <stdio.h>

int main(void)
{
    int num1, num2;
   
    printf("Enter in two integer parameters (least to greatest): ");
    scanf("%d%d", &num1, &num2);
   
    if (num1 < 3)
    {
        printf("1\n2\n");    
    }

    for (int i = num1; i < num2; i++)
    {
        for (int j = 2; j < i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j == i - 1)
            {
                printf("%d\n", i);
                break;
            }
        }
    }
   
    getchar();
    getchar();
    return 0;
}


The main idea is to use the modulo operator (%) to find out if any number between a range of numbers is divisible by anything from 2-n. The modulo operator is pretty much division, except it returns the remainder from the division, just like we all did in third grade. However, what is most interesting is how to optimize this program. Currently, when I run this with a range of 1-100000, it takes about 18% of my CPU usage to calculate all the prime numbers within that range. In order to optimize this program I took use of the knowledge that you only need to test up to the square of the upper parameter (the larger number you input). Although instead of finding the square root of the upper parameter, I just square the variable j within my for loop's second expression.

PrimeFind_Optimized
#include <stdio.h>

int main(void)
{
    int num1, num2, isPrime;
   
    printf("Enter in two integer parameters (least to greatest): ");
    scanf("%d%d", &num1, &num2);

    for (int i = num1; i < num2; i++)
    {
        isPrime = 1;
       
        for (int j = 2; j*j < i; j++)
        {
            if (i % j == 0)
            {
                isPrime = 0;
                break;
            }
        }
       
        if (isPrime == 1)
        {
            printf("%d\n", i);
        }
    }
   
    getchar();
    getchar();
    return 0;
}


If you run both of these programs at the same time the optimized one should finish two or so seconds sooner. This is because it makes 1/4 the amount of comparisons as the first program. My first program would test to see if each number from 1-n could be evenly divided into n, and the optimized program only tests 1-sqrt(n). The source code for these programs, as well as some other programs that are similar, can be found in this post of my blog: http://cecilsunkure.blogspot.com/2010/11/installing-cygwin-and-practicing-c.html



None.

Nov 2 2010, 11:22 pm CecilSunkure Post #3



Today I finished a program that generates a random walk across a 10x10 array, using the letters of the alphabet. If there is nowhere else to walk, the program was supposed to self-terminate, and you weren't supposed to let the program collide into a previously moved into spot (this means I have very basic collision detection!). A final outcome should look something like this:

Code
a . . . . . . . . .
b c . . . . . . . .
e d . . . p q r . .
f . . . . o . s . .
g h i j . n u t . .
. . . k l m v . . .
. . . . . . w . . .
. . . . z y x . . .
. . . . . . . . . .
. . . . . . . . . .


Luckily our forums have a nice codebox, so I'll post my source code here:
Random_Walk.exe
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef int bool;

int randomInt(int low, int high)
{
   return (rand() % (high - low + 1) + low);
}

int main(void)
{
    int board[10][10] ={{'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.',},
                        {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.'}};
    int letters[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    int x = 0, y = 0;
    int move, row, column;
   
    srand(time(0));
   
    for (int i = 0; i < sizeof(letters) / sizeof(letters[0]); i++)
    {
        board[y][x] = letters[i];
       
        for (column = 0; column < 10; column++)
        {
            for (row = 0; row < 10; row++)
            {
                printf("%c ", board[column][row]);
            }
            printf("\n");
        }
       
        printf("\n");
        while (1) //Randomize 0-3, and update x or y accordingly.
        {
            move = randomInt(1, 4);
           
            if (move == 1)
            {
                if (x != 0)
                {
                    if (board[y][x - 1] == '.')
                    {
                        x -= 1;
                        break;
                    }
                }
            }
           
            if (move == 2)
            {
                if (y != 9)
                {
                    if (board[y + 1][x] == '.')
                    {
                        y += 1;
                        break;
                    }
                }
            }
           
            if (move == 3)
            {
                if (x != 9)
                {
                    if (board[y][x + 1] == '.')
                    {
                        x += 1;
                        break;
                    }
                }
            }
           
            if (move == 4)
            {
                if (y != 0)
                {
                    if (board[y - 1][x] == '.')
                    {
                        y -= 1;
                        break;
                    }
                }
            }
           
            if (board[y][x + 1] != '.' && board[y][x - 1] != '.' && board[y + 1][x] != '.' && board[y - 1][x] != '.')
            {
                printf("\n\nThere is no where else to walk. Hit enter to leave.");
                getchar();
                return 0;
            }
           
            if (x == 0 && board[y][x + 1] != '.' && board[y + 1][x] != '.' && board[y - 1][x] != '.')
            {
                printf("\n\nThere is no where else to walk. Hit enter to leave.");
                getchar();
                return 0;
            }
           
            if (x == 9 && board[y][x - 1] != '.' && board[y + 1][x] != '.' && board[y - 1][x] != '.')
            {
                printf("\n\nThere is no where else to walk. Hit enter to leave.");
                getchar();
                return 0;
            }
           
            if (y == 0 && board[y][x + 1] != '.' && board[y][x - 1] != '.' && board[y + 1][x] != '.')
            {
                printf("\n\nThere is no where else to walk. Hit enter to leave.");
                getchar();
                return 0;
            }
           
            if (y == 9 && board[y][x + 1] != '.' && board[y][x - 1] != '.' && board[y - 1][x] != '.')
            {
                printf("\n\nThere is no where else to walk. Hit enter to leave.");
                getchar();
                return 0;
            }
        }
    }
   
    getchar();
    return 0;
}


I didn't learn anything new while writing this program, although, I did get more familiar with C syntax, which was my main goal.

If you'd like to see the source code file or the compiled .exe, you can find them here: http://cecilsunkure.blogspot.com/2010/11/2d-array-practice.html



None.

Nov 2 2010, 11:46 pm O)FaRTy1billion[MM] Post #4

👻 👾 👽 💪

Now make a random maze generator! :D That's always a fun one to do.



TinyMap2 - Latest in map compression! ( 7/09/14 - New build! )
EUD Action Enabler - Lightweight EUD/EPD support! (ChaosLauncher/MPQDraft support!)
EUDDB - topic - Help out by adding your EUDs! Or Submit reference files in the References tab!
MapSketch - New image->map generator!
EUDTrig - topic - Quickly and easily convert offsets to EUDs! (extended players supported)
SC2 Map Texture Mask Importer/Exporter - Edit texture placement in an image editor!
\:farty\: This page has been viewed [img]http://farty1billion.dyndns.org/Clicky.php?img.gif[/img] times!

Nov 6 2010, 9:28 pm CecilSunkure Post #5



I've posted about one of the most important aspects of C; pointers! Pointers pointers pointers are very necessary to know, and you should all read this post: http://cecilsunkure.blogspot.com/2010/11/pointers-basics.html



None.

Nov 6 2010, 11:38 pm DT_Battlekruser Post #6



You should learn assembly now :)



None.

Nov 7 2010, 12:21 am CecilSunkure Post #7



You actually have to code in Assembly a few times during Freshman year at DigiPen. So, I'll eventually have to :P



None.

Nov 10 2010, 7:46 am Sand Wraith Post #8

she/her

C++ > C (evaluates TRUE)

cecil since you're so cool why don't you look at an assignment-program of mine

assignment descriptor: http://pastebin.com/PLPjTY7V

Man, not having to be able to use arrays sucked. Man, 4 functions, largely the same, for the 4 directions... eugh. Could have just used 1.

Think you can review it? I've gone through it as well as I can, I'm relatively satisfied with it, considering the implementation of the log-examiner. I could try doing more with it, but I think I'm done with this. +_+ I'm exhausted already.

http://pastebin.com/MSx25sqE (too massive for SEN)

Used 3.x series of Python.

But, seriously, why C instead of C++?




Nov 10 2010, 8:44 am CecilSunkure Post #9



I'll have to look at it tomorrow as I'm not getting home till really late tonight.

In order to become an extremely talented programmer, you have to first understand the fundamentals at a very deep level of detail; you have to have an extremely strong base in order to build a tall building. I can't move onto higher level programming without mastering the low-level stuff, if I ever plan to be able to code entire high-performance games from scratch.

C++ isn't something you can learn without mastering C, unless you're okay with your programming being lacking.



None.

Nov 10 2010, 5:01 pm EzDay281 Post #10



Maybe you already mentioned this and I just didn't notice, and it is ultimately trivial, but I figured I might as well:
I think you made a mistake in your optimized prime-finder.
Line 14:
Code
       for (int j = 2; j*j < i; j++)

should be
Code
       for (int j = 2; j*j <= i; j++)

When I ran your program, I noticed it was listing 4, 9, 25, 36... as primes. :P



None.

Nov 10 2010, 7:14 pm Jack Post #11

>be faceless void >mfw I have no face

Quote
C++ > C (evaluates TRUE)
C is faster than C++, although it hasn't got classes and a few other things.



Red classic.

"In short, their absurdities are so extreme that it is painful even to quote them."

Nov 10 2010, 9:16 pm Biophysicist Post #12



According to my dad, that's a non-issue on modern computers.

Though he does do corporate stuff, not gaming or anything graphics-intensive, so take this with a grain of salt (or pepper, if you prefer).



None.

Nov 10 2010, 9:27 pm Sand Wraith Post #13

she/her

Quote from Jack
Quote
C++ > C (evaluates TRUE)
C is faster than C++, although it hasn't got classes and a few other things.

Quote from Biophysicist
According to my dad, that's a non-issue on modern computers.

Though he does do corporate stuff, not gaming or anything graphics-intensive, so take this with a grain of salt (or pepper, if you prefer).

My present bias is that computers have developed enough to the point that the performance boost from using C instead of C++ is negligible. I think the extra features (especially classes) that C++ provides is generally more beneficial than any performance boost from using C.

The situation still dictates the course of action though. Assuming that C++ is mostly a superset of C, isn't it possible to do low-level programming in C++ anyway?

I'd love to see any academic articles on the issue though.




Nov 10 2010, 9:46 pm CecilSunkure Post #14



Quote from EzDay281
Maybe you already mentioned this and I just didn't notice, and it is ultimately trivial, but I figured I might as well:
I think you made a mistake in your optimized prime-finder.
Line 14:
Code
       for (int j = 2; j*j < i; j++)

should be
Code
       for (int j = 2; j*j <= i; j++)

When I ran your program, I noticed it was listing 4, 9, 25, 36... as primes. :P
Strange. In the copy I have, that isn't a problem. Maybe I accidentally hit a key and saved it before I uploaded it. Oh well :P

The one I have works perfectly fine.

Quote from name:Zany
C is faster than C++, although it hasn't got classes and a few other things.
That isn't really true. C++ can be just as fast as C depending on the coder. You can do, as far as I know, anything in C with C++. C++ is just an expansion pack for C, hence C being so backwards compatible.



None.

Nov 10 2010, 9:56 pm Jack Post #15

>be faceless void >mfw I have no face

Ah, after checking up on it I see I was wrong, and that C++ being slower is a myth unless you use it wrong.



Red classic.

"In short, their absurdities are so extreme that it is painful even to quote them."

Nov 11 2010, 1:00 am O)FaRTy1billion[MM] Post #16

👻 👾 👽 💪

There are a few exceptions with "C works under C++", though. Some of my programs wont compile under C++ without changing some things. :P



TinyMap2 - Latest in map compression! ( 7/09/14 - New build! )
EUD Action Enabler - Lightweight EUD/EPD support! (ChaosLauncher/MPQDraft support!)
EUDDB - topic - Help out by adding your EUDs! Or Submit reference files in the References tab!
MapSketch - New image->map generator!
EUDTrig - topic - Quickly and easily convert offsets to EUDs! (extended players supported)
SC2 Map Texture Mask Importer/Exporter - Edit texture placement in an image editor!
\:farty\: This page has been viewed [img]http://farty1billion.dyndns.org/Clicky.php?img.gif[/img] times!

Nov 11 2010, 1:56 am CecilSunkure Post #17



New post about structures, unions, and enumerations is up! Do you know what each of these data types are? Are you a little fuzzy about the differences between them? Then read this!



None.

Nov 12 2010, 6:34 am A_of-s_t Post #18

aka idmontie

I'll just leave this here:

Code
...
/**
    * Nas-nav menu highlighter
    */
    pathArray = "";
    if(location.href.indexOf('?') != -1) {
        pathArray = location.href.split( "?" );
        pathArray = pathArray[1].split( '&' );
        pathArray = pathArray[0].split( '=' );
        pathArray = pathArray[0];
        if(pathArray !== "add")
            pathArray = "";
    }
    //Find the link that matches the url that lies within the nas navigation, and only bold the first occurance.
    $('div[id="nas_nav"] a[href*="' + location.pathname + '"][href*="' + pathArray + '"]:first').css("font-weight", "bold");
   
...




Personal GitHub
Starcraft GitHub Organization - Feel free to request member status!
TwitchTV

Nov 12 2010, 8:03 pm A_of-s_t Post #19

aka idmontie

Interesting things about C++:

The Singleton:
Code
class Singleton {
private:
   static Singleton* inst;
   Singleton() {}
public:
   static Singleton* getInstance();
};

Singleton* Singleton::getInstance() {
   if (inst == 0)
       inst = new Singleton();
   return inst;
}


Memory Alignment:
Code
#pragma pack(push,1)

struct ReallySlowStruct {
   char c:6; //6 bytes
   __int64 d:64;
   int b:32;
   char a:8;
};

struct SlowStruct {
   char c;
   __int64 d;
   int b;
   int a;
};

struct FastStruct {
   __int64 d;
   int b;
   char a;
   char c;
   char unused[2];
};

#pragma pack(pop)

The smallest unit that can be reserved is 2 bytes.



Personal GitHub
Starcraft GitHub Organization - Feel free to request member status!
TwitchTV

Options
  Back to forum
Please log in to reply to this topic or to report it.
Members in this topic: None.
[01:39 am]
Ultraviolet -- no u elky skeleton guy, I'll use em better
[10:50 pm]
Vrael -- Ultraviolet
Ultraviolet shouted: How about you all send me your minerals instead of washing them into the gambling void? I'm saving up for a new name color and/or glow
hey cut it out I'm getting all the minerals
[10:11 pm]
Ultraviolet -- :P
[10:11 pm]
Ultraviolet -- How about you all send me your minerals instead of washing them into the gambling void? I'm saving up for a new name color and/or glow
[2024-4-17. : 11:50 pm]
O)FaRTy1billion[MM] -- nice, now i have more than enough
[2024-4-17. : 11:49 pm]
O)FaRTy1billion[MM] -- if i don't gamble them away first
[2024-4-17. : 11:49 pm]
O)FaRTy1billion[MM] -- o, due to a donation i now have enough minerals to send you minerals
[2024-4-17. : 3:26 am]
O)FaRTy1billion[MM] -- i have to ask for minerals first tho cuz i don't have enough to send
[2024-4-17. : 1:53 am]
Vrael -- bet u'll ask for my minerals first and then just send me some lousy vespene gas instead
[2024-4-17. : 1:52 am]
Vrael -- hah do you think I was born yesterday?
Please log in to shout.


Members Online: eksxo