• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Exuro

Member
I think I understand what you're asking for and you're looking at the solution for virtual memory. You shift pages into physical memory from storage to pretend like you have 4 GB of physical memory.
Why would you need to pretend? Is there an advantage in having 0 valid bit pages in the page table rather than evicting them?
 

Garcia

Member
Newbie question:

Does it really matter which language you choose to learn first? I'm learning Java but was wondering if there will be any benefits if I simultaneously learn C++. What's your opinion on the subject, codeGAF? Thanks in advance.
 

tokkun

Member
Why would you need to pretend? Is there an advantage in having 0 valid bit pages in the page table rather than evicting them?

You pretend that you have 4GB of memory regardless of your actual physical memory because you want to give the same address space to a program regardless of how much physical memory is available in the system.

From a 32-bit program's point of view, it always has access to 4GB of memory. This makes it a lot easier to write programs and compilers, because you don't need to worry about having a separate version of your program for computers with less memory or to deal with multi-tasking, where some of the memory is being used by another process.

The key here is that it is possible for only some of the 4GB to be in physical memory, and have the rest refer to locations on a hard drive. The page table keeps track of whether a memory page is actually resident in physical memory or if it on the disk. If the program tries to access a page that is not in physical memory, then a mechanism (in the olden days a piece of hardware, nowadays usually the operating system) is invoked that brings the page into physical memory and kicks one of the existing pages out to disk. The page table is then updated with the new information.

Newbie question:

Does it really matter which language you choose to learn first? I'm learning Java but was wondering if there will be any benefits if I simultaneously learn C++. What's your opinion on the subject, codeGAF? Thanks in advance.

Unless you have a compelling reason, I would stick with one language as a beginner, so you don't get confused with small differences in syntax and semantics. The important part of learning your first language is understanding how to structure a program, translate an algorithm into into control flow, and how to select data structures to accomplish a task. That does not require a specific language. Once you are more experienced, it makes sense to take a survey of different languages and see what they offer.

There are important differences between C++ and Java, but they are not beginner-level topics.
 
Thanks for the suggestions so far!

Speaking of, I find that regardless of what music I'm listening to there are times where I have to mute everything. Generally when I'm focusing on a really tricky or complicated problem. Anybody else experience this, or are you able to tune out the music when you need 100% concentration?
If I've been listening to something as I've gotten sucked into a problem, it naturally just fades out of focus for me (I feel like everything fades out as I get absorbed) and I can handle it, but if I'm diving into something challenging cold I definitely can't deal with music on in the background.
 

iapetus

Scary Euro Man
Newbie question:

Does it really matter which language you choose to learn first?

Yes.

Which language you learn first is likely to colour your programming style for some time. Also, some languages are easier to use as first languages than others; Java certainly isn't at the top of the easy pile, but it's not at the bottom of it either. It's a kind of middling language for learning.

I wouldn't recommend my personal path into coding these days (BASIC followed by 6502 assembler, a little Z80, ARM assembler and then C), awesome as it was. But there are better ways in these days; starting with a fairly straightforward language that lets you get straight down to the coding basics as quickly as possible (Java just requires too much structure), then on to the more practical languages for real world use.

I'm learning Java but was wondering if there will be any benefits if I simultaneously learn C++. What's your opinion on the subject, codeGAF? Thanks in advance.

I think it's a terrible idea. Firstly, as others have said, sticking to one language to start with will help. Secondly, C++ and Java are just too similar - but very different in some ways. You'd be trying to learn the same things with the same syntax but fundamentally different approaches in other places. It's just confusing. If you really felt the need to learn two languages, I'd go for something completely different as a second language. Prolog, anyone? :D But seriously, I'd go with one language at a time. If Java's where you're committed to starting, start with Java. Once you've got a solid grasp on it, then you can begin to branch out.
 

Garcia

Member
The important part of learning your first language is understanding how to structure a program, translate an algorithm into into control flow, and how to select data structures to accomplish a task.

Yes.

Which language you learn first is likely to colour your programming style for some time. Also, some languages are easier to use as first languages than others.

I think it's a terrible idea. Firstly, as others have said, sticking to one language to start with will help. Secondly, C++ and Java are just too similar - but very different in some ways.

But seriously, I'd go with one language at a time. If Java's where you're committed to starting, start with Java. Once you've got a solid grasp on it, then you can begin to branch out.

Thank you so much. Very generous advice! Right now I'm taking Stanford's CS106A course online (Youtube Videos, handout/assignments done in Eclipse) and so far the experience has been rewarding. Some people in the comments section mention C++ from time to time and I was just wondering if there were any real benefits in learning 2 at a time.

