Putting the 'role' back in role-playing games since 2002.
Donate to Codex
Good Old Games
  • Welcome to rpgcodex.net, a site dedicated to discussing computer based role-playing games in a free and open fashion. We're less strict than other forums, but please refer to the rules.

    "This message is awaiting moderator approval": All new users must pass through our moderation queue before they will be able to post normally. Until your account has "passed" your posts will only be visible to yourself (and moderators) until they are approved. Give us a week to get around to approving / deleting / ignoring your mundane opinion on crap before hassling us about it. Once you have passed the moderation period (think of it as a test), you will be able to post normally, just like all the other retards.

Vapourware Trying to learn programming from ~0, realistic goals naturally help needed.

baturinsky

Arcane
Joined
Apr 21, 2013
Messages
5,537
Location
Russia
I haven't coded in c++ for a long while (and not at all in c++11), but looks like "auto" just makes compiler figure out the type of variable instead of you. You could just use actual type instead, but then you have to deal with the clusterfuck that is C++ type syntax. Or if you want a less messy code, use vector instead.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Ehhh i have now old problem.
Can't figure out proper data handling for my game.

I have three types of data structures:

lists - which are most basic. By doing them though i need to write ton of code to compare it with either dicts or lists. sortable
dicts - good way to include stuff that gives me at least 1 additional data about something like ak74 : 20 (for damage) but it is way worse to do anything else.
classes - ideal for big data thanks to it each object can have ton of different things to it. Problem is though that of i want to proceduraly generate stuff then i can't later sort list as list of objects as variables are random hex based variables.

My main problem is though how to deal with proceduraly generated stuff.

I mean for example let's say i want to create combat scenario.
i create class that handles atributes of enemy and player.

Now i create that combat scenario and here comes problem:

I want to create initiative for my combat so later list of turns will be sorted in reverse so object with biggest initiative will have first turn.
player1 is easiest as it is static and there are no more players so i can safely create just one variable "player1".
Problem is with enemies. In my combat scenario game will randomly generate between x and x number of enemies add that to enemies list.

To create combat inititive i would just need to create separate list do for loop to add each object from that list to that new list + player1.
Now i need to actually sort that list via self.inititive though and this is a problem.

I can't figure out how to sort list of objects based on one of the variables in that object without knowing name of variable (which is randomly generated upon creation of Enemy() )

It would be lovely for example if it could instead of random hex based name of variable generate from list of names for variables like (enemy01, enemy02 and so on) and that would be easy to sort.


Other idea i have for sorting out this problem is to create variables like enemy01, enemy02, enemy 03, enemy 04, enemy05 and made it so that amount of enemies generated in fight won't be bigger than 5 and for each randomly generated enemy object assign one of above.



Any ideas ?
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Ok looks like i figured it out myself !!
:yeah:

What i did:

first i naturally created objects and added them to list.
Then i created dictionary that will take for every object in above list as key object.name and as value object.inititative.
It gave me dictionary with keys sorted via value value from smallest to biggest number.

So what i just needed to do was to reverse order in which keys will be taken from that dictionary and then compare key to x.name in object_list

so if key == x.name then run code and thus i created turn order in which every object in object list has it's own turn
 

Declinator

Arbiter
Joined
Apr 1, 2013
Messages
542
Ehhh i have now old problem.
Can't figure out proper data handling for my game.

I have three types of data structures:

lists - which are most basic. By doing them though i need to write ton of code to compare it with either dicts or lists. sortable
dicts - good way to include stuff that gives me at least 1 additional data about something like ak74 : 20 (for damage) but it is way worse to do anything else.
classes - ideal for big data thanks to it each object can have ton of different things to it. Problem is though that of i want to proceduraly generate stuff then i can't later sort list as list of objects as variables are random hex based variables.

My main problem is though how to deal with proceduraly generated stuff.

I mean for example let's say i want to create combat scenario.
i create class that handles atributes of enemy and player.

