The Thread for Programming

here's a good place for FRIENDLY, ENJOYABLE, and otherwise very GENERAL discussion!
User avatar
WhattayaBrian
Posts: 239
Joined: 8 years ago

Re: The Thread for Programming

Post by WhattayaBrian »

Howdy people.

I'm a professional software engineer in the game industry, and I work primarily in C/C++. Python is my scripting language of choice, and I can manage in just about any iterative language that's used to any real extent (no I can't program in whitespace), so C#, Java, Unrealscript (worst language ever), and even Actionscript sometimes.

I probably won't be posting any coding snippets of my own, mostly because it's really hard to program at home after you spend all day programming at work, but I love helping people and discussing techniques.

@Zyglrox Odyssey: I made almost that exact same program years ago, to learn hiragana and katakana. I even did it in Visual Basic (sad days). It brings a smile to my face.
If you read this post and thought "Wow, what a swell guy, I sure would like to hear his voice and also watch videogames?" then do I have a link for you.

Current Game: Distorted Travesty 3
User avatar
docopoper
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla non pharetra enim, nec maximus odio.
Posts: 78
Joined: 11 years ago
First name: Shane Farrell
Pronouns: they/he
Location: Ireland

Re: The Thread for Programming

Post by docopoper »

WhattayaBrian wrote: I probably won't be posting any coding snippets of my own, mostly because it's really hard to program at home after you spend all day programming at work, but I love helping people and discussing techniques.
Haha, I know that feeling. That was me during June and July with my summer job. It's probably my least favourite thing about having a programming job... That it stops me from programming.
The first thing I would do with infinite power would be to make myself a cave where I could look at my shadow forever.

Image <- Go team Yeah Doctor Shemp.!
Image <- That's everyone being nice to me. ^^

I made a game called Utter Confusion! Play it! :D
It's a lot of fun and has been incredibly popular at every indie game dev party I've brought it to.
Frozelar
Retired Screamer
Posts: 5
Joined: 11 years ago
Location: The Place You Wish You Were

Re: The Thread for Programming

Post by Frozelar »

Oh man, so, I'm kind of having problems with my program thingy I'm making. I've spent the past two weeks trying to figure it out but I'm stumped. I looked at multiple similar situations on Stack Overflow but they either didn't work or weren't relevant.

I'm also aware that my code is probably really bad and really sloppy, but this is my first program and my priority wasn't to make pretty code, but rather to make WORKING code. After I get it to work I'll pretty it up. That being said, if my code is really bad, I'd love to be told how to improve it.

I know that it'll probably take a lot of time to help me out and I can completely understand if nobody wants to but I figure it's worth a shot. All my fellow talkhausers are super nice, I've learned. Anyways, enough of this mumbo jumbo.

I've spoilered the post because it's really long.
Anyways, now for the problems. I'm trying to make a sort of game in C++ and SDL2, where you can move all around and collide with blocks and enemies. When I start debugging it, this window comes up:
Image

This is what the "Call Stack" says (no idea what the call stack is):
Image

The First Error
So, the first error it shows is line 509. Here's the function that uses that line:

Code: Select all

void Texture::free()
{
	// if a texture exists, get rid of it and reinitialize everything
	if (txTexture != NULL)
	{
		SDL_DestroyTexture(txTexture);     // THIS IS LINE 509
		txTexture = NULL;
		txRect.w = DEFAULT_W;
		txRect.h = DEFAULT_H;
		txRect.x = DEFAULT_X;
		txRect.y = DEFAULT_Y;
	}
}
This function is part of the Texture class. The Texture class is used for each game object's texture, and each variable inside of the Texture class is prefixed with "tx". The function checks to make sure that the pointer that points to an SDL_Texture is actually pointing to a texture and not empty. Then, it calls SDL_DestroyTexture and re-initializes the pointer and variables.
txTexture is a texture pointer, so I'm not using incorrect function parameters.

Not gonna lie, a lot of my code is based off of Lazy Foo's tiling tutorial. I wrote this program completely from scratch, using his tutorial for reference. Anyways, this is the code he uses in his tutorial:

Code: Select all

void LTexture::free()
{
	//Free texture if it exists
	if( mTexture != NULL )
	{
		SDL_DestroyTexture( mTexture );
		mTexture = NULL;
		mWidth = 0;
		mHeight = 0;
	}
}
His version runs just fine. Not really sure how my code would make anything different happen. I dunno.

The Second Error
Here's the code that includes line 464:

Code: Select all

bool Texture::loadF(string path)
{
	// keeps track of whether a failure occurred
	bool success = true;

	// free the current texture (if it exists)
	free();

	// the texture that we will (hopefully) end up with
	SDL_Texture* createdTexture = NULL;          // THIS IS LINE 464

	// the surface that the texture's image will be loaded onto
	SDL_Surface* imageSurface = IMG_Load(path.c_str());

	if (imageSurface == NULL)
	{
		// output a message if the surface failed to load
		printf("Error loading image at the specified path: %s\n", path);
		printf("IMG_GetError: %s\n", IMG_GetError());
		success = false;
	}
	else
	{
		// set the color key
		SDL_SetColorKey(imageSurface, SDL_TRUE, SDL_MapRGB(imageSurface->format, 0, 255, 255));

		// create the texture itself from the surface
		createdTexture = SDL_CreateTextureFromSurface(gRenderer, imageSurface);

		if (createdTexture == NULL)
		{
			// output an error
			printf("Error creating texture from surface.  SDL_GetError: %s\n", SDL_GetError());
		}
		else
		{
			txRect.w = imageSurface->w;
			txRect.h = imageSurface->h;
		}
	}

	// the surface isn't needed anymore
	SDL_FreeSurface(imageSurface);

	// make the texture member point to the newly created texture
	txTexture = createdTexture;

	// return whether everything ran successfully or not
	return success;
}
This code frees the current texture, loads an image surface, sets the color key, creates a SDL_Texture from the surface, sets the Texture's rect's width and height, frees the unneeded surface, and makes the Texture's pointer point to the SDL_Texture.
I have no idea how line 464 could cause an error. I'm just declaring (or defining? not good with vocabulary) a pointer to an SDL_Texture.

Again, this is similar to Lazy Foo's code, which runs fine:

Code: Select all

bool LTexture::loadFromFile( std::string path )
{
	//Get rid of preexisting texture
	free();

	//The final texture
	SDL_Texture* newTexture = NULL;

	//Load image at specified path
	SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
	if( loadedSurface == NULL )
	{
		printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
	}
	else
	{
		//Color key image
		SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );

		//Create texture from surface pixels
        newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
		if( newTexture == NULL )
		{
			printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
		}
		else
		{
			//Get image dimensions
			mWidth = loadedSurface->w;
			mHeight = loadedSurface->h;
		}

		//Get rid of old loaded surface
		SDL_FreeSurface( loadedSurface );
	}

	//Return success
	mTexture = newTexture;
	return mTexture != NULL;
}
No clue why I get an error.