It really makes sense to put your focus on one language before you start moving to another.

I appreciate your input, guys.
 

Billen

Banned
Yes.

Which language you learn first is likely to colour your programming style for some time. Also, some languages are easier to use as first languages than others; Java certainly isn't at the top of the easy pile, but it's not at the bottom of it either. It's a kind of middling language for learning.

I wouldn't recommend my personal path into coding these days (BASIC followed by 6502 assembler, a little Z80, ARM assembler and then C), awesome as it was. But there are better ways in these days; starting with a fairly straightforward language that lets you get straight down to the coding basics as quickly as possible (Java just requires too much structure), then on to the more practical languages for real world use.



I think it's a terrible idea. Firstly, as others have said, sticking to one language to start with will help. Secondly, C++ and Java are just too similar - but very different in some ways. You'd be trying to learn the same things with the same syntax but fundamentally different approaches in other places. It's just confusing. If you really felt the need to learn two languages, I'd go for something completely different as a second language. Prolog, anyone? :D But seriously, I'd go with one language at a time. If Java's where you're committed to starting, start with Java. Once you've got a solid grasp on it, then you can begin to branch out.

I got curious as you mention some are easier as first than others. If Java is neither top nor bottom, and C++ is very similar, which ones are easier? C#? Python? Pull out the TI 99/4A and plug in the extended basic cartridge?? :D
 

oxrock

Gravity is a myth, the Earth SUCKS!
I got curious as you mention some are easier as first than others. If Java is neither top nor bottom, and C++ is very similar, which ones are easier? C#? Python? Pull out the TI 99/4A and plug in the extended basic cartridge?? :D

I meddled around in a few languages before finally picking to start with python. I have no regrets. Personally not a fan of the newer releases though, 2.7 for life!
 

Billen

Banned
I meddled around in a few languages before finally picking to start with python. I have no regrets. Personally not a fan of the newer releases though, 2.7 for life!

Are there any similarities between python and other languages such as C#, or is it a standalone experience meant for jungle survivors, kamikaze pilots and/or astronauts?
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Are there any similarities between python and other languages such as C#, or is it a standalone experience meant for jungle survivors, kamikaze pilots and/or astronauts?

Python has really simple syntax, and is more of a scripting language from what I understand. I have only had minor experience with it myself.

Lots of people recommend learning it as a first language, and a lot of university courses have switched, or are in the process of switching over to Python for their introductory classes.
 

Billen

Banned
Python has really simple syntax, and is more of a scripting language from what I understand. I have only had minor experience with it myself.

Lots of people recommend learning it as a first language, and a lot of university courses have switched, or are in the process of switching over to Python for their introductory classes.

Quite interesting, thanks. I think I will have a go at codecademys python for fun.
 
I find video game soundtracks are often really good for me. Probably because they're generally meant to be background music, so they aren't too distracting for me. I can't program to anything with lyrics...

Speaking of, I find that regardless of what music I'm listening to there are times where I have to mute everything. Generally when I'm focusing on a really tricky or complicated problem. Anybody else experience this, or are you able to tune out the music when you need 100% concentration?

I actually saw a study that said that VideoGame music is good for productivity for this exact reason. Its meant to be in the background and to not interrupt your concentration on other tasks. At least earlier game music, I dunno about more modern stuff.

I can only really program to lyrical stuff if its something I've heard like a 1000 times. I find uptempo punk/metal/ska to all help because they energy music. I generally find electronic music to be too grating on my ears to really focus while listening too.
 

oxrock

Gravity is a myth, the Earth SUCKS!
Are there any similarities between python and other languages such as C#, or is it a standalone experience meant for jungle survivors, kamikaze pilots and/or astronauts?

Outside of basic operations you see in most languages, not really. Python is really more of a cut out the fluff kind of language. The great thing is that you don't need curly brackets every 3 seconds, the bad part is that it's crazy anal about spacing. You don't need to have any sort of header for instance. You just introduce your variables (which you don't even have to label the type) and then get to your functions. That being said, the thinking and the methods learned for attacking problems can easily be carried over into other languages. I've been digging deeper and deeper into c# lately because I'm using unity and at no point do I find myself wishing I'd chosen a different base than python. It has similar syntax's, I just find python's versions less annoying. And on a side note, I enjoy being able to introduce variables any damn where I please, coding grammar and aesthetics be damned!
 

Water

Member
This is driving me mad. What's the name of the sort of aliasing that texture filtering is supposed to fix?
Maybe the name you are looking for is "Moire pattern"? Not all texture aliasing is Moire though, and I'm not aware of any simple general name.

The general description would be something like "aliasing due to undersampling texture data or having too little data to sample".
 