Now i create that combat scenario and here comes problem:

I want to create initiative for my combat so later list of turns will be sorted in reverse so object with biggest initiative will have first turn.
player1 is easiest as it is static and there are no more players so i can safely create just one variable "player1".
Problem is with enemies. In my combat scenario game will randomly generate between x and x number of enemies add that to enemies list.

To create combat inititive i would just need to create separate list do for loop to add each object from that list to that new list + player1.
Now i need to actually sort that list via self.inititive though and this is a problem.

I can't figure out how to sort list of objects based on one of the variables in that object without knowing name of variable (which is randomly generated upon creation of Enemy() )

It would be lovely for example if it could instead of random hex based name of variable generate from list of names for variables like (enemy01, enemy02 and so on) and that would be easy to sort.


Other idea i have for sorting out this problem is to create variables like enemy01, enemy02, enemy 03, enemy 04, enemy05 and made it so that amount of enemies generated in fight won't be bigger than 5 and for each randomly generated enemy object assign one of above.



Any ideas ?

I'm not sure why you would need a random variable name or why the name of the variable matters at all in a list but I guess that might be something specific to Python-likes.

Normally a list of classes is sorted by an already existing sort function that should be able to be given a helper function/key by which the function sorts the list.

https://wiki.python.org/moin/HowTo/Sorting

The last example under the header "Key Functions" seems to be what you are going for.

Something like this should work and return a new sorted list:
sorted(enemy_list, key=lambda enemy: enemy.initiative)

Your dictionary solution is probably quite inefficient in comparison.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
I'm not sure why you would need a random variable name or why the name of the variable matters at all in a list but I guess that might be something specific to Python-likes.

Normally a list of classes is sorted by an already existing sort function that should be able to be given a helper function/key by which the function sorts the list.

https://wiki.python.org/moin/HowTo/Sorting

The last example under the header "Key Functions" seems to be what you are going for.

Something like this should work and return a new sorted list:
sorted(enemy_list, key=lambda enemy: enemy.initiative)

Your dictionary solution is probably quite inefficient in comparison.

Ok that is actually great !

I didn't know i can sort class objects like dictionaries lists (just with additional line lambda)

gonna read that thing now.
 

Burning Bridges

Enviado de meu SM-G3502T usando Tapatalk
Joined
Apr 21, 2006
Messages
27,562
Location
Tampon Bay
Tbh I think you got quite a few of the concepts mixed up, but that's absolutely normal at your stage.

Only when you made mistakes you will be ready for the next step which is improvement. There is now way to shortcut this phase by asking people with years of experience.

Anyway, here would be a simple combat loop in pseudo code

global:
List<> Objects
bool Combat


combat loop:
while(Combat)
{
nextObject = GetObjectWithHighestInitiative()
ResolveCombat(nextObject)
}

now you would need to implement two functions, one GetObjectWithHighestInitiative() that gives you the next object (from the global list of Objects that make up your game)
and ResolveCombat(object) that resolves the combat for this item, and you have many ways to update the Combat flag
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
I have a question. How you deal with loops ?

I mean simple gameloop looks like this:

Code:
mainloop:
    loop1:
        loop1a:
        loop1b:
            loop1aa:
    loop2:
    loop3:

but that is simple game loop. If i want to create something more complicated then i would use much more loops that would soon destroy readability of my code if i would do it in above way also it would be hard to read loop deep as 5-6 or above

Also when you write code in those loops you want to reduce code to be as minimal as it needs (via functions) or what ?

If i understand correctly i should divide different parts of game for different loops so for example gamecodeloop --- > Uiloop instead of marging two in same loop

Tbh I think you got quite a few of the concepts mixed up, but that's absolutely normal at your stage.

Only when you made mistakes you will be ready for the next step which is improvement. There is now way to shortcut this phase by asking people with years of experience.

Anyway, here would be a simple combat loop in pseudo code

