Another SFML pong error.... :(

Started by
11 comments, last by superman3275 11 years, 6 months ago
Well, I have my work cut out for me. Pong seems impossible!
It won't display my sprite to the screen for some reason?
Pong.cpp: (The extra Sprite is just for reference, ignore it)

// Pong.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "Paddle.h"

int _tmain(int argc, _TCHAR* argv[])
{
sf::RenderWindow App(sf::VideoMode(800,600,32), "Pong");
App.SetFramerateLimit(30);
sf::Image Image1;
sf::Sprite Sprite1;
if (!Image1.LoadFromFile("images/RedPaddle.png"))
return EXIT_FAILURE;
Sprite1.SetImage(Image1);
Sprite1.Move(350, 750);
Paddle Paddle1;
Paddle1.Initialize(200, false, Image1);

while (App.IsOpened())
{
sf::Event Event;
while (App.GetEvent(Event))
{
if (Event.Type == sf::Event::Closed)
App.Close();
}
Paddle1.Update(App, Image1);
Paddle1.Draw(App);
App.Clear();
App.Display();
}
return 0;
}

Paddle.hpp:

#pragma once
#include <SFML/Graphics.hpp>
class Paddle
{
public:
void Draw(sf::RenderWindow &Window);
void Update(sf::RenderWindow &Window, sf::Image PaddleImage);
void Initialize(float speedx, bool isplayercontrolled, sf::Image Image);
private:
sf::FloatRect Collision;
sf::Sprite PaddleSprite;
bool HasAI;
float speedx;
};

Paddle.cpp:

#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "Paddle.h"

void Paddle::Initialize(float speedx, bool isplayercontrolled, sf::Image Image)
{
this->speedx = speedx;
HasAI = isplayercontrolled;
PaddleSprite.SetImage(Image);
}
void Paddle::Draw(sf::RenderWindow &Window)
{
Window.Draw(PaddleSprite);
}
void Paddle::Update(sf::RenderWindow &Window, sf::Image PaddleImage)
{
if (sf::Key::Left) PaddleSprite.Move(-speedx * Window.GetFrameTime(), 0);
else if (sf::Key::Right) PaddleSprite.Move(speedx * Window.GetFrameTime(), 0);
Collision.Top = PaddleSprite.GetPosition().y;
Collision.Left = PaddleSprite.GetPosition().x;
Collision.Bottom = Collision.Top + PaddleImage.GetHeight();
Collision.Right = Collision.Left + PaddleImage.GetWidth();
}

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

Advertisement
Backstory: This is my third attempt at pong! (Never Give Up -- I read 99% of people give up on programming their first game -- thats not going to be me!)
I haven't implemented collision yet, and this code *Should* be working, however I have a sneaking suspicion I declared something wrong.

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

ok, i dont know SFML at all, but... heres some suggestions:
it looks like you draw the sprite using Sprite.Draw(app); then shortly after that you clear the screen
using App.Clear()

when programming, you have to follow lines in a logical step-by-step way:
if you draw something and THEN clear the screen, the result is a cleared screen!

so.. i think your solution is (i'm assuming App is a View, which is created from a window handle):
App.Clear();
App.Draw(sprite);
App.Display();
I did what you said, and later found out it was a combination of me messing up with input and not doing what you said!!!! (Fixed) The only problem now is the image, which for some reason is appearing white, although I have a sneaking suspicion I didn't put a line of code in my Initialize() class that should be there. Thank You!
EDIT:
I fixed one problem which involved me not knowing the resolution (thought the width was the height and vice versa). But now I have another problem:
the Paddle shows up as white. Everything else works except it's white. I can promise you that it is, indeed, red. Any Ideas?

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

[s]Screenshot?[/s]

[s]Is the paddle image showing up as an entirely white square, or is it still in the correct shape of the paddle but white? Or is it a single white pixel?[/s]

You are passing by value. An sf::Image holds the image, and sf::Sprite is used for drawing the image. The sf::Image must continue to exist, for as long as you intend to use the sf::Sprite (This is so multiple sf::Sprites can share the same sf::Image without wasting memory).

So what's the problem then? I'll comment your code to illustrate.
sf::Sprite Sprite1; //Creating a sprite. Good.
if (!Image1.LoadFromFile("images/RedPaddle.png")) //Loading the image. Good.
return EXIT_FAILURE;
Sprite1.SetImage(Image1); //Setting the sprite to reference the image. Good, because the image continues to exist.

Paddle1.Initialize(200, false, Image1); //Passing the image into the Paddle... by value, not by reference. ***This copies the image***

void Paddle::Initialize(float speedx, bool isplayercontrolled, sf::Image Image) //'Image' is now a new copy.
{
this->speedx = speedx;
HasAI = isplayercontrolled;
PaddleSprite.SetImage(Image); //Setting the paddle's sprite to the image _copy_. This is fine, because the copy still exists.
} //Oh no! Our image copy went out of scope and got deleted! Our sprite now is referencing a deleted image!


Solution: Pass the image into the Initialize() function by reference (which is actually referencing the original image), not by value (which creates a copy that then goes out of scope).

void func(sf::Image Image) //Pass by value.
void func(sf::Image &Image) //Pass by reference.


If you haven't already, now would be a good time to look up C++ references.

[hr]

One other thing that isn't related to your problem: Instead of a Initialize() function, use class constructors. They do almost the same thing, but have a common meaning and bring extra benefits as well, like enabling RAII. It's just better, safer, programming. wink.png

Pong seems impossible now, but it's not Pong that's giving you difficulty, it's learning the language that's the hard part.
You are currently doing five things at once:

  1. You are learning generalized programming concepts that apply to almost every language. (Computer science)
  2. You are learning multiple abstract programming paradigms. (Procedural programming, OOP programming, and RAII, as well as a number of others that are less visible but none-the-less present)
  3. You are learning the ins and outs of a specific language and its syntax. (C++)
  4. You are learning the ins and outs of a specific API, and its pros and cons. (SFML)
  5. You are making an interactive game. (Pong)


Let me tell you something else: You're also doing a fantastic job at it, even if it doesn't seem like it. I can tell just from looking at your code, even though it may not be as good as an experienced programmer's code, I can see where you are learning good practices ahead of some other beginners at your level. You are doing excellently, so stick with it - I'm not just blowing false encouragement either.

Also, there's no shame in making Pong. Some things that seem foolish to people (because it's 'weak' or 'childish'), is actually the wiser thing to do.
I'm getting an all new .pdf / book on memory management now, just so I'll understand this more. Thanks, the fix worked.
EDIT:
Just touched up and experimented, and you Can set an image = to another image! That makes using my classes functions way easier because there's less arguments!

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

Yes, you can set an image to another image, but you have to make sure whatever copy you give to the sprite exists as long or longer than the sprite is being used for (or until you set the sprite to a different image).
Oh Crap, another error message. Which makes no sense:
Main.cpp:

// Pong.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "Paddle.h"
#include "Ball.h"

int _tmain(int argc, _TCHAR* argv[])
{
sf::RenderWindow App(sf::VideoMode(800,600,32), "Pong");
App.SetFramerateLimit(30);
sf::Image iBluePaddle;
sf::Image iRedPaddle;
if (!iRedPaddle.LoadFromFile("images/RedPaddle.png"))
return EXIT_FAILURE;
if (!iBluePaddle.LoadFromFile("images/BluePaddle.png"))
return EXIT_FAILURE;
Paddle PlayerPaddle(200, false, iRedPaddle);
Paddle AI_Paddle(200, true, iBluePaddle);

while (App.IsOpened())
{
sf::Event Event;
while (App.GetEvent(Event))
{
if (Event.Type == sf::Event::Closed)
App.Close();
}
AI_Paddle.Update(App);
PlayerPaddle.Update(App);
App.Clear();
PlayerPaddle.Draw(App);
AI_Paddle.Draw(App);
App.Display();
}
return 0;
}

Paddle.h:

#pragma once
#include <SFML/Graphics.hpp>
#include "Ball.h"
class Paddle
{
public:
Paddle(float speedx, bool isplayercontrolled, sf::Image &Image);
void Draw(sf::RenderWindow &Window);
void Update(sf::RenderWindow &Window, Ball bally);
sf::FloatRect GetCollision();
private:
sf::Image PaddleImage;
sf::FloatRect Collision;
sf::Sprite PaddleSprite;
bool HasAI;
float speedx;
};

Paddle.cpp:

#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "Paddle.h"

Paddle::Paddle(float speedx, bool isplayercontrolled, sf::Image &Image)
{
this->speedx = speedx;
HasAI = isplayercontrolled;
PaddleImage = Image;
PaddleSprite.SetImage(PaddleImage);
PaddleSprite.Move(350, 550);
}
void Paddle::Draw(sf::RenderWindow &Window)
{
Window.Draw(PaddleSprite);
}
void Paddle::Update(sf::RenderWindow &Window, Ball bally)
{
if (HasAI)
{
return;
}
if (Window.GetInput().IsKeyDown(sf::Key::Left)) PaddleSprite.Move(-speedx * Window.GetFrameTime(), 0);
else if (Window.GetInput().IsKeyDown(sf::Key::Right)) PaddleSprite.Move(speedx * Window.GetFrameTime(), 0);
Collision.Top = PaddleSprite.GetPosition().y;
Collision.Left = PaddleSprite.GetPosition().x;
Collision.Bottom = Collision.Top + PaddleImage.GetHeight();
Collision.Right = Collision.Left + PaddleImage.GetWidth();
}
sf::FloatRect Paddle::GetCollision()
{
return Collision;
}

Ball.h:

#pragma once
#include <SFML/Graphics.hpp>
#include "Paddle.h"
class Ball
{
public:
Ball(float speedx, float speedy, sf::Image &BallImage);
void Update(sf::RenderWindow &Window);
void Draw(sf::RenderWindow &Window);
sf::FloatRect GetCollision();
void Test_For_Collision(sf::FloatRect LeftWall, sf::FloatRect RightWall, Paddle &TopPaddle, Paddle &BottomPaddle);
private:
sf::FloatRect Collision;
sf::Sprite BallSprite;
sf::Image BallImage;
float speedx, speedy;
};

Ball.cpp:

#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "Ball.h"
Ball::Ball(float speedx, float speedy, sf::Image &BallImage)
{
this->speedx = speedx;
this->speedy = speedy;
this->BallImage = BallImage;
BallSprite.SetImage(this->BallImage);
}
void Ball::Update(sf::RenderWindow &Window)
{
BallSprite.Move(speedx * Window.GetFrameTime(), speedy * Window.GetFrameTime());
Collision.Top = BallSprite.GetPosition().y;
Collision.Left = BallSprite.GetPosition().x;
Collision.Bottom = Collision.Top + BallImage.GetHeight();
Collision.Right = Collision.Left + BallImage.GetWidth();
}
void Ball::Draw(sf::RenderWindow &Window)
{
Window.Draw(BallSprite);
}
sf::FloatRect Ball::GetCollision()
{
return Collision;
}
void Ball::Test_For_Collision(sf::FloatRect LeftWall, sf::FloatRect RightWall, Paddle &TopPaddle, Paddle &BottomPaddle)
{
if (GetCollision().Intersects(TopPaddle.GetCollision()))
{
speedy = -speedy;
}
if(GetCollision().Intersects(BottomPaddle.GetCollision()))
{
speedy = -speedy;
}
if (GetCollision().Intersects(LeftWall))
{
speedx = -speedx;
}
if (GetCollision().Intersects(RightWall))
{
speedx = -speedx;
}
}

Error Message:

1>------ Build started: Project: Pong, Configuration: Debug Win32 ------
1> stdafx.cpp
1>c:\users om\documents\visual studio 2010\projects\pong\ball.h(12): error C2061: syntax error : identifier 'Paddle'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

When I use a Paddle in one of my member functions in the Ball class, I get an error message, while it works fine to use a ball in the paddle class. I have been searching Google and have no idea why my class isn't working. I'm pretty much thinking of stuff that might be causing it and experimenting (As I've been for about 45 minutes now).
Sorry about asking you guys for SO MUCH help.

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

Well, the error message does make sense. That's what error messages are for: Making sense of mistakes. An error message that doesn't make sense wouldn't be added to the compiler. Compiler messages always make sense, but I can't always make sense of them. See? I'm shifting the blame from the perfectly working compiler, to my own lack of understanding - semantics, yes, but an important distinction none the less, otherwise I'll mentally assume the compiler is broken and ignore the good information it's trying to communicate to me.

I use a different compiler than yours, and my compiler gives different messages, so I also have no idea what that error message means.
So instead of guessing at what the error might be, knowing that the compiler already told me what the error is, I just now researched how to read it.

Your error message:
c:\users om\documents\visual studio 2010\projects\pong\ball.h(12): error C2061: syntax error : identifier 'Paddle'

Is saying:
In the file, "c:\users om\documents\visual studio 2010\projects\pong\ball.h"
At line number "(12)"
We got an error code "C2061"
Involving the identifier "Paddle".

Everything there is perfectly understandable, except that we don't know what C2061 means. That's what the research was for.
Top link of Google, without even having to follow the link, says: "The compiler found an identifier where it wasn't expected. Make sure that identifier is declared before you use it."

So in the file ball.h on line 12, it found 'Paddle' but 'Paddle' wasn't yet declared.

Looking at the code you posted, at (around-ish) line 12 in ball.h, I find:
void Test_For_Collision(sf::FloatRect LeftWall, sf::FloatRect RightWall, Paddle &TopPaddle, Paddle &BottomPaddle);
And sure enough, Paddle is used there.

And that's how you read an error message. It tells us what problem the compiler encountered, and where it encountered it. Now the "why" it encountered it is left to us.
Why does it not know what 'Paddle' is? Why does it think it's not yet declared?

Ball.h quite clearly #includes "Paddle.h", so why is there a problem? And Paddle.h quite clearly includes "Ball.h", so why is there a problem?

Wait a sec... Ball.h includes Paddle.h that includes Ball.h that includes Paddle.h that includes Ball.h that includes Paddle.h that includes... Looks like an infinite #include loop to me. Good thing you have" #pragma once" there, keeping the header from being included more than one time.
But, oh wait, let's walk through this in our head real quick:

Let's say, Paddle.h gets included before Ball.h. It'll look like this:
Process Paddle.h
Include Ball.h
Don't include Paddle.h, because it was already included once.
But Ball.h needs Paddle!
But Paddle isn't defined, because it wasn't included because it was already included previously!

So when the compiler is compiling Ball.h, and encounters 'Paddle', it doesn't know what it is, because the header you included, you also told it not to include if it was already included... and it was already included, but someplace where Ball.h can't access it.

#include just means "Copy and paste the code from the file I'm including into this file."

So let's see what that might look like to the compiler:


//--------------------------------------------------
//Beginning of Paddle.h
#pragma once //Compiler: Activated! Got it! As a compiler, I won't include Paddle.h anymore.
#include <SFML/Graphics.hpp>
//--------------------------------------------------
//Beginning of SFML/Graphics.hpp
#pragma once //Compiler: Activated! Got it! As a compiler, I won't include SFML/Graphics.hpp anymore.
//Lots of SFML stuff here.
//End of SFML/Graphics.hpp
//--------------------------------------------------
#include "Ball.h"
//--------------------------------------------------
//Beginning of Ball.h
#pragma once //Compiler: Activated! Got it! As a compiler, I won't include Ball.h anymore.
#include <SFML/Graphics.hpp>
//--------------------------------------------------
//Compiler: Hey! We already included SFML/Graphics.hpp! We won't include it a second time.
//(Luckily, our copy+paste puts the SFML stuff ABOVE this stuff, so we still have access to it all)
//--------------------------------------------------
#include "Paddle.h"
//--------------------------------------------------
//Compiler: Hey! We already included Paddle.h! We won't include it a second time.
//(But our Paddle class is BENEATH us, so class Ball doesn't yet know it exists)
//--------------------------------------------------
class Ball
{
public:
Ball(float speedx, float speedy, sf::Image &BallImage);
void Update(sf::RenderWindow &Window);
void Draw(sf::RenderWindow &Window);
sf::FloatRect GetCollision();
//--------------------------------------------------
//Hey! What in the world is 'Paddle'? Going from top to bottom of this file I'm compiling,
//I don't see any 'Paddle' being declared before this line, so I don't yet know what a Paddle is.
//Error! Error! This type of error is "C2061".
//This file is "Ball.h"
//This line is "12"
//The variable I don't know is called "Paddle".
//--------------------------------------------------
void Test_For_Collision(sf::FloatRect LeftWall, sf::FloatRect RightWall, Paddle &TopPaddle, Paddle &BottomPaddle);
private:
sf::FloatRect Collision;
sf::Sprite BallSprite;
sf::Image BallImage;
float speedx, speedy;
};
//End of Ball.h
//--------------------------------------------------
class Paddle
{
public:
Paddle(float speedx, bool isplayercontrolled, sf::Image &Image);
void Draw(sf::RenderWindow &Window);
void Update(sf::RenderWindow &Window, Ball bally);
sf::FloatRect GetCollision();
private:
sf::Image PaddleImage;
sf::FloatRect Collision;
sf::Sprite PaddleSprite;
bool HasAI;
float speedx;
};
//End of Paddle.h
//--------------------------------------------------


Your Paddle class depends on the Ball class which depends on the Paddle class. This is known as a circular dependency.
Circular dependcy isn't bad, but to make sure Ball knows about Paddle and Paddle knows about Ball, you can't define (give the details of) the same class twice - that's a compiler error.
But also, both classes need to know about the other, otherwise there's a compiler error.

So what you do is declare the class (which means, say that the class exists) without yet defining what the class is.

You: I declare that there is a class called "Paddle"
You: I declare that there is a class called "Ball" and I define that it has such and such variables and functions, including ones that use the previously declared Paddle, which Ball knows exists but which hasn't yet defined.
You: I now define "Paddle", and the functions and variables it has, including that it needs "Ball" (which is already defined and declared).

Declaring something without yet defining it, is called a "forward declaration". We also call this a "pre-declaration".
You can forward declare functions and variable types. In this case, we're forward declaring a class, so it's a "forward class declaration".

It looks like this:
class Paddle; //Declared without being defined.

So when the compiler "copy + pastes" your headers together, the end result should look roughly like this:
//Just (pre)declare the "Paddle" class.
class Paddle;

//Declare AND define the Ball class.
class Ball
{
//Uses 'Paddle'... Great! I know that Paddle exists, though I don't yet know what it is.
}

//Define the pre-declared Paddle.
class Paddle
{
//Uses 'Ball'. Great! I know that Ball exists, AND I know what it is.
}
@servant of the lord:
wow perfect and in depth explanation. I had this problem once too and I was pulling my hair out until I figured this out. [s]OP why don't you give pre-compiled headers a try they not only make compilation faster but also makes managing header files easier.[/s]
EDIT: it seems you are already using precompiled headers. But you are not using them correctly. Include the headers in the stdafx.h and just include this file in your other files. This way you won't have to include Paddle.h in Ball.h and vice versa. Just include "stdafx.h" and you're set.

This topic is closed to new replies.

Advertisement