Sign in to follow this  
superman3275

Another SFML pong error.... :(

Recommended Posts

superman3275    2061
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)
[CODE]
// 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;
}
[/CODE]
Paddle.hpp:
[CODE]
#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;
};
[/CODE]
Paddle.cpp:
[CODE]
#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();
}
[/CODE] Edited by superman3275

Share this post


Link to post
Share on other sites
superman3275    2061
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.

Share this post


Link to post
Share on other sites
Kaptein    2224
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(); Edited by Kaptein

Share this post


Link to post
Share on other sites
superman3275    2061
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? Edited by superman3275

Share this post


Link to post
Share on other sites
[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.
[code]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![/code]

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).

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

If you haven't already, now would be a good time to look up [url="https://www.google.com/search?q=C%2B%2B+references&sugexp=chrome,mod=15&sourceid=chrome&ie=UTF-8"]C++ references[/url].

[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. [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img]

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:[list=1]
[*]You are learning generalized programming concepts that apply to almost every language. (Computer science)
[*]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)
[*]You are learning the ins and outs of a specific language and its syntax. (C++)
[*]You are learning the ins and outs of a specific API, and its pros and cons. (SFML)
[*]You are making an interactive game. (Pong)
[/list]

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. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
superman3275    2061
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! Edited by superman3275

Share this post


Link to post
Share on other sites
superman3275    2061
Oh Crap, another error message. Which makes no sense:
Main.cpp:
[CODE]
// 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;
}
[/CODE]
Paddle.h:
[CODE]
#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;
};
[/CODE]
Paddle.cpp:
[CODE]
#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;
}
[/CODE]
Ball.h:
[CODE]
#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;
};
[/CODE]
Ball.cpp:
[CODE]
#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;
}
}
[/CODE]
Error Message:
[CODE]
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 ==========
[/CODE]
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.

Share this post


Link to post
Share on other sites
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 [u]make sense[/u], but I can't always make sense [u]of[/u] 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 [url="https://www.google.com/search?q=error+C2061%3A&oq=error+C2061%3A&sugexp=chrome,mod=15&sourceid=chrome&ie=UTF-8"]researched[/url] how to read it.

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

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

Everything there is perfectly understandable, except that we don't know what C2061 means. That's what the [url="https://www.google.com/search?q=error+C2061%3A&oq=error+C2061%3A&sugexp=chrome,mod=15&sourceid=chrome&ie=UTF-8"]research[/url] was for.
Top link of Google, without even having to follow the link, says: "[i]The compiler found an identifier where it wasn't expected. Make sure that identifier is declared before you use it.[/i]"

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

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

And that's how you read an error message. It tells us [b]what[/b] problem the compiler encountered, and [b]where[/b] it encountered it. Now the "[b]why[/b]" it encountered it is left to us.
[b]Why[/b] does it not know what 'Paddle' is? [b]Why [/b]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:
[i]Process Paddle.h[/i]
[i]Include Ball.h[/i]
[i]Don't include Paddle.h, because it was already included once.[/i]
[i]But Ball.h needs Paddle![/i]
[i]But Paddle isn't defined, because it wasn't included because it was already included previously![/i]

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:
[CODE]

//--------------------------------------------------
//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
//--------------------------------------------------
[/CODE]

Your Paddle class depends on the Ball class which depends on the Paddle class. This is known as a [url="http://en.wikipedia.org/wiki/Circular_dependency"]circular dependency[/url].
Circular dependcy isn't bad, but to make sure Ball knows about Paddle and Paddle knows about Ball, you can't [i]define [/i](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 [i]declare[/i] the class (which means, say that the class exists) without yet [i]defining [/i]what the class is.

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

Declaring something without yet defining it, is called a "[url="http://en.wikipedia.org/wiki/Forward_declaration"]forward declaration[/url]". 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 "[i]forward class declaration[/i]".

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

So when the compiler "copy + pastes" your headers together, the end result should look roughly like this:
[code]//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.
}[/code] Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
frazchaudhry    1220
@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. Edited by frazchaudhry

Share this post


Link to post
Share on other sites
Kaptein    2224
forward declares makes your life so much easier :)
if you google the subject you can see all sorts of ways to use them, and it will give you many more options when you are designing your application
there was indeed a time when i didn't know about them :) trying to sew together an application without them was a nightmare..
it compiled fast! but.. it was a real nightmare, and thank god someone told me about forward declares.. i use it on an as-needed basis!

Share this post


Link to post
Share on other sites
wqking    761
OP, not directly related to your question, but I highly suggest you start from the sample code in SFML package.
It's guaranteed working code (other wise, poke SFML author for a bug report :) ), and what you need to do is to understand the code, then re-structure it for your need, add more game plays, etc.
There is a Pong sample code and I tested it works very well.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this