global:
List<> Objects
bool Combat


combat loop:
while(Combat)
{
nextObject = GetObjectWithHighestInitiative()
ResolveCombat(nextObject)
}

now you would need to implement two functions, one GetObjectWithHighestInitiative() that gives you the next object (from the global list of Objects that make up your game)
and ResolveCombat(object) that resolves the combat for this item, and you have many ways to update the Combat flag

Hmm interesting.
 

titus

Arcane
Patron
Joined
Sep 28, 2011
Messages
1,719
Location
Romania
I'll hijack this thread again for a bit.

So, I'm working on some stuff for uni, and I needed a 2d array, to simulate a matrix. After I got a stack overflow, I went to learn about the stack and the heap. Since my matrix is big, I needed to declare it using the new operator (I'm using C++ btw), but I discover you can't declare a 2d array using new.

So I went to search around on the net, and there's loads of convoluted solutions and stuffies, but one dude suggests:

Use the keyword auto:
auto array_of_something = new something[x][y];

And it works! It seems it only works on C++11 forward, but VS2010 ain't complaining about it, so :shrugs:

Anyway, my question is, what the fuck does the auto do in this case? Because I was JUST today reading about that stuff, and the C++ primer (which is probably C++03 compliant, since it's from 2005) says auto was a keyword to tell the compiler a variable had block scope, which they do by default and it was not actually needed. I read the C++11 improvements, and there's no mention of 2d arrays working with auto now.

So, why does this work?

EDIT: And how do I call delete[] on it?

EDIT2: How do I check the size of an object made from a class I made? And how do I check the size of the stack so I have an idea if I'm close to filling it up? Also, does the stack change from machine to machine, or if I compile for a different OS?

How exactly are you declaring the array and just how big is it?
This should work as long as n*m*sizeof(int)<2gb. Or 4gb if you set /LARGEADDRESSAWARE for the linker. Assuming that your PC has 4gb of free memory, ofc.
Code:
    int **arr = new int*[1024];
    for(int i=0; i<1024; i++)
    {
        arr[i] = new int [1024];
    }
    delete [] arr;

I have a question. How you deal with loops ?

I mean simple gameloop looks like this:

Code:
mainloop:
    loop1:
        loop1a:
        loop1b:
            loop1aa:
    loop2:
    loop3:

but that is simple game loop. If i want to create something more complicated then i would use much more loops that would soon destroy readability of my code if i would do it in above way also it would be hard to read loop deep as 5-6 or above

Also when you write code in those loops you want to reduce code to be as minimal as it needs (via functions) or what ?

If i understand correctly i should divide different parts of game for different loops so for example gamecodeloop --- > Uiloop instead of marging two in same loop

self sufficient objects and lots of comments?
 

Destroid

Arcane
Joined
May 9, 2007
Messages
16,628
Location
Australia
Perkal usually it looks more like:

Code:
Main_loop
    Get_input
    Update_objects
    Render

Each of those parts is independent so while you work on one you don't have to worry about the details of the others.
 

Raghar

Arcane
Vatnik
Joined
Jul 16, 2009
Messages
22,698
Well, I don't think a beginner should bother with lambdas, but I'm glad you have fun and managing to learn stuff largely without interference.

Have you looked at a list of standard algorithms and data structures?


I don't do loops, I structure my code as finite state machines, but I'm quite unique in that. But UI is normally drawn as a mask in the last stage of GFX processing. The structure actually depends on game as a game that allows planning can use a different method than a fast paced RTS which needs quick reaction time and no latency. I normally runs 3D GFX in separate thread on separate physical core, because it simplifies programming, and reduces all FPS hiccups to zero, I communicate with it async. But for 2D games it would be a lot more coding, and more importantly a text 2D game can be made to wait on user input and SIGNIFICANTLY reduce power consumption and competition for system resources.

Another thing that can alter handling of whole game code is a third party UI library.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Hmm found a problem.

I am currently refactoring my code to make it look much better and simpler so i put most of my things in functions so i just call one function instead of writing full loop.

Problem though is that:

Code:
choice = ""

def clrscreen():
    choice = raw_input()

clrscreen()
print choice

function defined in this way doesn't seem to do with choice anything at all.
In case above it doesn't print anything but it gives me a way to type something
I feel like i am doing some dumb mistake here.


Well, I don't think a beginner should bother with lambdas, but I'm glad you have fun and managing to learn stuff largely without interference.

Have you looked at a list of standard algorithms and data structures?


I don't do loops, I structure my code as finite state machines, but I'm quite unique in that. But UI is normally drawn as a mask in the last stage of GFX processing. The structure actually depends on game as a game that allows planning can use a different method than a fast paced RTS which needs quick reaction time and no latency. I normally runs 3D GFX in separate thread on separate physical core, because it simplifies programming, and reduces all FPS hiccups to zero, I communicate with it async. But for 2D games it would be a lot more coding, and more importantly a text 2D game can be made to wait on user input and SIGNIFICANTLY reduce power consumption and competition for system resources.

Another thing that can alter handling of whole game code is a third party UI library.

You don't use loops ?

I mean without loop you can't go back to earlier part of code and fire it up once again ( i think ? )

As for 3D and stuff beside simplest libraries i don't think i should delve in that as i started my programming journey like a month ago (with a solid one week vacation in that).


Currently i am trying to create simple RPG mostly procedurally generated. This gives me ton of experience on how to deal with various problems.

Soon i will probably look for something that will give me ability to quickly do some GFX work as CMD isn't really amazing for displaying anything than one screen on non changing data

On other hand i always wondered how people deal with FPS. I mean for CMD raw_input just stops anything for enter but in 3D it needs to render everything.

Perkal usually it looks more like:

Code:
Main_loop
    Get_input
    Update_objects
    Render

Each of those parts is independent so while you work on one you don't have to worry about the details of the others.

could you elaborate more ?

render i get but getinput and update_objects is something i don't quite understand.
 
Last edited:

desocupado

Magister
Joined
Nov 17, 2008
Messages
1,802
I'll hijack this thread again for a bit.

So, I'm working on some stuff for uni, and I needed a 2d array, to simulate a matrix. After I got a stack overflow, I went to learn about the stack and the heap. Since my matrix is big, I needed to declare it using the new operator (I'm using C++ btw), but I discover you can't declare a 2d array using new.