The Third Error
Sprite variables are prefixed with sp (I have Player and Enemy classes which inherit from the Sprite class). The code with line 321:

Code: Select all

Player::Player(int passedX = DEFAULT_X, int passedY = DEFAULT_Y, int passedW = DEFAULT_W, int passedH = DEFAULT_H)
{
	// initialize variables
	spRect.x = passedX;
	spRect.y = passedY;
	spRect.w = passedW;
	spRect.h = passedH;
	spFrames = 4;

	// load the player's texture
	spTexture->loadF("resources/cubeman.png");
	
	// center the camera around the player
	centerCamera();          // THIS IS LINE 321
}
This function (which is the Player class's constructor) assigns the variables, loads the player's texture, and centers the camera around the player.
Again, no idea what's with the error. Here's the centerCamera function (Camera variables prefixed with cm):

Code: Select all

void Player::centerCamera()
{
	// variable to represent the camera
	SDL_Rect* camera = &gCamera.cmRect;
	camera->w = WINDOW_W;
	camera->h = WINDOW_H;

	// determines whether the camera is at the level's edge or not
	bool edge = false;

	// represents the camera when it moves
	SDL_Rect moddedRect;

	// set moddedRect properties
	moddedRect.x = camera->x;
	moddedRect.y = camera->y;
	moddedRect.w = camera->w;
	moddedRect.h = camera->h;

	// set moddedRect to camera's next move
	moddedRect.x++;
	moddedRect.y++;

	// if camera is about to go off the left of the screen, stop its movement
	if (moddedRect.x < camera->w / 2)
	{
		camera->x = 0;
		edge = true;
	}

	// if it is about to go off the right, stop it
	if (moddedRect.x > LEVEL_W - camera->w / 2)
	{
		camera->x = LEVEL_W - camera->w;
		edge = true;
	}

	// if it is about to go off the top, stop it
	if (moddedRect.y > camera->h / 2)
	{
		camera->y = 0;
		edge = true;
	}

	// if it is about to go off the bottom, stop it
	if (moddedRect.y > LEVEL_H - camera->h / 2)
	{
		camera->y = LEVEL_H - camera->h;
		edge = true;
	}

	// if not at the edge of the level, keep camera centered around player
	if (!edge)
	{
		camera->x = spRect.x - (camera->w / 2);
		camera->y = spRect.y - (camera->h / 2);
	}
}
This function makes an SDL_Rect pointer that points to the camera's rect, and sets all the variables. Then it defines another SDL_Rect that represents where the camera is about to move to. If the place where the camera is about to move is the edge of the screen, then the camera needs to stop moving in that direction so that it doesn't scroll offscreen.

The Fourth Error
Here's line 253:

Code: Select all

// player, camera, and background
Player gPlayer(0, 0, 64, 64);          // THIS IS LINE 253
Camera gCamera(0, 0, 64, 64);
Background gBackground(0, 0, 64, 64);
The parameters in all those functions are the x and y positions, followed by the width and height. I gave the constructors default parameters, but when I omit the parameters in the above declarations it gives me an error for some reason. I have no idea why; here's the gPlayer constructor definition:

Code: Select all

Player::Player(int passedX = DEFAULT_X, int passedY = DEFAULT_Y, int passedW = DEFAULT_W, int passedH = DEFAULT_H)
{
	// initialize variables
	spRect.x = passedX;
	spRect.y = passedY;
	spRect.w = passedW;
	spRect.h = passedH;
	spFrames = 4;

	// load the player's texture
	spTexture->loadF("resources/cubeman.png");
	
	// center the camera around the player
	centerCamera();
}
So, I guess there's two questions with this one. Why am I getting a dynamic initializer error, and why are my default parameters not working? Perhaps they're connected somehow?

And I'm not sure what the last two lines of the Call Stack mean. Maybe they're important?
In case I haven't provided enough information, here's the full program. Or you could certainly ask for more info if I didn't give enough. I'd really love any help with one error or multiple errors.
User avatar
WhattayaBrian
Posts: 239
Joined: 8 years ago

Re: The Thread for Programming

Post by WhattayaBrian »

A couple things:

1. You've listed some information about the errors you've gotten, but not the actual errors themselves. Those are critical to figuring out what's going on.
2. You've listed quite a few compilation errors, but you also show a call stack, which implies a runtime error: how are you getting it to run with those compilation errors still in?
3. Default arguments go in the declaration, not the definition, so you need to put them in the section where you say "class Player { ... }", for example.
4. You've uploaded the main cpp of your project, but you've neglected the solution and project files, which make it unlikely anyone else will be able to run it.

I can get into more detail once you supply those things. :)