oxrock

Gravity is a myth, the Earth SUCKS!
Quite interesting, thanks. I think I will have a go at codecademys python for fun.

Udacity has a video learning course for python where they give you tests constantly to check your code. After every test there's a video explaining how to do the test, how it worked, etc. So even if you didn't understand it to begin with, you understand it after. Over the length of the course you make an internet search engine which I thought was pretty cool. It begins slow, it's meant for complete beginners but I found it very helpful when I went through it.
 

hateradio

The Most Dangerous Yes Man
Are there any similarities between python and other languages such as C#, or is it a standalone experience meant for jungle survivors, kamikaze pilots and/or astronauts?
They're both Object Oriented and can do some functional things, but besides that, the style is different.

Ruby is a close cousin of Python, and I tend to like it more. There's also Groovy (for the JVM) and Boo (for .NET) that are meant to be more similar to Ruby/Python.
 

Tamanon

Banned
Udacity has a video learning course for python where they give you tests constantly to check your code. After every test there's a video explaining how to do the test, how it worked, etc. So even if you didn't understand it to begin with, you understand it after. Over the length of the course you make an internet search engine which I thought was pretty cool. It begins slow, it's meant for complete beginners but I found it very helpful when I went through it.

Seconding the recommendation on this course. Also they have another one that focuses on taking Python and building a web app using Google App Engine which is also pretty nice.
 

Chuckpebble

Member
Going through the Apple Dev sight and I get to this:
programflow4.png

XYZShoutingPerson inherits from XYZPerson which inherits from NSObject.
sayHello is a public interface and saySomething is not.
The line at step 3 throws up an error at compile time about there being no visible @interface for the saySomething method within the XYZPerson object. I can easily add that method to the interface file, but the text lead me to believe it could stay private and work.

What gives?
 

Billen

Banned
I would just like to thank you guys giving advice here. Really some interesting information. I have always wanted to learn some languages, partly due to interest but also to be able to solve some practical troubles I encounter at work etc.

Mostly just because it just seems so damn fun though, and I have no fucking clue as to why I haven't done it yet. I just work, and there you face the standard vb scripting, powershell etc. Once again, really thankful for the pointers here.
 
They're both Object Oriented and can do some functional things, but besides that, the style is different.

Ruby is a close cousin of Python, and I tend to like it more. There's also Groovy (for the JVM) and Boo (for .NET) that are meant to be more similar to Ruby/Python.

You can also program Python on .NET with IronPython. I've never seriously tried it, but it seems like a cool idea.
 
Okay so I am refreshing some of my C++ knowledge and fooling around with a few examples I found.

One of them is to ask for a name (console based) and "dynamically" adjust the output to have the name surrounded by '*'. Now this works until I use Umlaute (???) like ä, ö, ü, ß because then the output gets messed up by 1 space. So far I figured out this is because I the size those take is different to normal letters. I thought I could just use:

Code:
int num = std::count(name.begin(), name.end(), 'ö');

for each Umlaut and then use a if-else code to adjust the "greeting" output from "_*" to "__*". But it doesn't work. Compiler warns me about multi-char issues probably becaue of the Umlaute and I am not really sure if that would work anyway. num stays 0 no matter what I enter. Could someone please point me in the right direction?

Whole code (without any Umlaut countermeasures):

Code:
#include <iostream>
#include <string>

// need that for std::count
#include <algorithm>

int main()
{
  // Name input
  std::cout << "Please enter your first name: ";
  std::string name;
  std::cin >> name;

  // Construct the output lines
  const std::string greeting = "Hello, " + name + "!";
  const std::string spaces(greeting.size(), ' ');
  const std::string second = "* " + spaces + " *";
  const std::string first(second.size(), '*');
  
  // not working
  // int num = std::count(name.begin(), name.end(), 'ö');

  // Output
  std::cout << std::endl;
  std::cout << first << std::endl;
  std::cout << second << std::endl;
  std::cout << "* " << greeting << " *" << std::endl;
  std::cout << second << std::endl;
  std::cout << first << std::endl;

  return 0;
}
 

Water

Member
One of them is to ask for a name (console based) and "dynamically" adjust the output to have the name surrounded by '*'. Now this works until I use Umlaute (???) like ä, ö, ü, ß because then the output gets messed up by 1 space. So far I figured out this is because I the size those take is different to normal letters.
There's no simple trick. A C++ string doesn't consider the encoding of the data inside, e.g. UTF8 using more than one character in the string data to represent the real character. So if you use any non-ASCII characters, to find out the length of a string in real characters you essentially have to define what the string's encoding is and convert to a wide character string where every real character is represented by one piece of data. Then the size() of the string equals the real length. Standard library does offer some means of doing that. This works in C++11 (tested on clang compiler):
Code:
#include <codecvt>
...
using namespace std;
string utf8 = u8"aöä";
cout << "Byte length: " << utf8.size() << endl; // 5
wstring_convert<codecvt_utf8<char32_t>, char32_t> conv;
u32string converted = conv.from_bytes(utf8);
cout << "Character length: " << converted.size() << endl; // 3
http://rosettacode.org/wiki/String_length#C.2B.2B
 