So I went to search around on the net, and there's loads of convoluted solutions and stuffies, but one dude suggests:

Use the keyword auto:
auto array_of_something = new something[x][y];

And it works! It seems it only works on C++11 forward, but VS2010 ain't complaining about it, so :shrugs:

Anyway, my question is, what the fuck does the auto do in this case? Because I was JUST today reading about that stuff, and the C++ primer (which is probably C++03 compliant, since it's from 2005) says auto was a keyword to tell the compiler a variable had block scope, which they do by default and it was not actually needed. I read the C++11 improvements, and there's no mention of 2d arrays working with auto now.

So, why does this work?

EDIT: And how do I call delete[] on it?

EDIT2: How do I check the size of an object made from a class I made? And how do I check the size of the stack so I have an idea if I'm close to filling it up? Also, does the stack change from machine to machine, or if I compile for a different OS?

How exactly are you declaring the array and just how big is it?
This should work as long as n*m*sizeof(int)<2gb. Or 4gb if you set /LARGEADDRESSAWARE for the linker. Assuming that your PC has 4gb of free memory, ofc.
Code:
    int **arr = new int*[1024];
    for(int i=0; i<1024; i++)
    {
        arr[i] = new int [1024];
    }
    delete [] arr;

It's a 250x250 matrix of objects derived from the Elemento_dA class I made. I was declaring it like this:
Elemento_dA matriz_mat[size2][size2];

size2 being a constant I defined elsewhere;

It's weird, because the program hardly uses 20 megs of memory when I look it up on task manager.

After I started using the new operator, the program is allowing me much bigger sizes. A 10000x10000 matriz is using almost 800 megs of ram.
 
Last edited:

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
Hmm found a problem.

I am currently refactoring my code to make it look much better and simpler so i put most of my things in functions so i just call one function instead of writing full loop.

Problem though is that:

Code:
choice = ""

def clrscreen():
    choice = raw_input()

clrscreen()
print choice

function defined in this way doesn't seem to do with choice anything at all.
In case above it doesn't print anything but it gives me a way to type something
I feel like i am doing some dumb mistake here.

Why not do this instead:

Code:
def clrscreen():
    return raw_input()

choice = clrscreen()
print choice
 

Niektory

one of some
Patron
Joined
Mar 15, 2005
Messages
808
Location
the great potato in the sky
Hmm found a problem.

I am currently refactoring my code to make it look much better and simpler so i put most of my things in functions so i just call one function instead of writing full loop.

Problem though is that:

Code:
choice = ""

def clrscreen():
    choice = raw_input()

clrscreen()
print choice

function defined in this way doesn't seem to do with choice anything at all.
In case above it doesn't print anything but it gives me a way to type something
I feel like i am doing some dumb mistake here.
The problem here is that there are actually 2 separate variables named choice. One is defined in the global namespace. The other inside a function, in a local namespace, and is discarded (goes out of scope) when the function ends. You should read up about scopes and namespaces to understand this.
In general you should avoid using global variables inside functions. Usually data that a function needs should be passed in parameters, and results should be returned with the return keyword.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Why not do this instead:

Code:
def clrscreen():
    return raw_input()

choice = clrscreen()
print choice

i knew i was dumb :M

The problem here is that there are actually 2 separate variables named choice. One is defined in the global namespace. The other inside a function, in a local namespace, and is discarded (goes out of scope) when the function ends. You should read up about scopes and namespaces to understand this.
In general you should avoid using global variables inside functions. Usually data that a function needs should be passed in parameters, and results should be returned with the return keyword.

thanks.
 

Destroid

Arcane
Joined
May 9, 2007
Messages
16,628
Location
Australia
Perkal usually it looks more like:

Code:
Main_loop
    Get_input
    Update_objects
    Render

Each of those parts is independent so while you work on one you don't have to worry about the details of the others.

could you elaborate more ?

render i get but getinput and update_objects is something i don't quite understand.

With Get_input, you handle the inputs from the user, keystrokes, mouse, touch etc. In update, you update the state of your game, move characters around, trigger animations, remove things that have died, things like that.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
now i have a bit different problem...

i know i can't sort dict generally but i read that if i use for example sorted it should be possible.

So i wrote :

Code:
data = {'quit': 4,
        'new game': 1,
        'continue': 2,
        'cheats': 3}

print sorted(data, key=lambda x: x[1])

but it doesn't return me :

new game
continue
cheats
quit

but:

new game
cheats
continue
quit

It does sort dict but in weird way. I guess this way i can't sort dict ?


edit:

hmm i can't seem to sort it that way without going around it with import operator - > creating organized list of options from that dict and print it that way...

any other suggestions ?
 
Last edited:

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
now i have a bit different problem...

i know i can't sort dict generally but i read that if i use for example sorted it should be possible.

So i wrote :

Code:
data = {'quit': 4,
        'new game': 1,
        'continue': 2,
        'cheats': 3}

print sorted(data, key=lambda x: x[1])

but it doesn't return me :

new game
continue
cheats
quit

but:

new game
cheats
continue
quit

It does sort dict but in weird way. I guess this way i can't sort dict ?


edit:

hmm i can't seem to sort it that way without going around it with import operator - > creating organized list of options from that dict and print it that way...

any other suggestions ?

This should work:

Code:
data = {'quit': 4,
        'new game': 1,
        'continue': 2,
        'cheats': 3}

print sorted(data.items(), key=lambda x: x[1])

What you will get is a list of tuples/pairs and you probably want only the keys so you can get that by doing this:

Code:
print [x[0] for x in sorted(data.items(), key=lambda x: x[1])]

What your code does is the following:
it iterates over data keys, each key is then passed to 'key' function = lambda x: x[1]. What this does is extracts the second letter of your string key and uses that for comparison. You can check that by renaming the key 'quit' to 'qait' at will be first when sorted.

Edit: Have you looked into list comprehensions? If not I suggest you check that otherwise the above syntax in my second print will be strange to you.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
This should work:

Code:
data = {'quit': 4,
        'new game': 1,
        'continue': 2,
        'cheats': 3}

print sorted(data.items(), key=lambda x: x[1])

What you will get is a list of tuples/pairs and you probably want only the keys so you can get that by doing this:

Code:
print [x[0] for x in sorted(data.items(), key=lambda x: x[1])]

What your code does is the following:
it iterates over data keys, each key is then passed to 'key' function = lambda x: x[1]. What this does is extracts the second letter of your string key and uses that for comparison. You can check that by renaming the key 'quit' to 'qait' at will be first when sorted.

Edit: Have you looked into list comprehensions? If not I suggest you check that otherwise the above syntax in my second print will be strange to you.

Thanks. Everyday something awesome new thing to learn.

edit: proper syntax of above :
Code:
for x in sorted(data.items(), key=lambda x: x[1]):
    print x[0]

fully tested and works like a charm thanks !
 
Last edited:

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
edit: proper syntax of above :
Code:
for x in sorted(data.items(), key=lambda x: x[1]):
    print x[0]

fully tested and works like a charm thanks !

Btw if you wanted newlines between members of the list you can do this:

Code:
print '\n'.join(items)

Method join will take the seperator string and an iterable collection and create a string joined with the seperator. So
Code:
 'S'.join(items)
would join each element in items with S between them. Elements need to be strings.

For your exampe it would be
Code:
print '\n'.join([x[0] for x in sorted(data.items(), key=lambda x: x[1])])
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Ok something doesn't work properly:

Code:
cities = rand...
villaes = rand..
....

def worldgen():
    placesx = []
    for x in range(0, cities):
        newplace = PlaceCity()
        placesx.append(newplace)
    for x in range(0, villages):
        newplace = PlaceVillage()
        placesx.append(newplace)
    for x in range(0, bases):
        newplace = PlaceBase()
        placesx.append(newplace)
    for x in range(0, others):
        newplace = PlaceOther()
        placesx.append(newplace)
    return placesx

places = worldgen()

Above code works like a charm for one "for x" but when i place 4 of them it gives me an error.
 

7h30n

Augur
Joined
Aug 14, 2012
Messages
311
What error? It would be good each time you get an error don't say that you got it but also post it here (in spoiler/code tags).
By the looks of it you have villaes = rand.. and call in worldgen villages.
 

Perkel

Arcane
Joined
Mar 28, 2014
Messages
15,875
Traceback (most recent call last):

File "D:/Coding/Projects/PyCharm/Vendor/The Glow.py", line 299, in <module>
places = worldgen()
File "D:/Coding/Projects/PyCharm/Vendor/The Glow.py", line 113, in worldgen
newplace = PlaceVillage()
File "D:/Coding/Projects/PyCharm/Vendor/The Glow.py", line 141, in __init__
new_enemy = Enemy()
File "D:/Coding/Projects/PyCharm/Vendor/The Glow.py", line 253, in __init__
self.weapon = random.choice(weapons)
File "D:\Coding\Installed Programs\Languages\Python 2.7.8\lib\random.py", line 275, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
KeyError: 1
 

As an Amazon Associate, rpgcodex.net earns from qualifying purchases.
Back
Top Bottom