Edit:

Okay, I did a bit of looking around, and there's one very devastating mistake I found.

Code: Select all

for (int i = 0; i <= TOTAL_BLOCKS; i++)
When you make an array of size 64 (like, for example, blocks, enemies, and playerPos), that means your valid indices go from 0 to 63. Because your ending condition uses <= instead of <, you're actually going to index 64, and thus overwriting memory. You need to change the condition to use <.
If you read this post and thought "Wow, what a swell guy, I sure would like to hear his voice and also watch videogames?" then do I have a link for you.

Current Game: Distorted Travesty 3
Frozelar
Retired Screamer
Posts: 5
Joined: 11 years ago
Location: The Place You Wish You Were

Re: The Thread for Programming

Post by Frozelar »

Ah, yeah, apparently those were runtime exceptions and not actual errors. My bad!
WhattayaBrian wrote:Default arguments go in the declaration, not the definition, so you need to put them in the section where you say "class Player { ... }", for example.
Ah, duh. Thank you for pointing that out!
WhattayaBrian wrote:When you make an array of size 64 (like, for example, blocks, enemies, and playerPos), that means your valid indices go from 0 to 63. Because your ending condition uses <= instead of <, you're actually going to index 64, and thus overwriting memory. You need to change the condition to use <.
You know, I remember specifically checking over all that to make sure that that didn't happen and I still managed to screw it up, haha. Thank you!
And thank you for helping me out. I really do appreciate it a lot.
Rénà wrote:[a whole lot of super helpful words and stuff]
Thank you Rena; you're a life saver! Fixed all of the runtime exceptions. And taught me a little more along the way. You deserve a medal.
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

I've been sitting here waiting for my next class to start all day so I made a little thing.
http://pastebin.com/nr40j3uf
There's almost definitely a million better ways to do it than what I did but that's what I came up with. I don't know if there's an easier way to convert numbers into their spelled out strings, so I had to hardcode it into a separate class file. If I ever wanted to make it so you could use a broader range of numbers I would just have to modify the Conversion.java file to keep the pattern going with the switch, and then change the <= condition in the Numbers.java class. So at least I have that going for me.