0xCA2

Member
What is the name or author of the book?

Starting out With Programming Logic and Design, Tony Gaddis.

I don't know if it was special in how understandable it was, any beginning programming logic book might do.

Anyway, I have a question about game development that has been baffling me.

Many of the game programming tutorials that I've seen haven't touched on how to add logic to to specific parts of a game after loading in data about a level. So lets say I wanted to have Level1, Level2 etc each with different things that happen based on different conditions. Would I just have to make a program for each level?

So, for example,
- In Level 1, if you shoot 5 enemies the game is over
- In Level 2, if you didn't find the key from level 1, then you can't get the special weapon, etc

And extrapolating out to more complex things, not with level based games but games with rooms that are displayed differently based on whether or not you have an item or whether or not you did something. I've got the "read data in the file about what should be in a room and where and place those things" part, but I can't wrap my head around how I would add conditions to that without creating separate small programs for each room. Which I'm realizing now is probably the way this is done ( I don't know, the idea of having a bunch of separate Classes (in java terms ) for each level/room instead of one that handled them all didn't seem right, maybe I'm overthinking this?).
 
Going through the Apple Dev sight and I get to this:
programflow4.png

XYZShoutingPerson inherits from XYZPerson which inherits from NSObject.
sayHello is a public interface and saySomething is not.
The line at step 3 throws up an error at compile time about there being no visible @interface for the saySomething method within the XYZPerson object. I can easily add that method to the interface file, but the text lead me to believe it could stay private and work.

What gives?

Which version of XCode are you using? I think this changed around 4.3 but I could be wrong.

Anywho, all you should have to do is make the header for XYZPerson.h look like this:

Code:
@interface XYZPerson : NSObject
- (void)saySomething:(NSString*)greeting;
@end

For it to compile and link properly.

Also slightly similar question on the same source code from awhile back: http://stackoverflow.com/questions/...interface-for-xyzperson-declares-the-selector
 

Big Chungus

Member
About to go crazy, one of the last assignments in my C class is we have to manipulate bmp image data.

I'm a horrible programmer and so far i'm finding this the most difficult assignment ever.
 

upandaway

Member
Starting out With Programming Logic and Design, Tony Gaddis.

I don't know if it was special in how understandable it was, any beginning programming logic book might do.

Anyway, I have a question about game development that has been baffling me.

Many of the game programming tutorials that I've seen haven't touched on how to add logic to to specific parts of a game after loading in data about a level. So lets say I wanted to have Level1, Level2 etc each with different things that happen based on different conditions. Would I just have to make a program for each level?

So, for example,
- In Level 1, if you shoot 5 enemies the game is over
- In Level 2, if you didn't find the key from level 1, then you can't get the special weapon, etc

And extrapolating out to more complex things, not with level based games but games with rooms that are displayed differently based on whether or not you have an item or whether or not you did something. I've got the "read data in the file about what should be in a room and where and place those things" part, but I can't wrap my head around how I would add conditions to that without creating separate small programs for each room. Which I'm realizing now is probably the way this is done ( I don't know, the idea of having a bunch of separate Classes (in java terms ) for each level/room instead of one that handled them all didn't seem right, maybe I'm overthinking this?).
You could do it by having a separate set of Condition objects that each specify a different winning condition (similar to Comparator in Java). I think having each level in a different class is good but if you need them in the same class somehow, just take the conditions outside.
 
There's no simple trick. A C++ string doesn't consider the encoding of the data inside, e.g. UTF8 using more than one character in the string data to represent the real character. So if you use any non-ASCII characters, to find out the length of a string in real characters you essentially have to define what the string's encoding is and convert to a wide character string where every real character is represented by one piece of data. Then the size() of the string equals the real length. Standard library does offer some means of doing that. This works in C++11 (tested on clang compiler):
Code:
#include <codecvt>
...
using namespace std;
string utf8 = u8"aöä";
cout << "Byte length: " << utf8.size() << endl; // 5
wstring_convert<codecvt_utf8<char32_t>, char32_t> conv;
u32string converted = conv.from_bytes(utf8);
cout << "Character length: " << converted.size() << endl; // 3
http://rosettacode.org/wiki/String_length#C.2B.2B