Here's a few example outputs:

Code: Select all

Input a number between 0 and 20
13
thirteen is 8
eight is 5
five is 4
Four is the magic number.

Code: Select all

Input a number between 0 and 20
8
eight is 5
five is 4
Four is the magic number.

Code: Select all

Input a number between 0 and 20
3
three is 5
five is 4
Four is the magic number.
Image
Image
Image
Image
Image
Image
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

Haha, yeah that probably would have been easier than what I did. Didn't really think to do that though.

Regardless, I needed practise with passing variables between classes and whatnot because I've barely every used any of that before. I might go back and clean it up a bit later.
Image
Image
Image
Image
Image
Image
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

Alright, so I updated it with your suggestions. Also I made it so I don't have to manually update the "input a number between 0 and x" text if I were to add more numbers.
http://pastebin.com/NrBLDqLW
Image
Image
Image
Image
Image
Image
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

No, if you put a number that won't work in it loops back around and asks you to put another one in.

Code: Select all

do{
			System.out.println("Input a number between 0 and " + (words.length-1));
			theNum = sc.nextInt();
		}while(theNum<0 || theNum>(words.length-1));
(although it does throw a fit if you don't put an integer in)
Image
Image
Image
Image
Image
Image
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

ALRIGHT FINE

(thanks <3)
Image
Image
Image
Image
Image
Image
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

So I was thinking about the thing I made earlier and was trying to remember why I had both theNum and newNum and couldn't remember why they both were there.
So I checked through my code and there really didn't seem to be a reason why I did the first check so that theNum was between 0 and [length of array - 1], and then set newNum equal to theNum and start using that instead. Only reason I could see was in case for some reason I wanted back the user's original number after the loop went through, but I didn't so I removed the redundancy.
http://pastebin.com/NrBLDqLW

You (rena) never mentioned it to me when you were pointing things out to change, so I'm not sure if it's cause you didn't care, didn't notice, or if it's actually good practice to keep the original number (thinking back to the "write reusable code" thing).
Image
Image
Image
Image
Image
Image
User avatar
lukaramu
not lukaramu
Posts: 0
Joined: 10 years ago
First name: not lukaramu
Location: the place where i live

Re: The Thread for Programming

Post by lukaramu »

Because that promblem seemed kinda interesting I'm working on a solution in Haskell right now, which I will probably edit in later today. Just a note:
Wikipedia wrote:Despite being related to the word "four" (4), 40 is spelled "forty", and not "fourty".
User avatar
lukaramu
not lukaramu
Posts: 0
Joined: 10 years ago
First name: not lukaramu
Location: the place where i live

Re: The Thread for Programming

Post by lukaramu »

I did it! This solution is quite easily expandable for larger numbers as the strings for numbers larger than 19 are computed (I only implemented numbers up to 99, but with not much effort you could do everything quite quickly by recursing over numToStr and reusing it for things like nine-hundred and thirty-three thousand.

Here's the code!

(Also, you should learn yourself a Haskell (for great good)!)
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

Wikipedia wrote:Despite being related to the word "four" (4), 40 is spelled "forty", and not "fourty".
Oh my god, how did I not see that, haha

Also, good job with the thing!
Yeah, I originally got the idea from this Reddit thread, and someone there made one that goes up to a few billion (here).
Image
Image
Image
Image
Image
Image
Frozelar
Retired Screamer
Posts: 5
Joined: 11 years ago
Location: The Place You Wish You Were

Re: The Thread for Programming

Post by Frozelar »

It's with a heavy heart that I've decided to abandon my game "engine," if you can call it that, and start fresh again. I'll take a few of the things from it that actually weren't terrible, but I'll mostly start from scratch.
Like, so many things are going wrong with it and it's so disorganized that trying to pinpoint the issues is like trying to find the meat in a hamburger that uses airplanes instead of bread

I must say that I learned a tremendous amount through making it and (sort of) debugging it, and again, thank you rena and whattayabrian for your help!

Also wow, if rena makes a thing with unreal engine I so want to play it
EDIT: You meant unity engine
[/moron]
User avatar
Clamestarebla
Clamkind Arch-Highlord
Posts: 230
Joined: 9 years ago
Location: The Void
Contact:

Re: The Thread for Programming

Post by Clamestarebla »

That is pretty rad looking!
Train harder, run faster, be stronger, better, evolution never over.
Image
Image
Image
Image
Frozelar
Retired Screamer
Posts: 5
Joined: 11 years ago
Location: The Place You Wish You Were

Re: The Thread for Programming

Post by Frozelar »

Oh, really? That's pretty awesome rena. Totally gonna play whatever you make.
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

So with this CS class, I can't help but feel that a classroom scenario isn't a great way to start off when learning programming. Having a guy just talk to a group of like 300 people and then sending them off to labs and telling them to do things seems WAY less helpful than just watching a YouTube tutorial or something.
I suppose that's what the book is for, but if you're learning everything from the book, what's the point of the classes?

I'm totally getting everything that's going on, but there are a lot of people that still seem to be confused with basic stuff, and I don't don't think it's cause they're stupid; I just think the material is being taught in an awkward way.

I think once you get into more advanced CS classes and pretty much everyone there knows the basics at that point, these methods of teaching will work much better, but for people starting off I can imagine this would be super confusing.
Image
Image
Image
Image
Image
Image
User avatar
WhattayaBrian
Posts: 239
Joined: 8 years ago

Re: The Thread for Programming

Post by WhattayaBrian »

I would tend to agree with you. Teaching something like the fundamentals of a programming language, which is often rife with very strict and specific syntax requirements, is hard to do on a whiteboard.

Professors should be there to guide the order of the learning, as well as answer questions. And, once you get to more abstract things like "how do I linked list?" the whiteboard becomes very useful again.

I think we're bad at teaching programming because we haven't done it enough. It's still pretty new.
If you read this post and thought "Wow, what a swell guy, I sure would like to hear his voice and also watch videogames?" then do I have a link for you.

Current Game: Distorted Travesty 3
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

Are you a CompSci prof? If so, that's pretty neat!

And yeah, like I think part of it is, like you mentioned, it being a newer thing. But I also think that when there's a popular channel on YouTube where someone teaches you something, they're particularly good at teaching it and that's why they're so popular.

TheNewBoston in particular has a ton of programming tutorials for a ton of different languages, and I think a lot of his success comes from the fact that he just teaches things really well, puts things in easy to understand terms, and understands what kinds of questions a person new to programming would be asking.

During a CS class the other day, the prof was showing off some code that demonstrated putting two strings together into a new string. Something like:

Code: Select all

string text1 = "this is ";
string text2 = "a sentence";
string text3 = text1 + text2;

// now text3 says "this is a sentence"
and someone asked "couldn't we just make a variable that says 'this is a sentence'?" and he probably could have just explained that the point is to show how to put strings together, and create new strings from other strings or something, but instead he went on a complex explanation of why you shouldn't hardcode or something along those lines. I mean, what he was saying made sense, but I think to a person asking that question it would have just caused more confusion.
Image
Image
Image
Image
Image
Image
devil†zukin

Re: The Thread for Programming

Post by devil†zukin »

devil†zukin

Re: The Thread for Programming

Post by devil†zukin »

http://imgur.com/fZwyZnK

this run animation doesn't seem very safe
User avatar
WhattayaBrian
Posts: 239
Joined: 8 years ago

Re: The Thread for Programming

Post by WhattayaBrian »

Ashan wrote:Are you a CompSci prof? If so, that's pretty neat!
Ah, sorry, no. By "we" I meant "we" as in humans vs "we" as in people who teach programming. I am a programmer by trade, though, and I've gone through the gamut of programming classes.

I think one of the problems is the same as in teaching everything else: there's no one correct way people learn things. For example, I really get hung up on black boxes, so when a professor says: "Just put 'return 0;' at the end of main, don't worry about it," I definitely start to worry about it a lot. I get hung up on these things that I'm told to ignore because they're "not the point", such that I start to ignore the lesson at hand.

And C++ is notorious for this, since so many things are so explicit. It's easier to ignore stuff in C#, where everything is so abstracted you have 0 chance of understanding the vast majority of it.

But on the other hand, some people get along with that method just fine.
If you read this post and thought "Wow, what a swell guy, I sure would like to hear his voice and also watch videogames?" then do I have a link for you.

Current Game: Distorted Travesty 3
User avatar
Ashan
The world has become a place
Posts: 2660
Joined: 12 years ago
Location: Canada
https://ashan.talkhaus.com/

Re: The Thread for Programming

Post by Ashan »

Hah, I got you,

Well said.
Image
Image
Image
Image
Image
Image
devil†zukin

Re: The Thread for Programming

Post by devil†zukin »

oh my gerd so many things readily available to me that never were with unity (destructible meshes, for example)

i made a little demo when i was playing with these features WASD space click

Image
http://cat.rena.so/ue/RPG.zip

!!!!!!!!!!!FILESIZE WARNING ITS LIKE SEVENTY MEGABYTES!!!!!!!!!!!!!!

byo sound effects
Post Reply