Thank you for the information. I will sit down this afternoon and look how far I get. Seems like a small oversight to not include the different character encodings.
 
Starting out With Programming Logic and Design, Tony Gaddis.

I don't know if it was special in how understandable it was, any beginning programming logic book might do.

Anyway, I have a question about game development that has been baffling me.

Many of the game programming tutorials that I've seen haven't touched on how to add logic to to specific parts of a game after loading in data about a level. So lets say I wanted to have Level1, Level2 etc each with different things that happen based on different conditions. Would I just have to make a program for each level?

So, for example,
- In Level 1, if you shoot 5 enemies the game is over
- In Level 2, if you didn't find the key from level 1, then you can't get the special weapon, etc

And extrapolating out to more complex things, not with level based games but games with rooms that are displayed differently based on whether or not you have an item or whether or not you did something. I've got the "read data in the file about what should be in a room and where and place those things" part, but I can't wrap my head around how I would add conditions to that without creating separate small programs for each room. Which I'm realizing now is probably the way this is done ( I don't know, the idea of having a bunch of separate Classes (in java terms ) for each level/room instead of one that handled them all didn't seem right, maybe I'm overthinking this?).

If the only thing that changes between levels is the end condition (has the player finished the level?) then it would be a good solution to make something like upandaway suggested. Make an interface like this:
Code:
interface LevelFinishedPredicate {
	public boolean finishedLevel(Level l, Player p);
}
This assumes that you have a player class that you can pass around. In the Level class, you need to save this as an instance member and check the finished() method in each call to the Level's update method:
Code:
class Level {
	// members
	private LevelFinishedPredicate predicate;

	public Level(..., LevelFinishedPredicate p) {
		predicate = p;
	}

	public void update(float dt) {
		//.. logic ..

		boolean finished = predicate.finishedLevel(this, GameState.getPlayer());
		if (finished) {
			// ...
		}
		else {
			// ...
		}
	}
}
The other way would be to make an abstract class or interface for Level and then implement this for each new level.
 

Water

Member
Thank you for the information. I will sit down this afternoon and look how far I get. Seems like a small oversight to not include the different character encodings.
Awful oversight, really. It's absurdly hard for a newbie to get this stuff right in C++. I'm not sure what the good solution would be at this point... probably to have a separate std::ucstring class for Unicode strings. The other way would be to add functionality to std::string to handle iterating Unicode stuff, checking Unicode length, taking substrings with Unicode indices etc., but that would allow very easily making a mistake and using the normal functions without the compiler being able to warn you.
 

0xCA2

Member
Thanks for the replies, though i feel i didnt explain myself well. I'm not necesarily talking specifics, i mean generally:

How are triggers, conditions, events (not referring to user input) done in games?

I was working off of the assumption that everything everything about a level or area is loaded in from some sort of file, including the triggers, conditions and events. Is that true? And if so, how?

In game programming, does each level/room/area typically have its own class(java) to handle the triggers, conditions and events?
 
Thanks for the replies, though i feel i didnt explain myself well. I'm not necesarily talking specifics, i mean generally:

How are triggers, conditions, events (not referring to user input) done in games?

I was working off of the assumption that everything everything about a level or area is loaded in from some sort of file, including the triggers, conditions and events. Is that true? And if so, how?

In game programming, does each level/room/area typically have its own class(java) to handle the triggers, conditions and events?

In Unity it is quite simple. Usually have a GameState script which handles global variables. Every gameobject has a script which tells it what to do and each method is called at appropriate times. Everything in the Update method is called once a frame, onTriggerEnter/Exit, onDestroy etc. You can have multiple scripts on each object and can reuse scripts. Each level can have a scene file which has its own gameobjects/scripts.
 

upandaway

Member
Thanks for the replies, though i feel i didnt explain myself well. I'm not necesarily talking specifics, i mean generally:

How are triggers, conditions, events (not referring to user input) done in games?

I was working off of the assumption that everything everything about a level or area is loaded in from some sort of file, including the triggers, conditions and events. Is that true? And if so, how?

In game programming, does each level/room/area typically have its own class(java) to handle the triggers, conditions and events?
Well think about it logically, to have the conditions and triggers not be in compile time, you'd basically have to create your own mini scripting language for the text files. It would be a mess to expand the scripting potential later, too, where you can just create a new class otherwise.

For levels as their own classes it's your call, but generally levels are a sum of multiple files like tiles and sounds and stuff. So you'd either have a text file which is a bunch of names or filepaths, or have specific level abstraction in the code. I think having it in the code is more flexible, say your text file parser assumes levels have one music track but later you decide you want just one level with two, and you didn't have the foresight for such an insane idea before. You'd have to refactor the parser and have a special tell for levels with two music tracks, and also a way to play both and in what way, instead of just having a new class for the level.

But yeah this is only if you're doing an engine from scratch, engines like unity have their own abstractions for these things.
 

Water

Member
How are triggers, conditions, events (not referring to user input) done in games?

I was working off of the assumption that everything everything about a level or area is loaded in from some sort of file, including the triggers, conditions and events. Is that true? And if so, how?

In game programming, does each level/room/area typically have its own class(java) to handle the triggers, conditions and events?
You have the right intuition; individual levels should definitely not have their own classes full of logic. Don't repeat yourself. You write code once, and then use it everywhere it needs to be used. You separate the data from the code. Rule X may be code, but "Rule X exists in Level Y with parameter Z" is data. So code that loads Level Y should look up which rules Level Y should have, and plug the code of those rules into the game logic temporarily. How that happens exactly depends on the game. The key question is: what input does the rule need, and how does it need to affect the game state?

In the example you gave, "if you shoot 5 enemies the game is over", the code for the rule needs to know when an enemy is shot, and it needs to be able to stop the game somehow. You could hardcode a notion of a "game-stopping rule" into the game logic like in edge's suggestion; that's simple and allows you to have different "game-stopping rules" per level, but still has the weakness that part of the rule is inside main logic. The main logic has to know and care about this specific kind of rule, and also contains an unnecessary assumption that only one rule may cause a game over. When more rules and rule types are created in this way, the main logic can become bloated and hard to maintain; not OK for a more complicated game. By adding abstraction, you can keep the main logic clean. For instance, you could have a "MessageManager" object that transmits messages. When level loading code creates a rule (let's say they are encapsulated in classes implementing an interface called "Rule") they will register themselves to MessageManager for receiving messages; that can be as simple as the Rule being added to a list inside MessageManager. The "ShootEnemiesToGameOver" rule will particularly want to listen/react to "EnemyShot" messages, and when it has gotten enough of them, it will trigger game over by calling some function somewhere, or even by sending out a "GameOver" message.

Note that the information of which rules belong to individual levels can be hardcoded inside the code that loads levels (again, fine for small projects with few rules), or they can be parsed from the level data file, or a combination of these.
 

Water

Member
Well think about it logically, to have the conditions and triggers not be in compile time, you'd basically have to create your own mini scripting language for the text files. It would be a mess to expand the scripting potential later, too, where you can just create a new class otherwise.
Being able to script your game on the fly is very valuable. Of course you should be careful not to waste time making your scripting too complicated; at some point it stops paying off and you should instead embed a well thought out existing scripting language like Lua. Then there's the possibility of using the same language as your main code for dynamic scripts; trivially easy if you happen to be working in Python, Ruby, Javascript etc. in the first place.
 

CrankyJay

Banned
Any MVC pros here? Trying to make a form that is bound to a model with a parent class that has a list of child classes. Basically I want to be able to add or delete these children with an add or delete button.

Right now I have an Ajax link that makes an asynchronous call back to the controller that returns a partial view (some argue that editor templates are better for this).

My problem is when I submit the entire form none of the child elements are bound to the days model do everything is null on the postback.
 

upandaway

Member
You have the right intuition; individual levels should definitely not have their own classes full of logic. Don't repeat yourself. You write code once, and then use it everywhere it needs to be used. You separate the data from the code. Rule X may be code, but "Rule X exists in Level Y with parameter Z" is data. So code that loads Level Y should look up which rules Level Y should have, and plug the code of those rules into the game logic temporarily. How that happens exactly depends on the game. The key question is: what input does the rule need, and how does it need to affect the game state?
For the record that's what I meant too but I think he's also asking whether to have all the data loaded from one file, or have, like, a class that gives itself the filepaths and names in the constructor. The logic should all be tucked away but having a standardized data file for each level can be limiting unless he gets the format perfect the first time, if he's trying to read from a text file he created himself.
Somewhere in the code you have to specify which level comes where anyway, so I don't think it makes a big difference whether you're creating an object for the level or loading a general file for it (in addition to all the other data files).

About your second paragraph it's pretty much what I was doing, so that makes me happy. As in having a different object manage the different logic clauses of the level.

Being able to script your game on the fly is very valuable. Of course you should be careful not to waste time making your scripting too complicated; at some point it stops paying off and you should instead embed a well thought out existing scripting language like Lua. Then there's the possibility of using the same language as your main code for dynamic scripts; trivially easy if you happen to be working in Python, Ruby, Javascript etc. in the first place.
Is it really a good idea to go that way for a small project? He could gain a lot more just by finishing the project faster without that and focus on it for something bigger.
 

0xCA2

Member
You have the right intuition; individual levels should definitely not have their own classes full of logic. Don't repeat yourself. You write code once, and then use it everywhere it needs to be used. You separate the data from the code. Rule X may be code, but "Rule X exists in Level Y with parameter Z" is data. So code that loads Level Y should look up which rules Level Y should have, and plug the code of those rules into the game logic temporarily. How that happens exactly depends on the game. The key question is: what input does the rule need, and how does it need to affect the game state?

In the example you gave, "if you shoot 5 enemies the game is over", the code for the rule needs to know when an enemy is shot, and it needs to be able to stop the game somehow. You could hardcode a notion of a "game-stopping rule" into the game logic like in edge's suggestion; that's simple and allows you to have different "game-stopping rules" per level, but still has the weakness that part of the rule is inside main logic. The main logic has to know and care about this specific kind of rule, and also contains an unnecessary assumption that only one rule may cause a game over. When more rules and rule types are created in this way, the main logic can become bloated and hard to maintain; not OK for a more complicated game. By adding abstraction, you can keep the main logic clean. For instance, you could have a "MessageManager" object that transmits messages. When level loading code creates a rule (let's say they are encapsulated in classes implementing an interface called "Rule") they will register themselves to MessageManager for receiving messages; that can be as simple as the Rule being added to a list inside MessageManager. The "ShootEnemiesToGameOver" rule will particularly want to listen/react to "EnemyShot" messages, and when it has gotten enough of them, it will trigger game over by calling some function somewhere, or even by sending out a "GameOver" message.

Note that the information of which rules belong to individual levels can be hardcoded inside the code that loads levels (again, fine for small projects with few rules), or they can be parsed from the level data file, or a combination of these.

Thanks for this, because none of the game tutorials I've read (including a book) have touched on this.

Could you give an example of how this happens? How would I plug the code of the rules into the game logic temporarily?

Also, are we talking make an abstract class for Rules, and then make a specific class for each rule, and then having a line in the text file that tells the game to create an object for that specific class? I feel like since rules can get pretty specific, wouldn't this just lead to a bunch of rule objects, and if so is that okay?

I just can't wrap my head around how you could have could have conditions in a text file that are executed by the program. Should I just use something like Rhino or Beanshell? Though I'm not exactly sure how, it seems like maybe an external scripting language could solve this problem.

Also, what do you mean here?
 
N

NinjaFridge

Unconfirmed Member
Need some java help. I need to take a string that the user inputs then take each char of the string, get the ascii value for it and pass that value into a for loop I have already made. It's been years since I've touched Java so I'm pretty lost.
 

Water

Member
Is it really a good idea to go that way for a small project? He could gain a lot more just by finishing the project faster without that and focus on it for something bigger.
Of course embedding a huge scripting language is not beginner stuff, but it's what large game projects normally do. I mentioned it as a counterpoint, because I felt you were giving the impression that extracting game logic from code to scripts/level data is a waste of time in general.

The bottom line is that it's good to have as much of your specific game/level logic pulled out of the main code as possible. The closer you want to approach that ideal, the more groundwork you have to do, so one has to find a reasonable balance. For a small project that balance will be closer to "hardcode everything" than to "make a generic game engine and build a game on top of that". But one should keep the ideal in mind and at least keep things generic when it's easy. It will generally make sense to start prototyping with everything in the code, and extract things piece by piece when they are working and it seems convenient.
 

Jokab

Member
Need some java help. I need to take a string that the user inputs then take each char of the string, get the ascii value for it and pass that value into a for loop I have already made. It's been years since I've touched Java so I'm pretty lost.

So basically:
Code:
String input;

for(some value to some value) {
	char c = <get character from input>
	int val = <get c ascii value>
	// do something
}

Which step are you having trouble with? What have you tried?
 

Water

Member
Also, are we talking make an abstract class for Rules, and then make a specific class for each rule, and then having a line in the text file that tells the game to create an object for that specific class? I feel like since rules can get pretty specific, wouldn't this just lead to a bunch of rule objects, and if so is that okay?

I just can't wrap my head around how you could have could have conditions in a text file that are executed by the program.
Yeah, that's exactly what I meant. Understand that the really important thing about this is that the rule objects are created inside the loading code - that is what allows the main part of your game logic to be ignorant of the specifics of each level. It's best to start by just hardcoding the rule object creation in the level loading code. Loading them based on file contents is not essential, but organizing your code like this lets you easily do loading from file at any later point if you want to.

Here's a simple example of what hardcoded level data, plus some data in a file might look like.
Code:
// In level loading code
MaybeLoadSomeDataFromFile("level" + levelnumber + ".txt");
currentRules.Clear();
if (levelnumber == 1) {
  currentRules.Add(new GameOverWhenEnemiesShot(5));
  SpawnPlayerInLocation(1, 1);
  currentRules.Add(new KeepSpawningEnemiesAt(2,2));
  ...
}

// level1.txt - tile map, numbers on first line define size of map
6 4
######
#  # #
#    #
######
It should be reasonably obvious that you can read this text file, and create a Tile object in appropriate coordinates whenever you read a #, essentially just call MakeTile(x,y) or something.
But then, nothing prevents you from adding more rows to the text file. For example:
Code:
GameOverWhenEnemiesShot 5
So then your file loading code would read the rest of file after the tiles, and for any row that starts with a word it recognizes, it picks out the parameters (if any) and then creates the appropriate rule or game object exactly like the hardcoded code above does. No different from creating the tiles, really.
 
N

NinjaFridge

Unconfirmed Member
So basically:
Code:
String input;

for(some value to some value) {
	char c = <get character from input>
	int val = <get c ascii value>
	// do something
}

Which step are you having trouble with? What have you tried?

This is what I have at the minute. I have C and n declared. What I have at the moment works but it uses the variable m which is set to 29. I want to take the string the user has input, get the ascii value for each character and use that value for m, then the value that comes out is displayed. I know what I want, I just don't know how to do it.
Code:
int [] anArray = new int [5];
        	anArray[0] = 1;
        	anArray[1] = 1;
        	anArray[2] = 0;
        	anArray[3] = 1;
        	anArray[4] = 1;

for(int i = anArray.length -1; i > -1; i--)
        {
              if(anArray[i] == 1)
              {
            	  C = Math.pow(C, 2.0) % n;
                  C = C * m % n;
              }

              else if(anArray[i] == 0)
              {
            	  C = Math.pow(C, 2.0) % n;
              }
              System.out.println(C);
              
        }
 

Jokab

Member
This is what I have at the minute. I have C and n declared. What I have at the moment works but it uses the variable m which is set to 29. I want to take the string the user has input, get the ascii value for each character and use that value for m, then the value that comes out is displayed. I know what I want, I just don't know how to do it.
Code:
code

To get an indvidual character of a string, you can use
Code:
myString.charAt(index)

You'll also need to know that the numerical value of a character in Java is its ascii value. So basically all you need to do is cast the character to int, and you'll have the ascii value.

I assume anArray is specific to the problem you're trying to solve?

If I understand things correctly, you'll need a for-loop that wraps the code you have, going through the input string and setting the m value for each index.
 

0xCA2

Member
Yeah, that's exactly what I meant. Understand that the really important thing about this is that the rule objects are created inside the loading code - that is what allows the main part of your game logic to be ignorant of the specifics of each level. It's best to start by just hardcoding the rule object creation in the level loading code. Loading them based on file contents is not essential, but organizing your code like this lets you easily do loading from file at any later point if you want to.

Here's a simple example of what hardcoded level data, plus some data in a file might look like.
Code:
// In level loading code
MaybeLoadSomeDataFromFile("level" + levelnumber + ".txt");
currentRules.Clear();
if (levelnumber == 1) {
  currentRules.Add(new GameOverWhenEnemiesShot(5));
  SpawnPlayerInLocation(1, 1);
  currentRules.Add(new KeepSpawningEnemiesAt(2,2));
  ...
}

// level1.txt - tile map, numbers on first line define size of map
6 4
######
#  # #
#    #
######
It should be reasonably obvious that you can read this text file, and create a Tile object in appropriate coordinates whenever you read a #, essentially just call MakeTile(x,y) or something.
But then, nothing prevents you from adding more rows to the text file. For example:
Code:
GameOverWhenEnemiesShot 5
So then your file loading code would read the rest of file after the tiles, and for any row that starts with a word it recognizes, it picks out the parameters (if any) and then creates the appropriate rule or game object exactly like the hardcoded code above does. No different from creating the tiles, really.

Okay I get it now. Most game tutorials I've seen just put conditions and game logic for the game directly in the code, so encapsulating that into a Rule is kind of foreign to me, but I get it now.

I'm guessing that I basically do the same thing for Triggers/Game Events , right? Abstract class and then specific Trigger classes that do stuff? Or maybe by Rule you essentially mean Trigger/Game Event (not sure)..
 
Simple question that I just got stuck on: Querying a database in my android app and i need to check if it returns something or not.

Code:
Cursor cursor  = [database query];
if(cursor == null){
    //handle it here
}


Do I need to check the count or is this sufficient?
 
Top Bottom