SFML community forums

Help => General => Topic started by: Lethn on June 20, 2013, 08:32:40 pm

Title: Lethn's Programming Questions Thread
Post by: Lethn on June 20, 2013, 08:32:40 pm
I thought instead of spamming the forum with new topics guys I'd just spam the one topic then that way everyone else can keep posting as normal. I didn't think I'd get this deep into programming but as I go through tutorials I've got more and more things to investigate, some stuff I just get on my own but other stuff like what I'm working on currently I need help with.

I'm looking at how to combine C++ and SFML so I can get a basic game running, so the obvious stuff like health or gold go up or down depending on what happens to the game. I understand the C++ code and I understand the SFML code for both of these functions but I'm of course running into problems combining the two because I'm not sure where to put it. I'm also getting these situations where the C++ code isn't liking my SFML objects very much and I suspect that's going to be because the two will be in conflict with each other somewhere so I need to experiment and find out what works.


#include <Iostream>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }
    sf::Text lineone;

    lineone.setFont( arial );
    lineone.setCharacterSize ( 12 );
    lineone.setPosition ( 340, 280 );





    while (window.isOpen())
    {
        {
            using namespace std;
            int numberinput;
            lineone.draw ( "Type in a number: " )
            cin>> numberinput;
            cin.ignore();
            if ( numberinput < 10 ){
            lineone.draw ( "Death, you entered too low a number" );


            }
        cin.get();
        }

    sf::Event event;
    while (window.pollEvent(event))


{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( lineone );
        window.display();

    }

    return 0;

}

I'm starting off with the basic C++ functions and combining them with the SFML text, I'm aware you could use SFML TextEntered but I want to be able to use all of my C++ functions rather than just a couple and getting stumped when I try to do something different.
Title: Re: Lethn Questions Thread
Post by: Nexus on June 20, 2013, 08:59:52 pm
I understand the C++ code and I understand the SFML code for both of these functions but I'm of course running into problems combining the two because I'm not sure where to put it. I'm also getting these situations where the C++ code isn't liking my SFML objects very much and I suspect that's going to be because the two will be in conflict with each other somewhere so I need to experiment and find out what works.
You're speaking as if C++ and SFML were two separate things, and that's probably the source of your error. You can't really learn C++ and SFML in parallel, since SFML is pure C++. Do you have a good book to read about C++? I strongly recommend not to use any tutorials, especially not YouTube videos, to learn the programming language. They're mostly badly written and don't cover important details. Experimenting is a very bad idea too; C++ contains enough pitfalls to make this approach a nightmare. You should really invest some time into learning C++, you won't get around it anyway if you plan to develop seriously ;)

Also, you should definitely describe your problem more clearly. "Not sure where to put it" or "they don't like each other" doesn't tell us about the problem, so we have to look at the code (which should be in code tags and properly indented) and guess.

Why do you mix standard input and SFML rendering in the same loop? std::cin blocks the thread and you can't render and poll input regularly. Also, you should include lower-case <iostream>, and you certainly don't need <OpenGL.hpp>.
Title: Re: Lethn Questions Thread
Post by: Lethn on June 21, 2013, 04:54:03 am
You've partially answered my question already, I've fixed the code thanks to your critique and the if statement I've written works fine, my problem is that I just haven't gotten it to work in the GUI window as text, I can only get it to work in the console. What I need is to get things like basic if statements like this working in the actual GUI window as SFML text rather than just a console application and your point about C++ and SFML got me thinking again because yes there's C++ already in it so I guess I just need to think about it more.

The way I've been learning is using the documentation from SFML, cprogramming tutorials http://www.cprogramming.com/tutorial/c++-tutorial.html and of course searching through the internet to see if my questions have already been answered ages ago. If you can recommend me a good C++ book that's up to date that would be nice, the problem is a lot of the books I've seen are even more outdated sometimes than the tutorials so it's pretty unhelpful for a newbie like me I think so you may as well give that sort of thing to someone who already knows the code.

The reason as well I'm not sure about using the SFML text input is of course many games use statistics and numbers so I'm not sure that command could cope with having numbers update themselves constantly unless I'm missing something.

Here's the updated code:

#include <iostream>
#include <SFML/Graphics.hpp>
int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }
    sf::Text lineone;

    lineone.setFont( arial );
    lineone.setCharacterSize ( 12 );
    lineone.setPosition ( 340, 280 );





    while (window.isOpen())
    {
        {
            using namespace std;
            int numberinput;
            cout<< ( "Type in a number: " );
            cin>> numberinput;
            cin.ignore();
            if ( numberinput < 10 ){
            cout<< ( "Death, you entered too low a number" );


            }

        }

    sf::Event event;
    while (window.pollEvent(event))


{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( lineone );
        window.display();

    }

    return 0;

}
 

Note: I'm aware of what the OpenGL.hpp does, it enables OpenGL but I guess I'll keep it simple now and save that for later :D
Title: Re: Lethn Questions Thread
Post by: The Hatchet on June 21, 2013, 04:58:58 am
lineone.setString("Blah blah blah this is a string");

to actually set what you string says.

and
window.draw(lineone);

to draw it.

But you really need to find a good c++ book to get the general ideas of program flow, control statements and scope nailed down.  You have randome {  } brackets in your 'while(window.isOpen())' loop and half of your code that should be in said loop isn't.
Title: Re: Lethn Questions Thread
Post by: Lethn on June 21, 2013, 05:00:20 am
So you'd put setString where cout would normally be? That would explain where I've been going wrong, I was doing the opposite lol :D

#include <iostream>
#include <SFML/Graphics.hpp>
int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }
    sf::Text line1;

    line1.setFont( arial );
    line1.setCharacterSize ( 12 );
    line1.setPosition ( 340, 180 );

    sf::Text line2;

    line2.setFont ( arial );
    line2.setCharacterSize ( 12 );
    line2.setPosition ( 240, 180 );






    while (window.isOpen())

                {
            using namespace std;
            int numberinput;
            line1.setString ( "Enter a number:" );
            cin>> numberinput;
            cin.ignore();
            if ( numberinput < 10 ){
                    line2.setString  ( "Death! You entered in too low a number!/n" );


            }
        }
    {

    sf::Event event;
    while (window.pollEvent(event))


{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( line1 );
        window.display();

    }

    return 0;

}
 

The code is compiling now but for some reason it just crashes, will keep working away at it.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on June 21, 2013, 06:46:55 am
Because I got lost in your ill formated code and was wondering if you had {} misplaced I cleaned your code up and only moved your code around and added 1 line i think to make it work fine.  Please take this as one of many examples of better formed code and try to get your hands on an actual book to learn core C++ practices and principles. 

Like others have said around this board and through my own explorations, online tutorials SUCK.  This site is one of the better formed that has actual working examples that are formed well and easily works with a little tweaking if there is something off about them *cough*'official' build and code::blocks default mingw compiler*cough*

#include <iostream>
#include <SFML/Graphics.hpp>

int main (int argc, char** argv)
{
    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) ){
                std::cout << "Font failed to load" << std::endl;
        }
    sf::Text line1;

    line1.setFont( arial );
    line1.setCharacterSize ( 12 );
    line1.setPosition ( 340, 180 );

    sf::Text line2;

    line2.setFont ( arial );
    line2.setCharacterSize ( 12 );
    line2.setPosition ( 240, 180 );

    while (window.isOpen()){
                //using namespace std;  
                /*a better habit to get into is NOT using namespaces,
                that way you access each library specifically and know
                who you are accessing.
                */

                int numberinput;
                line1.setString ( "Enter a number:" );
                /*
                because cin halts the thread on it we can't refocus our window when
                the console gets called forward.  Also we don't draw our screen
                for the first time until after this halt.  One should either do
                an initial draw, or figure a way to loop it so that the initial
                drawing does get done.
                */

                std::cin>> numberinput;  //added std:: library accessor to these calls
                std::cin.ignore();  //<-does this do what you think it does?

                if ( numberinput < 10 ){
                        line2.setString  ( "Death! You entered in too low a number!/n" );
                }

                sf::Event event;
                while (window.pollEvent(event)){
                        if (event.type == sf::Event::Closed)
                                window.close();
                }

                window.clear();
                window.draw ( line1 );
                window.draw(line2);//add ones line2 to be drawn
                window.display();
        }
        return 0;
}
 
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 21, 2013, 07:42:13 am
Thanks Hatchet, I'll be sure to have a look around for a good, up to date C++ book, to be honest, it's a wonder I've even gotten this far because even as a newbie I've seen some god awful tutorials out there, they're either completely out of date or the writer either forgets outright to explain basic things, I still don't know much about formatting and indentation, I tend to just focus on getting the code to function for now.

Just a quick question, with the int main (int argc, char** argv can that be used in SFML as well then? I've seen that on SDL tutorials so I assume that must be a C++ function if it's in both languages.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on June 21, 2013, 08:40:10 am
You only need this signature of main() if you parse the command line arguments. Otherwise, just write
int main()

About books, be careful; there is a lot of terrible literature about C++. See here (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?page=2&tab=votes) for a good guide.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 21, 2013, 05:47:44 pm
Ah, that's interesting, I copy and pasted your code hatchet just to see if it was me and I found the same window freeze happens, are you by any chance using a different compiler to me? I use codeblocks.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on June 21, 2013, 06:50:03 pm
Ah, that's interesting, I copy and pasted your code hatchet just to see if it was me and I found the same window freeze happens, are you by any chance using a different compiler to me?
Again, this is supposed to happen. It has nothing to do with the compiler.

Please read our posts carefully, I mentioned it already in the very beginning, and The Hatchet wrote it directly in his code:
Why do you mix standard input and SFML rendering in the same loop? std::cin blocks the thread and you can't render and poll input regularly.
                /*
                because cin halts the thread on it we can't refocus our window when
                the console gets called forward.  Also we don't draw our screen
                for the first time until after this halt.  One should either do
                an initial draw, or figure a way to loop it so that the initial
                drawing does get done.
                */

Furthermore, there is no problem if you open new threads for new problems. In fact, it is strongly encouraged to do so.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on June 21, 2013, 08:56:02 pm
That 'freeze' will always happen whenever you call 'std::cin', no matter what, no way around it, that's what happens.  If you don't want your windows freezing out of focus then learn to handle sf::Event and add code for Keyboard Events and get rid of std::cin.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 21, 2013, 09:44:20 pm
Well that's weird, I don't know why I didn't get this before, maybe it's because I had a break and did something else for a bit :D so like you say, the std::cin stuff is console and so replacing that with SFML code will let it run.

This is why I keep treating SFML and C++ differently, because it seems to me from a newbie perspective that some of the basic C++ is messing with the SFML code because SFML seems to act more like an addon library/mod for the basic C++ than C++ itself or am I thinking about this the wrong way?

By the way, this sort of thing is why I think it would be better to keep everything in one thread, I tend to get very detailed with my questions so the discussions can go on a lot :P you'd just end up with several Lethn threads being bumped on the front page.

Edit: Oh and I'm looking at the TextEntered Event on SFML and it looks a lot more flexible than I realised, I think I'll check out the syntax some more.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on June 21, 2013, 11:44:21 pm
This is why I keep treating SFML and C++ differently, because it seems to me from a newbie perspective that some of the basic C++ is messing with the SFML code because SFML seems to act more like an addon library/mod for the basic C++ than C++ itself or am I thinking about this the wrong way?
Yes, you're thinking the wrong way. Don't put everything in philosophical context, the reason why this does not work is trivial. It has nothing to do with SFML in specific, or "libraries messing with C++".

If you read the tutorial carefully (which you should finally do!), you'll see that SFML (in fact, every graphical library) relies on constantly updating the main loop. This includes user input and rendering. std::cin interrupts this update, because it waits for a input in the console -- therefore, the window doesn't behave properly.

By the way, this sort of thing is why I think it would be better to keep everything in one thread, I tend to get very detailed with my questions so the discussions can go on a lot :P you'd just end up with several Lethn threads being bumped on the front page.
If there are different topics, make different threads. Very similar questions can of course be gathered in one thread.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 22, 2013, 03:00:34 pm
Just thought I'd say, yes it does look like it's a fairly simple issue Nexus, I was overthinking it. When I removed the console stuff the code works fine my only issue is now that I need to make SFML work like the console stuff and get some input going.

This goes back to another one of my issues where I'm thinking about how to implement a gold statistics or an experience point statistic, SFML should be able to handle updating loops shouldn't it? I already know from me experimenting with input that it can handle if functions easily.

Here's the sort of fixed code, I'll look in how to implement the if statement I was after properly, I think I already have something in mind, you lot helped me understand what was possible and what wasn't so thanks for that :D

#include <iostream>
#include <SFML/Graphics.hpp>
int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }
    sf::Text line1;

    line1.setFont( arial );
    line1.setCharacterSize ( 12 );
    line1.setPosition ( 340, 180 );
    line1.setString ( "Enter a number:" );

    sf::Text line2;

    line2.setFont ( arial );
    line2.setCharacterSize ( 12 );
    line2.setPosition ( 240, 80 );
    line2.setString  ( "Death! You entered in too low a number!" );






    while (window.isOpen())
    {

    sf::Event event;
    while (window.pollEvent(event))


{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( line1 );
        window.draw ( line2 );
        window.display();

    }

    return 0;

}
 
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on June 22, 2013, 03:06:42 pm
If you want to read text from the user, have a look at the TextEntered event in the API documentation and the event tutorial. You should be able to gather the necessary informations yourself, in case of specific questions you can ask again.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 22, 2013, 03:10:48 pm
I did have a look last night but it can handle numbers fine can't it? Because of course it's unicode and yes, I was planning on replacing that console input stuff with TextEntered :)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 22, 2013, 07:06:37 pm

I looked at the TextEntered event documentation and it seems to be suggesting that I need to put unicode in between some brackets, I find this a bit baffling, is there an explanation of why this is and so on that I can have a look at so I don't spend hours getting frustrated over it?
Title: Re: Lethn's Programming Questions Thread
Post by: Laurent on June 22, 2013, 08:26:08 pm
Quote
I looked at the TextEntered event documentation and it seems to be suggesting that I need to put unicode in between some brackets
Hum... ? Could you show the corresponding code instead of trying to describe it with your own words of beginner? ;)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 23, 2013, 02:18:00 am
I did say I was baffled :D

 
74  struct TextEvent
75  {
76  Uint32 unicode;
77  };

Its what appears on Event.hpp, I'm also looking at TextEntered, I'm not sure how to use them looking at this code.
Title: Re: Lethn's Programming Questions Thread
Post by: Laurent on June 23, 2013, 08:52:28 am
Quote
Its what appears on Event.hpp
And? What's your question? Where are these brackets that you mentioned?

Quote
I'm not sure how to use them looking at this code
Don't look at source code. Look at documentation, tutorials and examples on the forum/wiki.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on June 23, 2013, 05:41:40 pm
The Events tutorials explains the TextEntered event pretty good, even for how short it is.  When you poll the TextEntered event it returns unicode # for the character entered.  If you cast this to a string or char it will pop out the other side as that character, for example if you type an 'a' the event will return the unicode '97' which on the ascii table is a lowercase 'a'. 

So the event gives you the unicode, you just have to make a buffer to stuff however many character you want to get into (like if youwanted them to enter a name), cast the stored codes in the buffer however you want, apply whatever switch/if statements to your contents however you want.

That's what i pulled from the tutorial section anyways  :-\
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 24, 2013, 12:40:56 am
Aha! Yes, read it more carefully now so I know what you mean.

Quote
  The member associated to this event is event.text, it contains the Unicode value of the entered character. You can either put it directly in a sf::String, or cast it to a char after making sure that it is in the ASCII range (0 - 127). 

My only concern with this method is getting this working with loops, which is of course what you need to make your statistics in the games like gold etc. it's easy for me to make something static but I'm probably going to have to mess with this quite a bit before I get it working the way I want.

Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 24, 2013, 09:57:21 am
#include <iostream>
#include <SFML/Graphics.hpp>
int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }
    sf::Text line1;

    line1.setFont( arial );
    line1.setCharacterSize ( 12 );
    line1.setPosition ( 340, 180 );
    sf::Text line2;

    line2.setFont ( arial );
    line2.setCharacterSize ( 12 );
    line2.setPosition ( 240, 80 );

            if ( event.type == sf::Event::TextEntered )
            {
                line1.setString ( "Enter a number:" ) << static_cast <char> ( event.text.unicode );
                if ( event.text.unicode < 128 );
            }




    while (window.isOpen())

    sf::Event event;
    while (window.pollEvent(event))



{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( line1 );
        window.draw ( line2 );
        window.display();

    }

    return 0;

}
 

Here's what I have planned so far, obviously going to be editing this more and changing things as I go since it isn't working yet.
Title: Re: Lethn's Programming Questions Thread
Post by: Laurent on June 24, 2013, 10:31:23 am
Seriously, you should really learn C++ first and practice with simpler programs. You're going to waste your time, coming to the forum everyday for new problems or questions, if you try to learn this way.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 24, 2013, 10:57:13 am
Reading through stuff now Laurent :D doesn't mean I can't mess with SFML along the way.
Title: Re: Lethn's Programming Questions Thread
Post by: Laurent on June 24, 2013, 11:54:28 am
Quote
doesn't mean I can't mess with SFML along the way
You can do whatever you want, but you're going to waste your time (and ours), because the only answer to most of your posts is "learn C++".

Look at your last code: you're trying to use the "event" variable before it is declared. Your code doesn't even compile because there's a missing { on the main loop. You don't even know how to indent your code properly so that it is more readable.

You don't need a forum to solve these problems, just learn and practice.

I don't mean to be rude, just trying to help you learn programming/C++/SFML more efficiently ;)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 25, 2013, 02:20:46 pm
lolz I'm looking at stuff now and now I know what you mean, the books listed do seem to explain the basics very well so I'll be having a read through of that now. Nice I finally understand properly what the semi-colons and brackets are about >_> the online tutorials are pretty crap :S.

Edit: Oh! I've already found updating loops that work like a game should! Badass! :P
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 26, 2013, 03:31:29 am

#include <iostream>
#include <SFML/Graphics.hpp>



int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int gold;
    gold = 100;

    sf::Text goldtext ( "You have", arial, gold = 12 );
    goldtext.setPosition ( 700, 100 );


    while (window.isOpen())


{
    window.close();
}

    window.clear();
    window.draw ( goldtext );
    window.display();


    return 0;
}


 

I've been looking at some of the books you guys gave me and already it's starting to help a lot, I can even ask questions in a less noobish way! :D Right now I'm trying to combine integers with SFML text, so far I haven't got any errors after some tinkering but the screen just opens and closes without doing anything.

Have I missed something out that's obvious?
Title: Re: Lethn's Programming Questions Thread
Post by: G. on June 26, 2013, 05:18:01 am
I'm not sure if it's a joke or not. ??? What do you think window.close(); does? Why is your code worse than the one before?
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 26, 2013, 05:35:24 am
LOL worse? I'm just going by what I read on the documentation and I didn't realise that you didn't really need it so that's gone now, maybe instead of just saying it's gotten worse you could explain where I'm going wrong? That aside the reason I had the main stuff like this is because that was the only way I could even seem to get it half working, codeblocks puts errors up if I try anything else.


#include <iostream>
#include <SFML/Graphics.hpp>



int main ()
{

    sf::RenderWindow window(sf::VideoMode( 800, 600 ), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int gold;
    gold = 100;

    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setString ( "You have" gold "gold" );
    goldtext.setPosition ( 700, 100 );

    window.clear();
    window.draw ( goldtext );
    window.display();


    return 0;
}


 

Found what I needed, the documentation explains all the possible options for string.

http://sfml-dev.org/documentation/2.0/classsf_1_1String.php#abc989da7f4fb873ab29188d40772ab24
Title: Re: Lethn's Programming Questions Thread
Post by: binary1248 on June 26, 2013, 12:38:59 pm
Laurent should really consider opening up a separate C++ help forum. People probably understand "Help requests that are not related to a specific module" in an all too general way. It should still be related to SFML in some way.

Also... did you have a look at the FAQ? Here is a link in case you can't find it: https://github.com/SFML/SFML/wiki/FAQ#wiki-grl-learn

As time passes, people are going to get more reluctant to help you considering you chose the head through the wall method of getting things done. This thread has been going on for a week and in that time instead of trying all possible combinations of code to make the compiler shut up and build you could have read an online introduction to C++ like the one at http://www.cplusplus.com/doc/tutorial/ among many others. Don't interpret the lack of replies you will be getting here as being unhelpful, it will be for your own good.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 26, 2013, 02:59:37 pm
That's actually the most helpful post I've seen here yet Binary, I didn't know about that faq and it's very helpful because now I know all the specifics of what I need to learn rather than just staring randomly at C++ books and only getting bits of knowledge I can use for SFML, thanks for the links.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on June 26, 2013, 09:38:05 pm
That's actually the most helpful post I've seen here yet Binary, I didn't know about that faq and it's very helpful because now I know all the specifics of what I need to learn rather than just staring randomly at C++ books and only getting bits of knowledge I can use for SFML, thanks for the links.

This should tell you that there are some deeper c++ issues than you think.  All the good C++ books I've read have always been laid out in such a way that by starting from Chapter 1 and progressing linearly through it I will learn everything a beginner needs to know about C++.  Books are generally laid out in a way that you start at the beginning and learn the building block in an order that brings their natural evolution to fruition.  If you are just turning to random pages and subjects trying to find one small piece of code to fix what you have wrong then you are doing it wrong.

Seriously just sit down with a book, ONE book, and start reading and doing the examples it has from the start to finish.  Once you're done adding SFML to a project will be easy-peasy.

Think of it this way, if you are having problems understanding what {} and ';' do (which groups parts of code and is the end of line syntax delimeter) and don't know how to properly manipulate strings yet
 goldtext.setString ( "You have" gold "gold" );
(This line is all kinds of wrong).  Then what makes you think that doing anything further down the road such as managing States, inventory, combat, creating and managing all your entities, pointers, new/delete(if you have to), vertex array usage, proper texture management is going to be any easier to understand or even have a 'fix' that you can find in a book?

At my last university I was at we took a year of Java and 2 years of C++ before they even let us touch other libraries for them.  Just straight basic Java and C++ was all I needed to learn the fundamentals and libraries seem like a snap now.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on June 26, 2013, 11:23:00 pm
I get what your saying Hatchet :D I definitely like the look of C++ primer books wise so I'll probably just get to reading through all that properly, what I like about it is that it points at the different bits of the code ( quite literally ) and properly explains what it all means, too often, especially with the tutorials you get the people who write them trailing off or just outright not bothering to mention completely basic things to you.

I guess I'm just getting frustrated as well because I honestly don't have too difficult a time getting this kind of stuff to work with the console but when it comes to SFML it all goes to hell. I'm going to hurry up and learn C++ properly so I can get to making games :D so far looking at C++ is helping me get a decent idea of things, I just need to know what actually works.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 02, 2013, 11:59:58 pm
I'm just thinking it through now after reading through the book and some stuff I found on google ( I'm learning all the different vocabulary properly now thanks to reading through C++ and the SFML book :D ) am I right in thinking that string buffers and insertion operators are the main thing you need for displaying integers in text? I found some very helpful answers when I changed the keywords I searched for, this is the sort of thing I've been looking at for those who are curious, should also help the vets know if I'm on the right track.

http://gamedev.stackexchange.com/questions/43431/how-to-display-text-and-numbers-in-sfml-2-0
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 03, 2013, 01:36:47 pm
am I right in thinking that string buffers and insertion operators are the main thing you need for displaying integers in text?
You probably mean string streams, there are no string buffers in C++. Yes, the std::stringstream class allows you to convert from and to strings.

C++11 also offers the std::to_string(), std::stoi() and similar functions -- these are helpful when you only want to convert a single value, instead of concatenating multiple ones.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 03, 2013, 02:13:07 pm
lol! Still got lots to learn, thanks for the heads up, one thing I always find is a real piss take no matter what profession you go into they all have their own vocabulary and often forget to explain it all to you >_<
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 03, 2013, 10:24:54 pm
You guys will like this, finally got what I wanted working, I just need to look at getting the numbers to update and stuff when I click a mousebutton or something and so on.


#include <Iostream>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 100;

    std::ostringstream gld;
    gld << "Gold:  " << goldamount;




    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 50, 50 );

    goldtext.setString ( gld.str () );



    while (window.isOpen())
    {

    sf::Event event;
    while (window.pollEvent(event))

{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( goldtext );
        window.display();

    }

    return 0;

}

 
Title: Re: Lethn's Programming Questions Thread
Post by: G. on July 03, 2013, 10:47:17 pm
That's pretty much the tutorial about drawing text.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 03, 2013, 10:57:43 pm
lol yeah exactly, what's interesting is in the end I didn't need to add that much on to get it all working which is nice >_< I used the example in the gamedev thread to help me work it out, now comes the trickier part of making it all interactive. The main thing I ended up having to figure out was that you needed for some reason to add a sstream header in then it all started working fine.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 03, 2013, 11:47:31 pm
You had to include the <sstream> header because you were using 'std::ostringstream gld;' which ostringstream is a class presented thru said header.

Again, its great you want to learn SFML but you really need to step back and get general programming knowledge down first.  If you didn't know that you had to include a header to get something from that headers class to work then your programming and/or c++ knowledge is still severely lacking.  Before diving deeper into SFML you may want to at the very least write small programs that revolve around different aspects of programming.  Such programs could be:

Console based:
1.)  Take input from the keyboard, only allow numbers, and then calculate whether that number is prime or not, return true or false, if true return the primes root, if false give a close estimate.
2.)  Simple text file I/O
3.)  Strings, learn to manipulate strings with user input and input from a text file.  Print strings back to the console and print back to another text file.
4.)  A program that takes a text file of random numbers and gives the user an option to pick one of X number of 'sorts' to sort the list.  Sorts could be quicksort, bubble sort, heap sort, any other kind of sort you want.
5.) a simple console based Tic-Tac-Toe game
6.) console based Othello/Chess/Checkers game
7.)  a program that makes use of pointers such as your own Linked List

these are just a few examples of the simple basic things I was taught within my first year of University CS courses.  All of these were done with just the C++ standard library on the console.  If you can get all of these done then you should have the basic understanding of Control structers, control loops, program flow, user/file input and output, pointers, references and values.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 03, 2013, 11:50:16 pm
what's interesting is in the end I didn't need to add that much on to get it all working which is nice [...] The main thing I ended up having to figure out was that you needed for some reason to add a sstream header in then it all started working fine.
It's nice that you found a solution, but the approach of trying around and putting code snippets from different homepages together won't work in the long term. Especially not with C++.

You have to understand  exactly what you're doing. And if you don't know why you need the <sstream> header, you should definitely read your C++ book more carefully.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 04, 2013, 01:54:43 am
I'll be looking through the C++ book for sure because it does help, the only problem is reading through a 1000+ page book like that is pretty boring ;_; the explanations are fine, it's just a dull book unfortunately. I find I'm better at learning in bits depending on what I'm doing so I'll get it eventually.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 04, 2013, 11:16:00 am
Why don't you try the tasks suggested by The Hatchet? Like this, you can apply the knowledge after each step. But for diving directly into SFML, it's probably too early, and you waste too much time understanding stuff and struggling around with compile and runtime errors...
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 19, 2013, 10:20:31 pm
If it seems like I ignored you last time Nexus sorry about that, I've been busy :D I'm actually working on trying to make simple stuff like that now to help me understand the code and it's working well.

I've run into a problem though, while I understand pretty easily now how to deal with strings and getting static text on the screen I'm trying to get the integers to update itself in a way much like you'd find in an RTS or Simulator. I've been reading through the C++ book normally and so I've been looking around the internet and so far the only thing I've found is incrementing and decrementing integers. Either I've misunderstood what they're actually for due to the vocabulary or I'm not using them in the correct way, if you guys could point me to the correct type of code I need to learn or explain things I'd appreciate it.

Here's the code, same as before, but I've done little tweaks and stuff like arranging the words around the statement so I can get used to how it all works and what breaks the code etc.


#include <Iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;
    ++ goldamount;


    std::ostringstream gld;
    gld << "You have " << goldamount << " Gold";



    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( gld.str () );



    while (window.isOpen())
    {

    sf::Event event;
    while (window.pollEvent(event))

{
 if (event.type == sf::Event::Closed)
 window.close();
}

        window.clear();
        window.draw ( goldtext );
        window.display();

    }

    return 0;

}

Note: I just double checked and yes I think I have misunderstood but it looks like I need to find some sort of function to add on to make it repeat, some kind of loop perhaps? Time to do investigating :D

Edit: I think it's for loops that I need to go and study, let me know if I'm wrong!
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 20, 2013, 12:23:51 am
OKAY, so it's good to hear you are reading through a c++ book but sad to see you not comprehending some of the basics.

Integers are numbers.  whole numbers, real numbers pure and simple.  type int can hold a number that ranges from –2,147,483,648 to 2,147,483,647, unsigned int can hold a number 0 to 4,294,967,295 typically.  There is nothing magical or hard to understand about integers, they are numbers, you can perform arithmetic with them, addition, subtraction, multiplication, division, modulus.

You are on the right track kinda with your loop statement.  The thing you don't seem to realize is you already have a loop running.  your while(window.open()) { ... } is a loop.  So to give you a working example of how to add 1 to your gold amount each iteration through your main program loop and print it to the screen I give you this.

#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "C++ Programming Test");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;

    std::ostringstream myStream;
    myStream << "You have " << goldamount << " Gold";



    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( myStream.str () );

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw ( goldtext );
        window.display();

        goldamount++; //adds 1 to our goldAmount integer
        myStream.str(""); //clears the string stream, correct way should be myStream.str(std::string())
        myStream << "You have " << goldamount << " gold"; //restuff the stream
        goldtext.setString(myStream.str()); //get string from the stream and set to text
    }
    return 0;
}

 
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 20, 2013, 12:25:00 pm
Okay that makes more sense now I think and I'm seeing where I went wrong, a lot of the solutions I saw seemed far too complicated for what I was trying to achieve. So if I'm right, the blank quotation marks clear the numbers and then you simply repeat the original function after to add the number?

It looks to me like this function would only work once, what if I wanted it to increase in multiples of ten or something? I keep thinking I'd have to use something like symbolic constants or floating point types but I wouldn't know the proper syntax in SFML, may just need to experiment with this example and see what I can come up with :D

Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 20, 2013, 01:23:55 pm
for increasing by another amount, say 10 would look like
goldamount = goldamount + 10;
or
goldamount += 10;
for a shorter version.

Symbolic constraints?  floating point types?  Like seriously you are overthinking a simple concept as numeric arithmetic.  Floating point is also just the fancy for NUMBERS WITH A DECIMAL POINT.

And why would you think the addition to goldamount would only work once?  cuz its only written once?  Look where it's written, its in the main while() loop of your program.  And what does a while() loop do?  It LOOPS and runs all the code written inside of it over and over and over and over and over and over and over again until its termination requirement has been met.  The program thread doesn't just decide to stop at the end of the loop and wait, it just goes and goes.

If the simple concept of a control structure like a while() loop and basic numerical arithmetic are beyond your current scope of understanding maybe you need to find a different book. If you've been truthful about reading through a c++ beginners book then these concepts should have been covered in like the first 2 chapters.  Most books i've seen take you through user input/output, simple data types and manipulating them and control structures like while() for() do() almost always in the first couple chapters.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 20, 2013, 02:15:23 pm
wow I have been overcomplicating it thanks, the interesting thing is I've seen these kind of methods being used but they're all incredibly complicated for what they're trying to do, I'm going to have read through of those loop sections again, thanks for the explanation, I think I'll have a fairly easy time of all of this now.

As for basic mathematics, it's always been a problem for me because of crappy teaching though I've noticed that seems to be a common trend in schools now to not teach it properly. I'm going to experiment and see what I can come up with for some reason I get it better when I see it all working.

Edit: Yep! I read through the section again and I get it now, I'll post up the code again when I have it all working.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 20, 2013, 02:37:55 pm
Oh that's awesome! I've got the incrementing working brilliantly now thanks to the example you gave hatchet, I just need to stop the while loop from interfering with the window event! Been studying for ages for this :D
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 20, 2013, 02:53:11 pm
Oh that's awesome! I've got the incrementing working brilliantly now thanks to the example you gave hatchet, I just need to stop the while loop from interfering with the window event! Been studying for ages for this :D

Can you clarify what you mean by this?  The while loop doesn't interfere with getting window events, in fact if you didn't have the event loop inside the main game loop you wouldn't be able to process any events at all.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 20, 2013, 03:04:37 pm
Hmm, probably overthinking again, what I'm trying to do now is get a basic while loop up and running but for some reason when I enter it in like this the program freezes, I've sometimes got it up and running with the text showing but then it just freezes after that as well. I tried putting in the while loop inside the other while loops etc. but it always gave the same results.

The example you gave me worked fine when it was just the int goldamount ++; by itself

#include <Iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;

    std::ostringstream gld;
    gld << "You have " << goldamount << " Gold";





    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( gld.str () );

    while (window.isOpen())
    {

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw ( goldtext );
        window.display();

        while ( goldamount + 5 ); /* the while loop that causes the window to freeze */
        gld.str ( " " );
        gld << "You have " << goldamount << " gold";
        goldamount ++;
        goldtext.setString ( gld.str() );

    }
    return 0;
}


 
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 20, 2013, 03:33:07 pm
What exactly are you trying to achieve with
while ( goldamount + 5 );
? This is an infinite loop with no body.

Are you sure you know the C++ basics? It really doesn't look so, and you should finally realize that :-\
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 20, 2013, 03:38:58 pm
I'm reading through this >_< :D I'll get it eventually, I just need to make sure I put the right stuff in the body don't I?

Quote

The while loop is a for loop stripped of the initialization and update parts; it has just a
test condition and a body:
while (test-condition)
body

First, a program evaluates the parenthesized test-condition expression. If the expression
evaluates to true, the program executes the statement(s) in the body.As with a for
loop, the body consists of a single statement or a block defined by paired braces. After it
finishes with the body, the program returns to the test condition and re-evaluates it. If the
condition is nonzero, the program executes the body again.This cycle of testing and execution
continues until the test condition evaluates to false (see Figure 5.3).

Clearly, if you want the loop to terminate eventually, something within the loop body must do something to affect the test-condition expression. For example, the loop can increment
a variable used in the test condition or read a new value from keyboard input. Like the
for loop, the while loop is an entry-condition loop.Thus, if test-condition evaluates to
false at the beginning, the program never executes the body of the loop.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 20, 2013, 03:42:49 pm
The problem is, you're wasting a massive amount of time with your approach. You are constantly experimenting with language features and wondering about why something works or fails. And it doesn't help to read up on single language features like the for loop; your next problem is certain to show up soon.

You need an understanding of how the features work together. I really suggest to read the book about C++ thoroughly. If you invested the time you're wasting with try&error into reading (and understanding what's written), you would progress much faster. And you would actually learn things for the future, a lot of topics cannot be learned by doing.

We have already said this multiple times now -- I really hope you realize that you're lacking basic knowledge which you cannot simply learn by asking forum questions and reading internet tutorials. This thread is going nowhere.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 20, 2013, 03:55:14 pm
^ What nexus said.  If you want some help outside of your reading material PM me and I can try and help.  I have a super slow boring job so I got plenty of time on my hands.

And no, you don't need to just 'put something in the body' of your 'while ( goldamount + 5 );'  You have the test condition completely wrong which is why its an infinite loop.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 21, 2013, 05:55:02 pm
I think you guys are suffering from the same thing the writer of this book is suffering and that's the problem of writing out vocabulary and words and expecting someone completely new to understand it all immediately so I pretty much have no choice but to resort to trial and error because that's the only way I'll be able to learn.

The examples are fine and I'm sure I'd understand the explanations if they were written in English but it pisses me off when time and time again I come across tutorials/books/people who use vocabulary and don't even explain to beginners what they mean.

Here's a perfect example of what I'm talking about, the book did a great job of showing me the absolute basics, explaining that the ";" was something you used to end the code etc. but as things have gone on it forgets about explaining this kind of thing entirely or just doesn't bother.

I'm surprised you didn't spot it to be honest because I'm still having trouble understanding that quote above but it rants on about test-conditions and refuses to explain to me what it actually means so I can't implement the code properly. This is something that a lot of professionals do and it's incredibly annoying and makes me wonder just whether they actually understand the things they've been taught which is why I keep asking so much about it. It isn't anything to do with not reading the book like you've immediately jumped to, it's the exact opposite, I've been trying to find a proper C++/programming glossary out there and I haven't really found anything yet.

On the bright side, I can get while loops and increments running separately just fine but for some reason ( and I suspect it's going to involve programming vocabulary again ) they're not really doing anything when I put them together.

#include <Iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;



    std::ostringstream gld;
    gld << "You have " << goldamount << " Gold";





    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( gld.str () );

    while (window.isOpen())
    {

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw ( goldtext );
        window.display();

        while ( goldamount > 5 )
        {
        gld.str ( " " );
        gld << "You have " << goldamount << " gold";
        goldamount ++;
        goldtext.setString ( gld.str() );
        }


    }
    return 0;
}


 
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 21, 2013, 07:07:12 pm
Sent you a PM about vocabulary stuffs.

As far as why your while() loop isn't doing anything lets look at it:
while ( goldamount > 5 )
{
     //do stuff
}
 
Your program thread will never ever enter this loop since the program first goes "Is goldamount greater than 5?"  since goldamount starts at 0 and you never add any to it outside of this loop the answer is "No, goldamount is not greater than 5 (this equates to FALSE)"  And since the test-condition returns as FALSE the thread never enters the loop. 

If you were to set goldamount to 6 or greater before the thread gets to this loop the test condition would evaluate to TRUE and then it would enter the loop and it would stay in the loop forever since goldamount would always be greater than 5.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 21, 2013, 07:40:52 pm
The examples are fine and I'm sure I'd understand the explanations if they were written in English but it pisses me off when time and time again I come across tutorials/books/people who use vocabulary and don't even explain to beginners what they mean.
But then you have chosen a bad book, good books explain their vocabulary. Unfortunately, there is a mass of bad literature about C++, because as you assume, a lot of authors haven't completely understood the matter themselves. Which one do you read?

Here's a perfect example of what I'm talking about, the book did a great job of showing me the absolute basics, explaining that the ";" was something you used to end the code etc. but as things have gone on it forgets about explaining this kind of thing entirely or just doesn't bother.
What does it forget? Of course books don't explain the same things again and again, but I don't think that's what you mean.

I think you guys are suffering from the same thing the writer of this book is suffering and that's the problem of writing out vocabulary and words and expecting someone completely new to understand it all immediately
This may be true to some extent, but consider that we've all had the same problems as you currently have. We had to find a way to inform ourselves about vocabulary and things we didn't understand; being able to get informations is one of the most important aspects of programming. But I'm also aware that some books teach really badly, I have seen this when learning C++ myself. It would be nice if you could avoid that by directly knowing which books are worth reading.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 21, 2013, 08:55:32 pm
Thanks for the help guys, I do appreciate it, also hatchet, you're right, before you posted I accidentally got it working and the function now works when I do more than 5. I think I've been misunderstanding how to use incrementing numbers so I'll have to have a look at more examples and explanations of it. If it helps, I've got a screenshot of the kind of integer thing I'm trying to achieve. The increment by itself works brilliantly but I'm going to have to look at how to change the way they work because once I do this I can get a basic game up and running so it looks like I need to go and do more research and find different books.

Take a look at the integer on the top left, that's the kind of thing I'm thinking of.

http://i1-news.softpedia-static.com/images/reviews/large/startopia_006-large.jpg

If you're wondering Nexus, I'm reading through C++ Primer Plus, 6th Edition, I think I remember someone mentioning not to read beyond a certain edition? I think I've just understood why :P
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 21, 2013, 09:07:10 pm
C++ Primer Plus has indeed not  a very good review (http://accu.org/index.php?module=bookreviews&func=search&rid=1744). As opposed to the C++ Primer, which is among the most often recommended beginner books.

See also: The Definitive C++ Book Guide and List (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 21, 2013, 09:11:18 pm
I've been confused! I'll have a look at other books then and see if that helps, probably will, I already have that thread bookmarked :D

Edit 1: This certainly looks a lot better, it's explaining things that the 6th edition missed out

Edit 2: I did get a PM from hatchet about vocabulary but

Quote
A condition is an expression that yields a result
that is either true or false.

YEYYYYYYYYYYYYYYYYYYYYYYYY!!!!!! That's exactly the kind of information I need.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 02:48:03 pm
I just had an idea and I wanted to know whether it would work or not, what's stopping me from just using sf::Time and displaying my stuff that way? Are there restrictions to how it works or could I quite happily implement my C++ programs using seconds etc. as far as I can work out I don't know why not but that's why I'm asking you guys.

sf::Time etc. just seems like it would be a lot more flexible way of doing things rather than messing around trying to figure out ways to get incrementing working and I could get the same sort of effects I want.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 24, 2013, 02:50:03 pm
what's stopping me from just using sf::Time and displaying my stuff that way?
What are you talking about? sf::Time stores a time, nothing else. It can't replace all the C++ logic you need in your program ???
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 03:06:38 pm
If I'm thinking of the wrong command then sorry about that, but what I mean is using seconds, milliseconds etc. instead so I can get a counter properly working because so far the only C++ I've found does all the stuff instantly and incrementing just seems to do it in 1's from what I can make out.

hmm >_< need to do m0ar reading.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on July 24, 2013, 04:29:47 pm
You need to explain what you want more precisely. Measuring time and counting in discrete steps are two completely different problems.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 05:12:19 pm
In that case looks like I can't use that idea, what I've been trying to do is to limit or change the incrementing in some way, I thought the while loop was the way to do it but the code etc. I've seen only deal in very basic methods.

The best example I can give is through a youtube clip of a game called Startopia, take a look at the energy meter on the top left ( a bit blurry I know ), that's what I'm aiming for and I guess it's my main project at the moment.

https://www.youtube.com/watch?v=9dVhlOl3-2A

. Updating numbers

. Limited

. Changes according to pressing a key/mousebutton etc.

. Bonus: getting a bar similar to the one in this video, but I'm focused on just getting the numbers part right for now :D

I have no problems getting these things to work immediately when it just flat out compiles the stuff I write, the problem is making it all happen while it's on the screen like in the video, I'm sure there's a proper programming word for it but the only thing I can think of is just updating integers on the screen.

This is why I thought of using the seconds and milliseconds in SFML but if that's not possible then I've got to keep reading again.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 24, 2013, 09:04:59 pm
From what you are describing  (and i looked at the vid just to make sure), you should already have all the knowledge you need to achieve a number counter on the screen.  The basics of having a high score/energy counter/hit point/ammo counter only consists of what you've already done.  All you need is:

-Know how to draw to the screen (drawing to screen with text)
-Store the number in a variable (using integers because decimal points aren't needed for whole numbers)
-Update that stored number

I'm not quite sure what magic function you are hoping to find in your reading.  Programming is about having all these super basic building blocks and then implementing your own ideas and function with them to do what you want.

Like i said before, i usually have a bunch of free time so if you PM me I could become a sort of tutor for you.  I could write up some simple programs and examples to do whatever ideas you want and make sure are doable then give you some tips and knowledge how to do them and grade your programs against mine.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 09:47:05 pm
Thanks Hatchet, you pretty much answered that question, I just couldn't phrase it properly, so it looks like I need to go and look at how to update the numbers I have in my code in that case, time for some reading.

I do already know how to do most of the stuff like I said, it's just getting the damn numbers to update themselves now :D
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 24, 2013, 09:52:24 pm
Well they aren't just going to magically update themselves.  You have to tell them when and how to update.  A simple way to see it happen would this:

(this is just pseudo-code but the ideas laid out)
while(sf::Event)
     -If Event is a Keypress (Spacebar for example)
     -Add however much you want to goldamount variable

That would let you hit a key and add whatever you code it to add
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 10:25:30 pm
Ahh, hang on, I think I tried this before but ran into problems, despite having put my + 5 in the braces nothing happens in the while loop, thankfully I don't get any crashes though, made me think I was looking at the wrong command but it looks like my coding is wrong.

#include <Iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), " ");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;

    while ( goldamount )
    {
        goldamount + 5;
    }


    std::ostringstream gld;
    gld << "You have " << goldamount << " Gold";





    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( gld.str () );

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw ( goldtext );
        window.display();


        gld.str ( " " );
        gld << "You have " << goldamount << " gold";
        goldtext.setString ( gld.str() );

    }
    return 0;
}


 

Edit: Yep and when I change the value in the test condition ( know the vocabulary now yey! :D ) the while loop crashes the program.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on July 24, 2013, 10:39:45 pm
Send you a PM over this, lets start with the PM help so we don't tie up the forum space.  If we hit a problem I can't help you with then we will return to the forum (or if i'm not online for a while and you need help)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on July 24, 2013, 10:50:18 pm
lol alright, I'll post you it there, I do think it's helpful though to keep the solutions and stuff public.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 02, 2013, 02:34:35 am
I'm going to post updates whenever I do something significant, with the help of hatchet I managed to get some basic incrementing like I wanted, I just need to figure out how to get the numbers updating without any user input now.

#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    int goldamount = 0;


    std::ostringstream gld;
    gld << "You have " << goldamount << " Gold";





    sf::Text goldtext;
    goldtext.setFont ( arial );
    goldtext.setCharacterSize ( 12 );
    goldtext.setColor ( sf::Color::Yellow );
    goldtext.setPosition ( 20, 20 );

    goldtext.setString ( gld.str () );


while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{

if (event.type == sf::Event::Closed)
window.close();
}

           if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::A ) )

           {
               goldamount --;
           }
           if ( sf::Keyboard::isKeyPressed( sf::Keyboard::D ) )
               goldamount ++;

        window.clear();
        window.draw ( goldtext );
        window.display();


        gld.str ( " " );
        gld << "You have " << goldamount << " gold";
        goldtext.setString ( gld.str() );

    }
    return 0;
}


 
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 02, 2013, 02:37:10 am
I am now working on doing the same sort of thing but with a coloured bar, I have the rectangle drawn and everything is compiling but now I need to figure out why the if statement isn't working as it should. As you might guess looking at the code I'm trying to make it so when you hit a button the rectangle changes size across the X axis, just like you'd get with a health bar or other statistic in a game.

#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    sf::RectangleShape health ( sf::Vector2f ( 120, 20 ) );
    health.setFillColor ( sf::Color::Green );
    health.setPosition ( 10, 10 );

    if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::Left ) )

    {
        health.setSize ( sf::Vector2f ( 100, 20 ) );
    }


while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{

if (event.type == sf::Event::Closed)
window.close();
}
        window.clear();
        window.draw ( health );
        window.display();

    }
    return 0;
}


 
Title: Re: Lethn's Programming Questions Thread
Post by: Gobbles on August 02, 2013, 05:44:41 am
I assume you mean that when you press Left, your health doesn't update and the if statement you are referring to is the one below.

if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::Left ) )

    {
        health.setSize ( sf::Vector2f ( 100, 20 ) );
    }


while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{
 

Your issue is that you can't access the the code once inside the while loop, as it only happens before hand.
In order to fix this, move the if statement to inside the while loop so it gets hit when you make the key press.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 02, 2013, 10:34:12 am
Ah yes, thanks! I seem to get the overall idea now I just make silly mistakes, when I was setting it all up I forgot that i needed to draw the rectangle at the end to make it appear on the screen lol >_<

Edit: Works fine now, I just need to tweak it some more, I thought I'd try something more fun and graphic based because I was getting tired of C++ :D
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 03, 2013, 04:26:48 pm
By the way guys, I'm having a look at getting animation into my SFML code, if you know of any good tutorials out there that explain things right I'd like to have a look at them. I also have a question about it, I keep hearing that sprite sheets are commonly used in 2D games and while I have no problem constructing them I have a piece of software that allows me to create some really nice animations and just easily export them as image sequences.

Is there any particular differences between me using image sequences or sprite sheets in the code or are these just two different ways of implementing animations? I ask this because being able to use image sequences would really help out my games and make them a lot less static because I could animate absolutely everything on the screen.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on August 03, 2013, 04:29:43 pm
What are image sequences, or how do they differ from sprite sheets?

You could have a look at Thor's animations to see how a possible implementation looks like, or directly use it in your projects.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 03, 2013, 06:30:37 pm
Well I can use this software called pencil, it's really nice to use ( for me at least :D ) and what it can do is either export my drawn frames as movie files or as a series of .pngs etc. the software uses the term 'image sequence'. I know how to do all the animation because I've been learning drawing way before I just need to understand it in the programming context.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on August 03, 2013, 08:02:49 pm
sprite sheets and image sequences are one in the same I'm pretty sure.  spritesheet is just a generic term to call any image file that contains multiple sprites on it, be it an animation sequence, tilesets, sprites for world objects, etc.
Title: Re: Lethn's Programming Questions Thread
Post by: Barlog on August 03, 2013, 09:14:02 pm
Image sequence and Spritesheets only have one thing in common. Either of them is graphical file in some format (png, jpg, tif, gif, etc).

For the rest they differ in following.
0. Images sequence (as output from Pencil) is the set of n files, where each one is one frame of animation.
1. Spritesheet is collection of usually similar in size images in one file. It could be animation, or image data for terrain tiles, or graphics for your game items.

From a programming perspective they differ in nearly same way.
0. For images sequence you must use as many sf::Textures as you have files. E.g. If you have 10 frames (10 files), then you need ten sf::Texture variables (or one vector of 10 sf::Textures) to hold image data.
1. For spritesheets you declare and define one sf::Textire variable and use different offset of TextureCoordinates to draw a sprite.

Hope this clarify things a bit.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 04, 2013, 07:11:28 am
thanks guys that's actually cleared things up a lot, my only fear now is the idea of having to add 30 frames any times I want to put a nice animation into my game, is there any way to batch add them in or is this just one of the more painful aspects of programming and why everyone keeps their animations really simple?

If I figure this out I'll be able to have some really nice building animations in my games etc. so I'm quite happy to get it done I just hope there are ways to make it less tedious, would the C++ break function be something to look at?

Edit: nope, break is the wrong one I'm thinking of but I remember there being a statement that lets you execute several other pieces of code in a batch which would probably be perfect for animations, hatchet mentioned it to me at one point.
Title: Re: Lethn's Programming Questions Thread
Post by: Gobbles on August 04, 2013, 07:20:54 am
This is where setting up an animation class for a Texture Atlas(a sprite sheet) really comes in handy.
Creating a class that will allow you to load in a new texture, give the animation a name, how many frames, whether it should auto-repeat(like an idle animation) or not (like an attack animation) and also set up the sprite rectangle to use for each frame will also be handy.

Animations are complex stuff and setting them up varies greatly on what you need. Its up to you as the programmer to decide what you need and how to implement it. Such is what game programming is all about after all.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on August 04, 2013, 03:20:54 pm
so I'm quite happy to get it done I just hope there are ways to make it less tedious, would the C++ break function be something to look at?
If you mean the break keyword -- no, again. If you haven't learned its meaning by now, it's more than time! Don't even start with SFML as long as you don't know basic control structures. Apparently you have still not considered our advice to learn C++ :(

but I remember there being a statement that lets you execute several other pieces of code in a batch which would probably be perfect for animations, hatchet mentioned it to me at one point.
Functions? :o

Seriously, learn the language. You're still guessing around -- what you need is an overview over language features and the knowledge how to combine them. You have the imagination that there is exactly one C++ feature for a specific task, which is completely wrong. Every task requires a combination of dozens of language features. And unless you learn how to use your tools, you won't be able to combine them and you'll still be guessing in a year...

This is where setting up an animation class for a Texture Atlas(a sprite sheet) really comes in handy.
Creating a class that will allow you to load in a new texture, give the animation a name, how many frames, whether it should auto-repeat(like an idle animation) or not (like an attack animation) and also set up the sprite rectangle to use for each frame will also be handy.
Like thor::Animator I mentioned earlier. But this requires again basic C++ knowledge.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 07, 2013, 05:23:02 pm
*currently reading through variables and basic types*

You can keep claiming bugger all about what I'm reading all you like Nexus, doesn't mean any of it's true. As for the way I'm treating SFML, from my learning so far i've found it's not necessarily just C++ and it's not by itself either ( I also meant statements not functions, everybody forgets things >_> ). It's more like a mod or an addon to C++ more than anything from what I've looked at and makes a lot of game/media related tasks a lot easier.

Thanks to peoples comments I think I have a rough idea of how to get animations in but I'll keep reading through the C++ book because as I've said before it's making things a lot easier to understand, particularly with how this one is teaching the vocabulary as you progress.

Note: I looked through the PM and I found it, switch() statement is the one I was thinking of! I'm thinking of using that when I learn how to do everything properly.


Edit: By the way, here's a small preview of the type of thing I'm going to be testing out animation wise this type of stuff can be from 30 - 200 frames long or even longer depending on what you want to do: http://www.swfcabin.com/open/1375887388
Title: Re: Lethn's Programming Questions Thread
Post by: Semicolon on August 08, 2013, 10:23:59 am
*currently reading through variables and basic types*

...

If you'd like videos instead (I know I do), I started out learning programming through xoax (http://xoax.net/cpp/crs/console/index.php). The videos are a bit sleep-inducing but still good.
Title: Re: Lethn's Programming Questions Thread
Post by: Grimshaw on August 08, 2013, 11:11:09 am

... As for the way I'm treating SFML, from my learning so far i've found it's not necessarily just C++ and it's not by itself either ( I also meant statements not functions, everybody forgets things >_> ). It's more like a mod or an addon to C++ ...


I mean no offense, but that is one of the silliest things a beginner can think about C++; SFML isn't a mod or an addon to c++, it doesn't change c++, but rather uses it. C++ isn't this or that implementation, it is a language, a set of rules for syntax and grammar and so on. Modding C++ involves writing further code in its compiler.. :p SFML is as much of an addon as the very code you write yourself :p

Sorry if this comes out in a bad way, I don't mean to offend, really ^^
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 08, 2013, 01:01:12 pm
lol! I'm not offended if it's true, it's if you're talking a load of rubbish and expect me to accept it that I'd get offended :P. I guess it must be because I'm a noob still but honestly, this is my view on it, without C++ code this thing doesn't work, you can't for instance, ditch the curly braces or say no to insertion operators and that's all C++ from what I've seen it's only C++ that works by itself.

If you just wrote some sf::Text stuff all by itself then you'd get error messages everywhere wouldn't you? You still need to even have the int main() to have it all working, that's what makes me think of it as an addon/mod. Yes, it's all coded entirely seperately, the person who made it had to have done it separately but in the end it looks to me like it's been written so that you need to have C++.

I'm aware as well from looking at the basic features though that it can be used in python/ruby etc. but in the end you still have to have the basic programming languages to make the thing work properly you can't just have pure SFML code and expect the program to work right?
Title: Re: Lethn's Programming Questions Thread
Post by: Ixrec on August 08, 2013, 02:40:42 pm
Yes, because SFML is a library, not a programming language.  It's just some code people wrote in C++ that you can use in your own C++ program.  It is in no way an extension of what the C++ language itself offers.

Maybe an analogy would help: saying SFML is a mod or extension C++ is like saying the King James Bible is a mod or extension of English.  Trying to read the Bible and learn English at the same time is just silly.  At best you'll come out of it with a very twisted understanding of both.  You should be starting off with a far simpler and more newbie-friendly book like See Spot Run (or in C++, a Hello World! program, reversing a string, implementing some basic sorting algorithms, etc, NOT a window-based program with user input and 3D graphics and whatnot using SFML).
Title: Re: Lethn's Programming Questions Thread
Post by: Grimshaw on August 08, 2013, 06:04:40 pm
Just to avoid confusion, C++ is indeed only the rules of the language, nothing else.

Even the basic functions like printf and the containers etc etc are a part of the STL or the libc or whatever other "built-in" library, every single piece of functionality is implementation specific I believe, while c++ is just the standard by which those implementators write their compilers/libraries by.

Hope its clear :D
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 13, 2013, 07:57:22 pm
Sorry, I took so long to post, been very busy, that does make a bit more sense now and thanks a lot for that post Semicolon I'll have a look I was wondering if there were any tutorials etc. out there that give good explanations so I'll see if these ones work for me. For some reason I find the way the internet lays out information a lot better even for reading than books.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on August 13, 2013, 08:16:59 pm
For some reason I find the way the internet lays out information a lot better even for reading than books.
The impression may mislead, omitting important information may look simpler. But it's not, it will make your life harder -- but you'll recognize that only when developing own projects and not while reading. I still haven't found a C++ tutorial that covers the language in-depth and in a modern way. You'll miss a lot of important details when looking only at internet tutorials. In addition, a lot of tutorials teach a C/C++ mix and ancient, bad code style (this even applies to many books). Especially now that C++11 is out, you should definitely forget the tutorials that were already outdated the last decade.

I have just looked quickly at the XoaX video tutorials, and they seem to totally confirm my expectations: C class prefixes and Hungarian Notation, useless destructors, useless variable initializations, non-local declarations and variable reuse, missing const-correctness, manual memory management (even for arrays), using namespace std at the beginning of each function, ... I'm sure there is more. You'll learn a lot of bad practices by following such tutorials, I really do not recommend them. The only way to learn C++ correctly is, again, by reading a good book.

Here's such a WTF snippet, I don't even know where to start. And this is just a simple initialization.
bool bCanMove(false);
bCanMove = mqGameBoard.CanMove(mcPlayerTurn);
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 13, 2013, 11:53:07 pm
Quote
I'm sure there is more.
I'll tell you more: he uses void main in some videos. ;D
And the comments just praise him extremely high for his easy, simple and quick tutorials.
Nexus, you are first class comedy supplier for me recently, these youtube tutorials you mention are always extremely funny.
On a more serious note: don't you wish everyone now just used clear, efficient, expertly written but 'old' practices like doom programming team does instead of learning from youtube? ::)
Because in the real world guys like him win over you or me, we tell them: read a book, read the code, read the reference, read the iso standard pdf and he says: I'll teach you how to do XYZ in 5 minutes video with pretty visuals and music. Who do you think they will follow? ;)
I'm personally quite happy, they are competition, the worse they do the better, it's their fault if they stay this way, I was that way too but I got better.

Here are two good resources for learning c++ online:
1. Bjarne Stroustrup's FAQs and glossary:
http://www.stroustrup.com/bs_faq.html
http://www.stroustrup.com/bs_faq2.html
http://www.stroustrup.com/C++11FAQ.html
http://www.stroustrup.com/glossary.html
These are pretty much prime resources since Stroustrup is original designer and creator of c++, sits in the committee(and claims to be happy with their decisions), the fact he is extremely skilled in C also helps these texts. Of course they are not to be read in one go or completely alone but the FAQs especially are well written, not boring or dry(the papers are, as expected from academic writings ;D) and can be read part by part from time to time, since they contain some interesting gotchas and explanations that can let you understand rationale and help you develop the mental model of why it's that way and why the other ways would fail.
2. Parashift FAQ:
http://www.parashift.com/c++-faq/
Very very in depth, long.

And of course reading some source code you can get your hands on is always good if it's right complexity compared to your experience so you learn but not get bored or confused by it. Also, nothing should be taken as granted when read from some source code, ever, because not all code follows good practices and much of it is legacy or outdated.

Quote
The only way to learn C++ correctly is, again, by reading a good book.
There actually is another way: being experience programmer in C, some OO language, optionally in assembly and some more langauges and then picking up c++ is quite easy. That's how half of Doom 3 team, including Carmack, learned c++, Carmack himself actually had Obj C and very strong C and assembler background. Doom 3 is a bit C-ish(it takes parts of renderer and probably some other things from id tech 3 which was in pure C, it's understandable to not start 100% from scratch when there are ready engines lying around, you have to excuse them for that) but it's well designed, efficient, modular, well abstracted and extremely short compared to something like Skyrim which is supposedly 30+ million lines.
But I can understand why you'd not mention this way. ;D
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on August 14, 2013, 10:13:45 am
I'm personally quite happy, they are competition, the worse they do the better, it's their fault if they stay this way, I was that way too but I got better.
With this attitude, I really have to wonder what you are doing in this forum ::)

There actually is another way: being experience programmer in C, some OO language, optionally in assembly and some more langauges and then picking up c++ is quite easy. That's how half of Doom 3 team, including Carmack, learned c++
No, picking up C++ like this is far from easy, as can be seen from the result -- I won't repeat the flaws again. That's why this approach is not a good idea, with respect to code. Remember, we're not talking about finished projects or great games here, only code.

I don't know what you're trying to achieve with your recent posts, that advertise ancient C++ code and obsolete techniques, just because a game was once written with them. Several years have passed meanwhile and C++ has greatly evolved. What's the point of ignoring progress and sticking to old principles? It's not as if writing a good game and clean code would inherently conflict, even if you want to believe that. Things like RAII massively simplify code, which in turn reduces development time and thus leaves more time to work on the actual game.
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 14, 2013, 11:26:43 am
Quote
With this attitude, I really have to wonder what you are doing in this forum ::)
Obviously I'm here to give bad advice and advertise doom codebase. ;D
Ok, actually:
There are comments telling them xoax is bad, using namespace std; void main is bad etc. but if instead something stupid like 'unsing namespace std; is more efficient' gets upvoted and they continue on watching these tutorials it's hardly my fault so why should I be concerned?
The forum on the other hand is very good resource because it's official for SFML(unlike coding made easy's SFML forum, which I'll make fun of and mock forever, since the official one is bigger, free and has all three authors on it so why do they go there..) , problem in here is equivalent to someone approaching me(or Stroustrup, because the SFML authors are here and can help too) about c++ and saying 'I read this <insert good book or tutorial here> but I don't understand this part, can you draw it out on paper for me?', which I did in the past and I'd do again, for free(maybe that was a mistake in that situation), because I support learning for real. What I don't support is quick-gain-little-effort approaches like watching these tutorials and plagiarism like 'I'll pay you if you code my c++ assignment' to which I said 'no'. :P

And of course the fact that I was that way(manual new/delete, cme tutorials) and got better, so they can/should too, the fact they are competition that is doing poorly is added benefit.
And I believe that most people are assholes and ungrateful and stupid by default and have to show something good(skill, willingness to learn, etc.) before I consider them worthwhile(but of course I don't say that upfront, that'd make them lock up and not able to show me their good side, which would be terrible loss). Being on this forum or reading from it is good enough thing to make me consider people who do it worthwhile(most of the time, excluding extreme cases like misusing SFML for something it wasn't meant to do or arguing about the fact that c++ is bad and SFML should be in C or something) and sacrifice a bit of my time to help here if I can.
Title: Re: Lethn's Programming Questions Thread
Post by: Grimshaw on August 14, 2013, 12:47:48 pm
What's with video tutorials these days.. What was wrong with the old way of learning? The way I learned to program was still weak compared to what it should be, in the early beginnings, but video tutorials seems like a new kind of low to me :/
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 14, 2013, 01:28:01 pm
Google conference keynote videos are great and on youtube, Linus' talk about git is great, interesting but not a tutorial but more of explanation of mental model behind git.

Everything seems to be some kind of low, people don't care about languages, learning, opinions like 'Linux sucks and is for poor stupid people who can't afford or pirate Windows' 'I don't give a shit about cross platform, only Windows matters' exist commonly etc. People are just bad in every respect and keep getting worse.

I say : don't worry, kick back and enjoy the laugh, this video is about 'unicode':
https://www.youtube.com/watch?v=R21fh-17um0&list=PLCCE82290D45D88E3&index=46
There are quite a lot of mistakes, barely anything is correct, comments are also very funny.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 14, 2013, 01:37:54 pm
What's with video tutorials these days.. What was wrong with the old way of learning? The way I learned to program was still weak compared to what it should be, in the early beginnings, but video tutorials seems like a new kind of low to me :/

Some video tutorials are bloody brilliant but I guess it can depend on what sort of thing you're trying to learn about and so on but there do seem to be unfortunately a lot of pretty crappy programming tutorials out there now I've gotten some knowledge :(. There are also those awful ones which are just crappy advertisements for paid tutorials so they'll leave stuff out etc. rather than just advertise honestly.
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 14, 2013, 01:47:18 pm
They might seem brilliant because they seem to be clear and explain well and the code works but it might be all crappy, not cross platform etc. the xoax unicode tutorial video is very very bad.  You should question anything you see and when in doubt you should trust Stroustrup's, Parashift's, Nexus' words and good book content. I really don't know what is in mind of guy who makes xoax tutorials, they are very harmful, unicode one especially because it's full of misinformation and windows specific stuff.
Title: Re: Lethn's Programming Questions Thread
Post by: Grimshaw on August 14, 2013, 02:22:21 pm
Those tutorials, as great as the teaching may be, it is not teaching what it should for a complete learning.. Programming languages are pretty easy to learn as they are only a few rules of syntax etc, but then you need a ton of practicing and reading about the little things to master it.

For every major language, the hardest thing is to enter the mindset of the people who created that language, so you can take the max advantage of the tool and what it was created for. And of course, in order for the tool to be really good at something, it is designed and meant to be used in a particular way. That's why knowing all the control structures and syntax won't help much if you don't know what you SHOULD be doing with them in the particular case of that language. This is why people underestimate how hard it is to learn C++ properly, the language is pretty unforgiving, it can and will give headaches if you aren't absolutely confident of what you're doing.. Video tutorials will skip most things because if they would cover everything they would be BORING and no one would watch them..

About the OS fanboys, I have to say I hate ALL of them... Anyone who says Apple/Microsoft/Linux is the universal truth and calls morons to everyone else doesn't deserve any respect.. All systems are good equally for most tasks and its up to each person to choose what feels best... Everyone should be writing portable code for more than a decade now and just forget about stupid OS wars..(Its easy, just pickup SFML, Qt or anything else if you don't know how to do it manually..)

EDIT: I was watching the unicode video.. man.. he is trying to sell windows specific multibyte encoding as UNICODE which is plain wrong.. this video should be banned all the way :( I don't even think 16bit unicode chars even match 1:1 with those wchar_t things..
 
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 14, 2013, 03:10:18 pm
He spreads Microsoft's misinformation(although there are comment saying that article is wrong), they say Unicode is 16 bit and has only 2^16 characters:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd183415%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.aspx
 
I'm guessing wchar_t have UCS-2 as described here:
http://www.unicode.org/faq/basic_q.html#14
which means that wchar_t is like UTF-16 limited to characters in BMP:
http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane
so technically it is fixed width but that is not unicode and is extremely Windows specific and xoax instructor said they stopped using void main() because tutorials are now compatible with all compilers so it shouldn't be Windows specific.

You have to admit this is quite funny. ;D
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 14, 2013, 03:27:01 pm
lol! Oh man the OS wars are ridiculous you have the same situation in games too as I'm sure you all know, I even discovered there are people arguing about OpenGL vs Directx.

Oh and by the way, I'm having a look at timestep so I can finally get some good interaction going without any lag and I'm having trouble understanding it, I have the SFML book explanation and I have the website the book gives but I'm having trouble understanding where it should all fit the code you make. I know about FPS etc. but because a lot of the stuff they show seems to be classes and things like that I think I need to do some more research on it.

The SFML book goes into plenty of detail into the mechanics of it but I need to have a look at more of the why is that placed there and so on.

p.s. will someone explain to me why the hell my thread is almost at 2000 views now? That's terrifying lmao :D

By the way, here's some code I'm doing with a simple stats bar as you can see, while it works, just like with my number incrementing the movement it's just way too jumpy, I need to learn how to fix the FPS issues properly so it's all nice and smooth. What's interesting for me is that it tends to get worse the higher the difference is between the number changes, it also seems to work mildly better when the window is a higher resolution.

#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    int healthstats = 1;


    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    sf::RectangleShape health ( sf::Vector2f ( healthstats, 5 ) );
    health.setFillColor ( sf::Color::Cyan );
    health.setPosition ( 20, 10 );

while (window.isOpen())
{
    if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::A ) )

    {
        health.setScale ( healthstats, 5 );
        healthstats = healthstats - 1;
    }

    else if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::D ) )
    {
        health.setScale ( healthstats, 5 );
        healthstats = healthstats + 1;
    }

sf::Event event;
while (window.pollEvent(event))
{

if (event.type == sf::Event::Closed)
window.close();
}
        window.clear();
        window.draw ( health );
        window.display();

    }
    return 0;
}
 

Edit: For the record, I do have the source code from the SFML book so I probably just need to take a closer look at it all to get it working properly in the context of my own programs, this is what I'm working with.

void Game::run()
{
        sf::Clock clock;
        sf::Time timeSinceLastUpdate = sf::Time::Zero;
        while (mWindow.isOpen())
        {
                sf::Time elapsedTime = clock.restart();
                timeSinceLastUpdate += elapsedTime;
                while (timeSinceLastUpdate > TimePerFrame)
                {
                        timeSinceLastUpdate -= TimePerFrame;

                        processEvents();
                        update(TimePerFrame);
                }

                updateStatistics(elapsedTime);
                render();
        }
}

It's probably time I obeyed the SFML book a bit more and got some seperate files and classes running so I know how it's all done.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 16, 2013, 02:10:10 pm
I asked about timestep etc. on another forum and I got what I thought was an extremely good explanation about it, I'll post it up here for people to have a look at.

Quote

Foxpup ( User on Bitcointalk )

"TimePerFrame" is a constant that you should set to whatever your game needs, eg if you need a constant framerate of 50 fps, you should set it to 20 (assuming the clock returns values in milliseconds; I think it does, but I'm not very familiar with SFML).

Then, with every iteration of the loop, it looks at how long it's been since the last time the game state was last updated, and if it was longer than 20 ms (or whatever you set for TimePerFrame), it runs the update() function (possibly multiple times, if your render framerate is slower than your game framerate, so it needs to update multiple times per frame).

The update() function is where you do your actual updating of the game state, eg incrementing the position of moving objects, applying health damage, whatever it is you need to happen in your game.

Finally, after all that, render() is where you put your actual rendering (screen drawing) code. A more advanced version of this code (which you should not attempt until you get the basics working) would have render() take timeSinceLastUpdate as an argument, and use it to do interpolation of moving objects (ie, don't draw them where they are, but where they will be timeSinceLastUpdate milliseconds from now; this allows for smoother animation, but since you're only drawing them in a different position instead of actually moving them, rounding errors will not accumulate).

One major problem with this code that you need to be aware of is that it will livelock (the technical term for what is referred to in the article as the "spiral of death") if TimePerFrame is less than the time it takes to run the update() function. Don't set TimePerFrame too low!

Title: Re: Lethn's Programming Questions Thread
Post by: FRex on August 16, 2013, 02:25:02 pm
You can also look pretty much anywhere on google and find that too:
http://gafferongames.com/game-physics/fix-your-timestep/
http://fabiensanglard.net/timer_and_framerate/

It's very well known method.
Even my Man uses that and might spiral into semi-deadlock(in theory, in practice it won't ever):
https://github.com/FRex/Man/blob/master/src/GameState.cpp#L134
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 16, 2013, 02:41:50 pm
The problem I had was those explanations are very good for explaining the how and why of everything but I just needed to know what all the little bits of code did :D
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 26, 2013, 06:21:37 am
I've run into a brick wall at the moment so I thought I'd post things up here again, my code is almost working the way I want it to but this damn time step is still an issue. I've got scope errors popping up which should be all means be easy to fix but these classes ( or at least I think they're classes ) don't seem to work like what I'm used to. I have the source code for the SFML game development book with me and I scoured it for the usual int commands to match up but there aren't any so I'm probably looking at this all completely wrong.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

   {

    sf::RenderWindow window(sf::VideoMode(800, 600), "");


    const sf::Time TimePerFrame = sf::seconds ( 1.f / 60.f );
    int healthstats = 1;


    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    sf::RectangleShape health ( sf::Vector2f ( healthstats, 5 ) );
    health.setFillColor ( sf::Color::Cyan );
    health.setPosition ( 20, 10 );

    sf::Clock clock;
    sf::Time TimeSinceLastUpdate = sf::Time::Zero;



while ( window.isOpen() )
{
    sf::Time ElapsedTime = clock.restart ();
    TimeSinceLastUpdate += ElapsedTime;
    while ( TimeSinceLastUpdate > TimePerFrame )
    {
        TimeSinceLastUpdate -= TimePerFrame;

        processEvents();
        update ( TimePerFrame );
    }

            updateStatistics ( ElapsedTime );
            render();
    }



    if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::A ) )

    {
        health.setScale ( healthstats, 5 );
        healthstats = healthstats - 1;
    }

    else if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::D ) )
    {
        health.setScale ( healthstats, 5 );
        healthstats = healthstats + 1;
    }

sf::Event event;
while (window.pollEvent(event))
{

if (event.type == sf::Event::Closed)
window.close();
}
        window.clear();
        window.draw ( health );
        window.display();

    }
    return 0;
}


 


Quote


|38|error: 'processEvents' was not declared in this scope|
|39|error: 'update' was not declared in this scope|
|42|error: 'updateStatistics' was not declared in this scope|
|43|error: 'render' was not declared in this scope|
||=== Build finished: 4 errors, 0 warnings (0 minutes, 0 seconds) ===|


Here's all the information guys, hope it helps and as usual thanks again in advance for any advice you give me :) I'm just at a brick wall with this at the moment but I managed to fix some basic things wrong with it myself thankfully so it looks like I'm learning.
Title: Re: Lethn's Programming Questions Thread
Post by: OniLinkPlus on August 26, 2013, 06:38:03 am
Those errors mean you haven't defined the functions "processEvents", "update", "updateStatistics", or "render". You need to define them before using them. If you've already defined them in another source (.cpp) file, include the header (.hpp) that correponds to that source file at the beginning of your source file that has the main function.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 26, 2013, 06:49:43 am
Yes, that's what I need to do, the problem is I don't see any example or explanation of where or how I'm supposed to set it all up? Is it a normal method like my int healthstats? Or is it something a bit more complicated using sf::Time etc? That's what I'm trying to find out, there doesn't seem to be any information in the book, I'll post the source code I'm working from too.

This is the SFML Game Development book code I'm working from, please note, I'm not putting together files at the moment, I'm just trying to get timestep working by itself so ignore the headers.


#include <Book/Game.hpp>
#include <Book/StringHelpers.hpp>


const float Game::PlayerSpeed = 100.f;
const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);

Game::Game()
: mWindow(sf::VideoMode(640, 480), "SFML Application", sf::Style::Close)
, mTexture()
, mPlayer()
, mFont()
, mStatisticsText()
, mStatisticsUpdateTime()
, mStatisticsNumFrames(0)
, mIsMovingUp(false)
, mIsMovingDown(false)
, mIsMovingRight(false)
, mIsMovingLeft(false)
{
        if (!mTexture.loadFromFile("Media/Textures/Eagle.png"))
        {
                // Handle loading error
        }

        mPlayer.setTexture(mTexture);
        mPlayer.setPosition(100.f, 100.f);
       
        mFont.loadFromFile("Media/Sansation.ttf");
        mStatisticsText.setFont(mFont);
        mStatisticsText.setPosition(5.f, 5.f);
        mStatisticsText.setCharacterSize(10);
}

void Game::run()
{
        sf::Clock clock;
        sf::Time timeSinceLastUpdate = sf::Time::Zero;
        while (mWindow.isOpen())
        {
                sf::Time elapsedTime = clock.restart();
                timeSinceLastUpdate += elapsedTime;
                while (timeSinceLastUpdate > TimePerFrame)
                {
                        timeSinceLastUpdate -= TimePerFrame;

                        processEvents();
                        update(TimePerFrame);
                }

                updateStatistics(elapsedTime);
                render();
        }
}

void Game::processEvents()
{
        sf::Event event;
        while (mWindow.pollEvent(event))
        {
                switch (event.type)
                {
                        case sf::Event::KeyPressed:
                                handlePlayerInput(event.key.code, true);
                                break;

                        case sf::Event::KeyReleased:
                                handlePlayerInput(event.key.code, false);
                                break;

                        case sf::Event::Closed:
                                mWindow.close();
                                break;
                }
        }
}

void Game::update(sf::Time elapsedTime)
{
        sf::Vector2f movement(0.f, 0.f);
        if (mIsMovingUp)
                movement.y -= PlayerSpeed;
        if (mIsMovingDown)
                movement.y += PlayerSpeed;
        if (mIsMovingLeft)
                movement.x -= PlayerSpeed;
        if (mIsMovingRight)
                movement.x += PlayerSpeed;
               
        mPlayer.move(movement * elapsedTime.asSeconds());
}

void Game::render()
{
        mWindow.clear();       
        mWindow.draw(mPlayer);
        mWindow.draw(mStatisticsText);
        mWindow.display();
}

void Game::updateStatistics(sf::Time elapsedTime)
{
        mStatisticsUpdateTime += elapsedTime;
        mStatisticsNumFrames += 1;

        if (mStatisticsUpdateTime >= sf::seconds(1.0f))
        {
                mStatisticsText.setString(
                        "Frames / Second = " + toString(mStatisticsNumFrames) + "\n" +
                        "Time / Update = " + toString(mStatisticsUpdateTime.asMicroseconds() / mStatisticsNumFrames) + "us");
                                                         
                mStatisticsUpdateTime -= sf::seconds(1.0f);
                mStatisticsNumFrames = 0;
        }
}

void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{      
        if (key == sf::Keyboard::W)
                mIsMovingUp = isPressed;
        else if (key == sf::Keyboard::S)
                mIsMovingDown = isPressed;
        else if (key == sf::Keyboard::A)
                mIsMovingLeft = isPressed;
        else if (key == sf::Keyboard::D)
                mIsMovingRight = isPressed;
}


 

I double checked the headers the code was linked to and there was nothing there that lead me to believe that I missed anything critical to get the code compiling.

Edit: OH LOL! Wait a minute, what's this? It looks like I missed a .hpp file hidden in the folders that's got all the declarations in it, I think this is the right thing to look at, let me know, I didn't think anything of it because it was named the same name but just a different file type.


#ifndef BOOK_GAME_HPP
#define BOOK_GAME_HPP

#include <SFML/Graphics.hpp>


class Game : private sf::NonCopyable
{
        public:
                                                                Game();
                void                                    run();
               

        private:
                void                                    processEvents();
                void                                    update(sf::Time elapsedTime);
                void                                    render();

                void                                    updateStatistics(sf::Time elapsedTime);
                void                                    handlePlayerInput(sf::Keyboard::Key key, bool isPressed);
               

        private:
                static const float              PlayerSpeed;
                static const sf::Time   TimePerFrame;

                sf::RenderWindow                mWindow;
                sf::Texture                             mTexture;
                sf::Sprite                              mPlayer;
                sf::Font                                mFont;
                sf::Text                                mStatisticsText;
                sf::Time                                mStatisticsUpdateTime;

                std::size_t                             mStatisticsNumFrames;
                bool                                    mIsMovingUp;
                bool                                    mIsMovingDown;
                bool                                    mIsMovingRight;
                bool                                    mIsMovingLeft;
};

#endif // BOOK_GAME_HPP


 

I should be able to fix it now with this I think.

Edit: Now I'm not so sure looking at it more carefully >_<
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on August 27, 2013, 05:00:16 am
AGAIN, LENTH, class file are a BASIC c++ knowledge that uses a HEADER file (*.h, or *.hpp) and (most of the time) a corresponding *.cpp of the same name.  We've all told you to get a good base knowledge of general c++ practices before trying to delve into SFML stuff.  This goes double for any code from the SFML book since it relies heavily on separate class files. 

HELL, even when you posted the 'Game.cpp' file from the SFML book it CLEARLY shows how its code is broken into the 'update', 'render', 'processEvents', and 'updateStatistics' method.  You literally posted your own solution to your problem and didn't realize it.  This says you have a long ways to go before you even understand simple OOP (object oriented programming) principles.  PLEASE PLEASE PLEASE take a step back from SFML and just try to program up examples and programs in straight c++ that just make use of the console.  If you can do that you will have a much better understanding of SFML later on. 

I already posted like a dozen example programs you can try to write in one of my earlier posts in this thread, please if you truly want to learn to program try and do those examples before moving on to SFML related stuff.  You have to learn to crawl before you can drive a car, which is essentially what you're trying to do.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on August 27, 2013, 06:59:35 am
Hatchet thanks LOL sorry, I just realised what had happened, I was so tired I didn't notice what was right in front of me ( I'd been up for several hours without sleep ) and now I can see it easily because I've got plenty of sleep and I'm waking up with a coffee now.

I feel like an idiot :P I do understand OOP but the problem was I was too tired to notice what the hell was going on! Remember people, don't program when suffering from lack of sleep! >_< I had already been making a lot of Jewellery settings beforehand, I feel stupid for doing that.

angry swearing: SADSAJD KSKA JSLDKKS KJDL KALSA.

Note: This will be easy to fix now, I swear I was so wasted I didn't notice a thing  ;D
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 07, 2013, 12:11:31 am

#include <iostream>
#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window ( sf::VideoMode(800, 600), "" );

    const sf::Time TimePerFrame = sf::seconds ( 1.f / 60.f );

sf::Texture playerimage;
if ( !playerimage.loadFromFile ( "player.png" ) )
{

}
sf::Sprite playersprite ( playerimage );
playersprite.setPosition ( 300, 200 );


sf::Clock clock;
sf::Time TimeSinceLastUpdate = sf::Time::Zero;

    while (window.isOpen())


    {
        sf::Time ElapsedTime = clock.restart();
        TimeSinceLastUpdate += ElapsedTime;
        while ( TimeSinceLastUpdate > TimePerFrame )

        {
            TimeSinceLastUpdate -= TimePerFrame;
        }

        sf::Event event;
        while (window.pollEvent(event))

                if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::A ) )
    {
        playersprite.move ( -5.0f, 0.0f );
    }

    else if ( sf::Keyboard::isKeyPressed ( sf::Keyboard::D ) )

    {
        playersprite.move ( 5.0f, 0.0f );
    }
        {

            if (event.type == sf::Event::Closed)
                window.close();
        }
        window.clear();
        window.draw ( playersprite );
        window.display();
    }

    return 0;
}

 

I just need to get the independent movement going as described by the book and in the source code and it should work great, there's also this annoying thing with update and processEvents which as you can see I've removed for now but I'll keep tweaking everything.

You know what helped me a lot guys? The highlighting in codeblocks! I had noticed it before but I didn't really understand what it was about but then I found when you drag-highlighted classes etc. it highlighted where they were all linked to each other on the entire page :D anyway, should be able to make some more interesting stuff once I get the independent movement right.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 12, 2013, 12:09:28 pm
So guys, I'm having a proper read through of the C++ primer book again and get everything in my head. Do any of you know how I can read through it without losing the will to live? If you don't have an suggestions I guess I'm just going to have to persevere >_< :D.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on September 12, 2013, 12:27:23 pm
I actually found it interesting to learn more about the programming language and its capabilities. But if you consider C++ a necessary evil instead of a powerful tool, it will of course be difficult to remain motivated... And you should consider another, simpler language. Don't learn C++ if you don't like it.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 12, 2013, 12:39:35 pm
I like C++, it's looks like a well thought out language and all the explanations make sense, it's just the book that's the problem and it's something that schools often do where they manage to make something that should be really interesting extremely boring. Just through reading the section about basic types and variables I've figured out how to use decrementing/incrementing properly for games.

You know Bitcoin was programmed in C++? :D Like I said, really interesting language but the book manages to make it boring even though it's giving me all the information I need.
Title: Re: Lethn's Programming Questions Thread
Post by: Josh_M on September 12, 2013, 02:28:39 pm
I don't really see how it can be so boring o_0. I've been through a 1400 page C++ book thoroughly in like 2 weeks before, and that was without access to even a basic compiler, so all my programming practice was on paper with painstaking (and terrible) error checking. It wasn't the most interesting thing in itself, but if you make your own exercises to do that involve what you're currently learning, it helps a bit too. But primarily, I think you just need a real interest in learning the language, nothing else is really going to cut it.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 12, 2013, 03:14:30 pm
I wonder if I'm explaining it right, but I can give an example, it's a bit like learning about gemstones and where they live. In geography I had to learn about sedimentary and igneous rocks etc. and the text books didn't mention that I could get shiny gemstones out of them which could end up being worth thousands of pounds and that this kind of knowledge was necessary if you wanted to do any sort of mining and exploration for gold/silver etc. so in the end you end up thinking that there's no real use for that kind of knowledge in real life.

The book has the same problem where it doesn't really talk about applications in the real world and just uses an excruciatingly boring example of a book store, as if the guy who wrote the book has only ever done that with such a powerful programming language in his life. Like I said, the informations great and I like the language but ugh :P the applications.
Title: Re: Lethn's Programming Questions Thread
Post by: model76 on September 13, 2013, 03:00:53 am
Well, not all of us learn equally well from a book alone, so why not try gameinstitute (http://www.gameinstitute.com/)?
That way you will have an instructor and tests to see if you understood the material well enough.

They have 2 courses on C++, and all the examples are game related in some way.
You can safely quit the 2nd course when it gets to the Microsoft specific stuff. You won't need that for SFML.

Worked well enough for me 6 years ago, so perhaps it will work for you now.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 13, 2013, 11:05:40 am
It looks interesting but the very fact that he said 'industry professionals' had me nearly running for the hills and I say this after having recently patched Rome 2 Total War which froze and crashed more than it had in the unpatched version for me. I'd have to get more feedback from real people but because of past experiences I think I'm done with crappy over-generalised courses run by people who know absolutely nothing about games design. Now if they were to quote someone who had vetted their work and could actually give me source code to look at or I actually knew by reputation ( like mojang or 2D Boy ) then I'd be interested.

I don't know if I mentioned this before but I actually went on a games design course once that was supposed to be 1/2 years ( long time ago :D can't remember well, I just remember how bad it was ) and the only reason me or anyone else there learned about actual games design was because we ignored what they were trying to teach us which was just stupid written assignments on the theory of it all which looked like it had been written up by school teachers during lunch. It may well be because they were a government run school they and were more concerned with looking good and getting good attendance records/passing their students than actually teaching anything.

This is why I'm perfectly happy struggling with the book and the code because at least I'm actually learning something about game development! :P

Edit: You just gave me an idea though model76 but I hang around on Bitcointalk and there are a bunch of programmers there who specialise in all sorts of languages. Maybe I could see if one of them would be interested in teaching me because I've found I do learn a lot better 1 on 1 and I've seen them openly offering to do it for Bitcoins. Some of them as you know even helped explain some of the SFML programming to me.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 22, 2013, 09:24:41 pm
So I'm experimenting more now with the code I've learned and making things, I've had no trouble putting up text as you can see in this code, changing colour, no problem, basic positioning etc. is fine.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }


    sf::Text FontOne;
    FontOne.setFont ( arial );
    FontOne.setCharacterSize ( 12 );
    FontOne.setColor ( sf::Color::Blue );
    FontOne.setPosition ( 350, 120 );

    FontOne.setString ( "This is line one!" );


    sf::Text FontTwo;
    FontTwo.setFont ( arial );
    FontTwo.setCharacterSize ( 12 );
    FontTwo.setColor ( sf::Color::Green );
    FontTwo.setPosition ( 350, 240 );

    FontTwo.setString ( "This is line two" );


        sf::Text FontThree;
    FontThree.setFont ( arial );
    FontThree.setCharacterSize ( 12 );
    FontThree.setColor ( sf::Color::Red );
    FontThree.setPosition ( 350, 360 );

    FontThree.setString ( "This is line three" );

while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{

if (event.type == sf::Event::Closed)
window.close();
}

        window.clear();
        window.draw ( FontOne );
        window.draw ( FontTwo );
        window.draw ( FontThree );
        window.display();

    }
    return 0;
}

 

I want to experiment more and see what I can do with the basic stuff I've learned though, does anyone have example code out there they can post? I'd like to see stuff like scrolling text ( Like you get in Zelda etc. with dialogue ) and things like that.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 23, 2013, 12:35:11 pm
Oh yeah, I figured out why I was so bored, it was because I'd spent too much time learning and not enough time actually coding and making stuff, so I guess I just need to balance it out more, look! Text input! :D need to do m0ar experimenting and looking at example code.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

    std::ostringstream txtinput;





    sf::Text writtentext;
    writtentext.setFont ( arial );
    writtentext.setCharacterSize ( 12 );
    writtentext.setColor ( sf::Color::White );
    writtentext.setPosition ( 20, 20 );


while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))

    if ( event.type == sf::Event::TextEntered )

{
    if ( event.text.unicode < 128 )


        txtinput << ( char  ) event.text.unicode;
        gaingold.setString ( txtinput.str() );


}
{

if (event.type == sf::Event::Closed)
window.close();
}

        window.clear();
        window.draw ( writtentext );
        window.display();
        window.setFramerateLimit ( 30 );

    }
    return 0;
}

 

Edit: Oops cocked up my naming, need to be more careful, the code still works fine though.

Edit 2: Better now.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 28, 2013, 12:09:14 pm
So I'm having a look at how buttons are made just out of curiosity while I keep doing experiments with them and I noticed that one thing is consistent with them is sf::Rect located here http://www.sfml-dev.org/documentation/2.1/classsf_1_1Rect.php, I was digging through old posts about this subject and I saw people like Nexus mentioning this documentation being what you need to look up :D.

I've also been looking at various games very closely which have a lot of buttons in them and I've noticed that even though you have buttons which clearly look circular or have an image that doesn't match the shape of a rectangle the way the programs read the mouse cursor going over it is that of a rectangle because if you go near the corners the hover colour just flips straight over to the other button rather than as a circle.

This is just a detail thing but I was wondering if there was an sf::circle somewhere I've missed? Or would it be the case you'd have to program your own thing somehow.
Title: Re: Lethn's Programming Questions Thread
Post by: eXpl0it3r on September 28, 2013, 02:52:57 pm
This is just a detail thing but I was wondering if there was an sf::circle somewhere I've missed? Or would it be the case you'd have to program your own thing somehow.
No there's not, since SFML doesn't use it and overall it would have only limited usage, where as sf::Rect has a lot of different usage.
Circular collision detection is quite easy though. All you need to do is measure the distance between button origin and mouse position and compare it against the button radius. And circle/circle collision is equally easy: Take the distance between two circle origins and check whether the distance is smaller than the sum of both radius.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 28, 2013, 03:07:27 pm
Thanks eXpl0it3r, that's interesting, one of the things I like about buttons is they can be used to represent and do almost anything in the game whereas with keys you're a bit more limited so I figure is a good idea to learn about it as soon as possible.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 29, 2013, 12:58:41 pm
I just successfully implemented some simple mouse movement detection thanks to an old post I found here http://www.gamedev.net/topic/619329-help-with-making-sfml-buttons/ I have some questions about the code provided though

The text changes to cyan when you put your mouse over it, the next step for me will be to make something happen when I click on it, like switching over to a different line of text or putting up a picture but that's for later.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }


    sf::Text FontOne;
    FontOne.setFont ( arial );
    FontOne.setCharacterSize ( 12 );
    FontOne.setColor ( sf::Color::Blue );
    FontOne.setPosition ( 350, 120 );

    FontOne.setString ( "This is line one!" );


    sf::Text FontTwo;
    FontTwo.setFont ( arial );
    FontTwo.setCharacterSize ( 12 );
    FontTwo.setColor ( sf::Color::Green );
    FontTwo.setPosition ( 350, 240 );

    FontTwo.setString ( "This is line two!" );


        sf::Text FontThree;
    FontThree.setFont ( arial );
    FontThree.setCharacterSize ( 12 );
    FontThree.setColor ( sf::Color::Red );
    FontThree.setPosition ( 350, 360 );

    FontThree.setString ( "This is line three!" );

    sf::FloatRect FirstButton ( 350, 120, 1, 1 );
    sf::FloatRect SecondButton ( 350, 240, 1, 1 );
    sf::FloatRect ThirdButton ( 350, 360, 1, 1 );

    FirstButton = FontOne.getGlobalBounds();
    SecondButton = FontTwo.getGlobalBounds();
    ThirdButton = FontThree.getGlobalBounds();

while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{

    if ( FirstButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true )

    {
        FontOne.setColor ( sf::Color::Cyan );
    }

    else

    {
        FontOne.setColor ( sf::Color::Blue );
    }

    if ( SecondButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true )

    {
        FontTwo.setColor ( sf::Color::Cyan );
    }

    else

    {
        FontTwo.setColor ( sf::Color::Green );
    }

    if ( ThirdButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true )

    {
        FontThree.setColor ( sf::Color::Cyan );
    }

    else

    {
        FontThree.setColor ( sf::Color::Red );
    }


if (event.type == sf::Event::Closed)
window.close();
}

        window.clear();
        window.draw ( FontOne );
        window.draw ( FontTwo );
        window.draw ( FontThree );
        window.display();

    }
    return 0;
}




 

What I wanted to know is that I found my code worked fine after I deleted:


else if(Event.Type == Event.MouseMoveEvent)

 

Is this because the code is old and it's something to do with an earlier version of SFML? I don't see any reason for it being there, I'd appreciate an explanation on that one because while I did find the problem I'm still a bit baffled as to what that line is supposed to do compared to the other stuff even though I understood the individual bits. Is it actually necessary to be there for a particular reason? Have I just made it more difficult for me to do something else later on if I delete it?

Secondly I wanted to know if it was possible to make the FloatRect visible so having some kind of block representing it so you knew that it went in correctly because at the moment when it comes to the way I'm doing it now it feels like I'm just guessing where a specific FloatRect is rather than actually knowing how wide it is etc. which will become a problem if I'm making a more complicated UI which I almost certainly will be.
Title: Re: Lethn's Programming Questions Thread
Post by: FRex on September 29, 2013, 03:42:29 pm
http://www.sfml-dev.org/documentation/2.1/classsf_1_1RectangleShape.php
http://www.sfml-dev.org/documentation/2.1/classsf_1_1VertexArray.php
Title: Re: Lethn's Programming Questions Thread
Post by: Tobberoth on September 30, 2013, 08:25:39 am
FRex is being a bit short, but he has a good point: Some of your questions you can answer yourself very easily by simply reading the resources available to you. While it might feel comforting to ask the forum, you'll learn far more and progress faster if you try to rely on the reference etc as much as possible.

FloatRect is drawable and transformable. This pretty much tells you straight up that you can go rect.setTexture(someTexture), then window.draw(rect) and you'll see it just fine. Experimentation like this is great to learn more about SFML.

As for the MouseMoveEvent, I can't tell you why it messed up your code or anything like that... but I can say that if you don't understand why you would need it, I'd say it's fine to delete it. The code is there to help you, if you don't see its use, remove it and you'll eventually learn what it's needed for when you run into a problem where you need it. It's far too little code to put you in a position where you'll get stuck and not realize you need it. Events are only interesting if you specifically care about the event at hand anyway.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on September 30, 2013, 08:52:12 am
lol Thanks guys, I had a look at the FloatRect documentation which helped me get through this problem so I'll read through the other stuff now as well, the book I was recommended is helping me understand the documentation a lot better :D. I just need to keep the reading and coding balanced now because I found that experimenting with the knowledge I had also helped me understand it better anyway, now I actually need to have a serious think about what games I want to get making O_O.
Title: AW: Re: Lethn's Programming Questions Thread
Post by: eXpl0it3r on September 30, 2013, 10:41:32 am
FloatRect is drawable and transformable. This pretty much tells you straight up that you can go rect.setTexture(someTexture), then window.draw(rect) and you'll see it just fine. Experimentation like this is great to learn more about SFML.
Nope, sf::FloatRect is a typedef for sf::RECT<float> which is neither an sf::Drawable nor an sf::Transformable.
I guess what he meant to say was sf::RectangleShape has all those properties. :)
Title: Re: AW: Re: Lethn's Programming Questions Thread
Post by: Tobberoth on September 30, 2013, 11:08:08 am
FloatRect is drawable and transformable. This pretty much tells you straight up that you can go rect.setTexture(someTexture), then window.draw(rect) and you'll see it just fine. Experimentation like this is great to learn more about SFML.
Nope, sf::FloatRect is a typedef for sf::RECT<float> which is neither an sf::Drawable nor an sf::Transformable.
I guess what he meant to say was sf::RectangleShape has all those properties. :)
Very true, I need to follow my own advice and spend more time reading the reference ^^
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 02, 2013, 03:00:05 pm
Does anyone have some documentation they could point me towards that shows you how to hide and show sprites? I'm experimenting a lot more now but straight away I've run into a problem because I need to work with different sprites going on top of each other, I suppose I could hide the sprites off screen and use setPosition but that just seems like daft workaround really.

The closest I've been able to find is for cursors https://github.com/SFML/SFML/wiki/Tutorial:-Change-Cursor but I haven't found any sprite equivalent of setVisible. It will probably be one of those things that is really obvious if someone just points it out to me :P but in the mean time I'll keep searching.
Title: Re: Lethn's Programming Questions Thread
Post by: zsbzsb on October 02, 2013, 03:02:34 pm
Umm, how about simply not drawing the sprite?
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 02, 2013, 04:40:32 pm
It's got to be conditional, based on whether or not the mouse goes over it and stuff like that.
Title: Re: Lethn's Programming Questions Thread
Post by: Laurent on October 02, 2013, 04:47:57 pm
bool sprite_must_be_drawn;

while (window.isOpen())
{
    ...

    sprite_must_be_drawn = mouse over it and stuff like that;

    if (sprite_must_be_drawn)
        window.draw(sprite);

    ...
}
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 02, 2013, 05:29:27 pm
Oh that's perfect! Thanks! Will need to experiment with it and see what happens.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 09, 2013, 02:18:50 pm

#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

sf::Texture SelectedButton;
if (!SelectedButton.loadFromFile("Button Selected.png"))
{

}

sf::Sprite SpriteSelectedButton ( SelectedButton );
SpriteSelectedButton.setPosition ( 350, 120 );


sf::Texture UnSelectedButton;
if (!UnSelectedButton.loadFromFile("Button.png"))
{

}

sf::Sprite SpriteUnselectedButton ( UnSelectedButton );
SpriteUnselectedButton.setPosition ( 350, 120 );

    sf::FloatRect FirstButton ( 350, 120, 5, 5 );

    FirstButton = SpriteSelectedButton.getGlobalBounds();


bool DrawTheSprites;

while (window.isOpen())
{

sf::Event event;
while (window.pollEvent(event))
{

{

DrawTheSprites = ( FirstButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true );

    if ( DrawTheSprites )
        window.draw ( SpriteSelectedButton );


    else

    {
        window.draw ( SpriteUnselectedButton );
    }

}


if (event.type == sf::Event::Closed)
window.close();
}

        window.clear();
        window.display();

    }
    return 0;
}

 

Well this is interesting, I think I've got the code sorted now but nothing comes up when I move my mouse over to where the button should be. If I put the window.draw where you normally would put it the sprite comes up but it's not conditional and just sticks there. Going to mess around further with this and see if I can fix it by myself but if it's something pretty obvious comments would be appreciated as usual :D.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on October 09, 2013, 02:26:44 pm
Could you please indent your code next time?

And please read the tutorial about event handling carefully. Seriously, if you never invest time into reading theory, you don't have to wonder nothing ever works ::)
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 09, 2013, 02:34:14 pm
lol! Sorry, it is a mess, I was editing a lot, I'll check it out thanks.

Edit: Just realised what was wrong, going to fix it now.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 09, 2013, 07:25:28 pm
F*CK YES! IT'S MESSY BUT IT WORKS! :P Apologies for the unindented code again but I was mainly going for function, I didn't realise that's what the window commands were for, I thought you kept the events separate.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

sf::Texture SelectedButton;
if (!SelectedButton.loadFromFile("Button Selected.png"))
{

}

sf::Sprite SpriteSelectedButton ( SelectedButton );
SpriteSelectedButton.setPosition ( 350, 120 );


sf::Texture UnSelectedButton;
if (!UnSelectedButton.loadFromFile("Button.png"))
{

}

sf::Sprite SpriteUnselectedButton ( UnSelectedButton );
SpriteUnselectedButton.setPosition ( 350, 120 );

    sf::FloatRect FirstButton ( 350, 120, 5, 5 );

    FirstButton = SpriteSelectedButton.getGlobalBounds();


bool DrawTheSprites;

while (window.isOpen())
{

{
    sf::Event event;


while (window.pollEvent(event))

DrawTheSprites = ( FirstButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true );


if (event.type == sf::Event::Closed)
window.close();
}


        window.clear();

          if ( DrawTheSprites )
        window.draw ( SpriteSelectedButton );


    else

    {
        window.draw ( SpriteUnselectedButton );
    }


        window.display();

    }
    return 0;
}


 


When in doubt, rage code.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on October 09, 2013, 08:39:26 pm
I don't know why it works, but your way of handling events is still wrong. It's only a matter of time (or bad luck) until it breaks.

By the way, if meaningful indentation is too much of a challenge, there are tools like astyle :P
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 09, 2013, 09:21:22 pm
I'm still not 100% sure what you mean by that though, could you explain it? I was looking at the documentation etc. and this is how I figured it out. When I did it Laurent's way I either found that it either threw up the blank screen or complained about event not being declared etc. it clearly must be right if it works but I still haven't found out how to do it his way.

There don't seem to be any weird glitches or anything like that going on right now so now I'm looking at it after it's working I'm a bit baffled too.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on October 09, 2013, 09:25:38 pm
Just check how an event loop looks here (http://www.sfml-dev.org/tutorials/2.1/window-events.php) and compare it with your code.

And read the text!
Quote
Before dealing with events, it is important to understand what the sf::Event type is, and how to correctly use it. sf::Event is a union, which means that only one of its member is valid at a time (remember your C++ lesson: all the members of a union share the same memory space). The valid member is the one that matches the event type, for example event.key for a KeyPressed event. Trying to read any other member will result in an undefined behaviour (most likely: random or invalid values). So never try to use an event member that doesn't match its type.

Now look at your code and recognize that you access event members before testing for the event type.

There is even a highlighted box which repeats and emphasizes the problem, Laurent wrote that exactly for people like you.
Quote
Read the above paragraph once again and make sure that it's printed in your head, the sf::Event union causes too many problems to inadvertent programmers.  

But please, please read those things. Laurent put a huge effort in making the tutorials, he also mentioned a lot of pitfalls in the hope that they would prevent people from making mistakes. If you read tutorials, documentations and C++ literature carefully, you will stop wasting the time of yourself and other people.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 09, 2013, 09:30:45 pm
Ahh, I think I understand that a bit now, so it's to do with this little bit here:


    // check the type of the event...
    switch (event.type)
    {

 

What I've done to make it work is ended up bypassing the whole event check entirely and dumped the code in with the drawing functions, so it works for the simple stuff but if I try to do anything more complicated it will break. Looks like another case of not checking the code carefully enough for missing bits and where it's all positioned >_< I tend to make those mistakes most even when I understand what I'm doing.

I'll see if I can't get the code working properly now I have an idea of what's going on.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on October 09, 2013, 09:33:51 pm
I think I understand that a bit now
Don't think you understand it a bit, but be sure you understand it completely!

What I've done to make it work is ended up bypassing the whole event check entirely and dumped the code in with the drawing functions, so it works for the simple stuff but if I try to do anything more complicated it will break.
Your code is already now broken. Please read my last post again, I edited it to clarify the problem.
Title: Re: Lethn's Programming Questions Thread
Post by: Nexus on October 09, 2013, 09:41:15 pm
Looks like another case of not checking the code carefully enough for missing bits and where it's all positioned >_< I tend to make those mistakes most even when I understand what I'm doing.
After loads of pages, I honestly doubt you understand what you're doing. And the problem is not tiny bits of code which you overlook, but rather the underlying knowledge which you are missing, or only know at the surface.

You want to achieve things with too fast pace, but you must learn that they inevitably take time. Trying to bypass theory or taking abbreviations makes everything worse, which can be seen very clearly in this thread.

Anyway, it's not as if not several people had said that months ago. It's really time that you actually consider our advice and not just speak of it.
Title: Re: Lethn's Programming Questions Thread
Post by: Mosseman on October 10, 2013, 03:17:13 am
F*CK YES! IT'S MESSY BUT IT WORKS! :P Apologies for the unindented code again but I was mainly going for function, I didn't realise that's what the window commands were for, I thought you kept the events separate.


#include <iostream>
#include <SFML/Graphics.hpp>
#include <sstream>

int main()
{

    sf::RenderWindow window(sf::VideoMode(800, 600), "");

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { }

sf::Texture SelectedButton;
if (!SelectedButton.loadFromFile("Button Selected.png"))
{

}

sf::Sprite SpriteSelectedButton ( SelectedButton );
SpriteSelectedButton.setPosition ( 350, 120 );


sf::Texture UnSelectedButton;
if (!UnSelectedButton.loadFromFile("Button.png"))
{

}

sf::Sprite SpriteUnselectedButton ( UnSelectedButton );
SpriteUnselectedButton.setPosition ( 350, 120 );

    sf::FloatRect FirstButton ( 350, 120, 5, 5 );

    FirstButton = SpriteSelectedButton.getGlobalBounds();


bool DrawTheSprites;

while (window.isOpen())
{

{
    sf::Event event;


while (window.pollEvent(event))

DrawTheSprites = ( FirstButton.contains ( event.mouseMove.x, event.mouseMove.y ) == true );


if (event.type == sf::Event::Closed)
window.close();
}


        window.clear();

          if ( DrawTheSprites )
        window.draw ( SpriteSelectedButton );


    else

    {
        window.draw ( SpriteUnselectedButton );
    }


        window.display();

    }
    return 0;
}


 


When in doubt, rage code.
Here's your program, rewritten so it doesn't break anything.  I'm learning how to write GUI applications with SFML myself and I thought this would be a fun little excercise for myself.

I'm no master programmer, but I'm inclined to agree with Laurent, Hatchet and Nexus.  STOP trying to learn how to write a GUI application when your understanding of C++ is so shaky.  If you're having trouble with physical books, I'd recommend http://www.learncpp.com/ (http://www.learncpp.com/) as it's easy to follow, does a great job explaining not only the basic language, but why the things you do learn are so important.  I know more experienced programmers don't like online tutorials, but that site is fantastic for helping people learn the basics of C++, not to mention a few good tips for software design in general.
//#include <iostream>           You don't need this module
#include <SFML/Graphics.hpp>
//#include <sstream>            or this one

// code has been properly indented
// ALWAYS make your code easy to read!
int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "For Lethn");

    /* You're not writing any text to screen right now, so this bit is pointless
    When modifying code, be sure to expunge all the obsolete stuff.  this is why comments
    such as these and readable code are so important

    sf::Font arial;
    if ( !arial.loadFromFile ( "arial.ttf" ) )
    { } */


    sf::Texture SelectedButton;
    // OLD CODE: if (!SelectedButton.loadFromFile("Button Selected.png")){} ...why?
    // I noticed you originally introduced this error back in June, despite months of on/off revisions, it's still here

    if (!SelectedButton.loadFromFile("ButtonSelected.png"))
        return EXIT_FAILURE;

    sf::Texture UnSelectedButton;
    if (!UnSelectedButton.loadFromFile("ButtonUnselected.png"))
        return EXIT_FAILURE;            // added return statement

    sf::Sprite buttonSprite;
    buttonSprite.setPosition(350, 120);

    sf::Rect<int> buttonRect(350,120,80,80); // I've cheated here and simply set the rect position & size
                                             // manually the same as our sprite.  it's late, brain no function sleep without

    // your while loop had two opening braces, though i'm not sure what caused that to happen.
    // Again, the more readable your code, the less likely you're to make this mistakes
    while (window.isOpen())
    {
        sf::Event event;

        while (window.pollEvent(event))
        {       // found the missing brace!
            switch(event.type)
            {
            case(sf::Event::MouseMoved):
                if(buttonRect.contains(event.mouseMove.x, event.mouseMove.y))
                    buttonSprite.setTexture(SelectedButton);            // use this texture when mouse is over the button
                else
                    buttonSprite.setTexture(UnSelectedButton);          // use this one when it's not
                break;

            case(sf::Event::Closed):
                window.close();
                break;

            default:
                break;
            }
        }

        window.clear();

        window.draw(buttonSprite);  // buttonSprite automatically uses the correct texture

        window.display();
    }
    return EXIT_SUCCESS;
}
 
Sorry about the dirty shortcut when defining buttonRect.
Title: Re: Lethn's Programming Questions Thread
Post by: The Hatchet on October 10, 2013, 03:17:51 am
Indeed, again you really should just sit down and develop some console versions of these programs:

1.)  Take input from the keyboard, only allow numbers, and then calculate whether that number is prime or not, return true or false, if true return the primes root, if false give a close estimate.
2.)  Simple text file I/O
3.)  Strings, learn to manipulate strings with user input and input from a text file.  Print strings back to the console and print back to another text file.
4.)  A program that takes a text file of random numbers and gives the user an option to pick one of X number of 'sorts' to sort the list.  Sorts could be quicksort, bubble sort, heap sort, any other kind of sort you want.
5.) a simple console based Tic-Tac-Toe game
6.) console based Checkers game
7.)  a program that makes use of pointers such as your own Linked List

By doing any of those first you'll start to gain a greater knowledge of what you're trying to play with now in SFML and all these tiny little graphical things you're trying to figure out will seem very simple.

If you were trying to build a bike you need to figure out how to build the gear/sprocket/chain and wheels first, instead you are focusing on what sound your horn is making.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 10, 2013, 11:13:33 am
Thanks, I'll bookmark that site and have a look ahh, hang on this looks a lot easier to read than that book because it's laid out properly on a webpage rather than just scanned to a .pdf so I might have an easier time with that and I can use the book for reference to cross-check everything so I know the site hasn't made mistakes.

I know what you guys have been saying with the console thing, I've done small bits with the console but god I hate it >_< it must be because I do art or something but I hate the idea of dealing with bland text which is why I'd rather struggle making multi-coloured text and interactive buttons that glow when you hover over them :P.

The console reminds me too bloody much of DOS >_< and DOS was something I always found irritating to use, I'll also be sure to use that code you posted Hatchet as reference and a starting point for everything else. What I don't understand is there seem to be conflicting bits in your code with the material I've been reading from, the only place where events are used in the way you used them are in the events tutorial but in the main documentation Laurent doesn't seem to use them. The same goes for that other piece of code I found for doing text based button work.
Title: Re: Lethn's Programming Questions Thread
Post by: Mosseman on October 10, 2013, 11:58:32 am
I know what you guys have been saying with the console thing, I've done small bits with the console but god I hate it
You seem to be a lot like me: A novice programmer with dreams of creating his own computer games.  I know writing programs for a command line interface seems dull compared to making games but you need to learn to walk before you run.

By insisting on writing GUI applications with the SFML library you're wrestling with several beasts at once.  Each time you try to write something and it goes wrong, you've got no idea if the problem is caused by your use of the language, if the program is structured improperly or if you're not using SFML properly.

Go through a tutorial or book, piece by piece and attempt to write programs that incorporate the things you've just learned, many tutorials will actually give you basic programs for you to write such as basic sorting algorithms or finding the nth prime.

Every time you make a modification to your program, I've noticed you're coming to these forums for help and you're leaning heavily on others to write code for you.  If you learn the C++ language, you'll not only have a much easier time writing your own software, but you'll be able to use SFML's documentation (http://www.sfml-dev.org/resources.php).  Asking for help isn't a problem, it's why these forums exist, but insisting on writing software so far outside your skill range means you're not learning anything.  The things people have shown you so far, you don't seem to understand, which means it's stuff you'll inevitably forget.

In the four months this thread's been alive, you could've sat down and studied C++ to the point where you could start writing GUI applications much easier.  You may not have the best coding practices, but at least you'd understand the libraries you're using much better.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 10, 2013, 12:22:07 pm
Well this website is much easier to read through than the book so I'll post up some basic console code soon if only to stop Nexus from being condescending and repeatedly accusing me of not understanding anything throughout this entire thread, but I'm sure he'll find a way even when I get to OpenGL.

Quote

Libraries are groups of functions that have been “packaged up” for reuse in many different programs. The core C++ language is actually very small and minimalistic — however, C++ comes with a bunch of libraries, known as the C++ standard libraries, that provide programmers with lots of extra functionality. For example, the iostream library contains functions for doing input and output. During the link stage of the compilation process, the libraries from the C++ standard library are the runtime support libraries that are linked into the program (this will be discussed further in lesson 1.4).


I actually understood that and I don't know why people didn't explain libraries that way to me before when I asked, so either this is a good website or people are all going to jump in now claiming it's bullshit. Thanks again for posting that Mosseman, I'm sure other people will find the website really useful too.
Title: Re: Lethn's Programming Questions Thread
Post by: Mosseman on October 10, 2013, 01:06:13 pm
I actually understood that and I don't know why people didn't explain libraries that way to me before when I asked, so either this is a good website or people are all going to jump in now claiming it's bullshit. Thanks again for posting that Hatchet, I'm sure other people will find the website really useful too.
I'm hurt.

But serisously, I'm glad it helps.  It's taught me a lot, it's helped me design little programs and hopefully hasn't taught me any bad habits.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 10, 2013, 01:13:53 pm
LOL sorry! wrong person, so much spam :D Edited :P
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 11, 2013, 09:05:30 am
I had to ask as well, are the case and break's really necessary? The code looks nice and solid but I was just wondering because they're only basic if/else functions ( yey, the website is helping! ) I would have thought break would only be necessary if you didn't want to use a ";" or something.
Title: Re: Lethn's Programming Questions Thread
Post by: Ixrec on October 11, 2013, 09:39:52 am
If you read a decent book about C and understood how switch statements actually work, it would be pretty obvious why you need all of them.  I'll give you a real answer because I'm in a good mood but please go learn the language already.

If you skip a break; statement, then it won't break, it will just continue past the next case label.  This is handy when you want the same or similar things to happen in multiple cases.

As for why switch instead of if/else, switch statements are extremely simple to implement because it takes a single fundamental type and compares it against some constants.  An if statement has to be able to accept any boolean expresion no matter how complex.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 11, 2013, 09:51:16 am
I get that, so why is it then that the documentation code shown for events was completely different to the events tutorial and I know this is what threw me off from making the code work which is why I posted it here.


 while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window : exit
if (event.type == sf::Event::Closed)
window.close();
}

 

There's no mention of event.type here yet there is in the tutorial so no one unless they already knew the answer right away would have been able to realise that the tutorial was the correct piece of code to use or was that on purpose? I was working on this assuming I should follow the documentation, I know enough about events but I haven't read up on break and switch properly yet.

The reason I ask these kind of questions is because books and tutorials won't answer, a lot of times books and tutorials always make the mistake of assuming you already know bits and pieces or skip out sections no matter how well they're written which is why I use multiple sources despite anyone's objections and I made this thread.

So either this code was written wrong, or the event tutorial code is what you use when using more advanced techniques, or, Laurent did this on purpose to catch people out :P.
Title: Re: Lethn's Programming Questions Thread
Post by: Ixrec on October 11, 2013, 10:02:02 am
I went and checked, and both the tutorial and documentation talk about event types, plus it's right there in the code snippet you pasted so what are you claiming is being left out?  Just because they use slightly different code that does the exact same thing doesn't mean that either one is wrong.

Also, it honestly sounded like you were saying the events tutorial should be teaching you how switch statements work, which is just ludicrous.  Once again, go learn C++ before trying to use a C++ library.  A real non-shitty C++ book WILL answer all your questions about C++, then you can come back to SFML and the documentation WILL answer all your questions about SFML.  You can't tackle both at once.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 11, 2013, 10:04:42 am
lol Guess I have more reading to do then :D the book I have was recommended but I still read from other sources.
Title: Re: Lethn's Programming Questions Thread
Post by: Ixrec on October 11, 2013, 10:07:47 am
Maybe that's the problem.  Since you complained about "all" sources assuming you already know certain parts, stick to one book that assumes you know nothing at all, teaching the whole language from start to finish, and use nothing else until you've completed the whole thing (except maybe a reference site like cplusplus.com).

If you want to be absolutely sure nothing is being left out or dumbed down to make things "more accessible", The C++ Programming Language is probably a safe bet, for obvious reasons.
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 11, 2013, 10:31:06 am
Well the C++ primer book I was recommended on this thread is very good but it's so frustrating to read, I think I'm just going to have to devote some proper time studying it bit by bit :S, I've gotten through a chunk of it but I'm only about two chapters in.
Title: Re: Lethn's Programming Questions Thread
Post by: Ixrec on October 11, 2013, 10:39:35 am
Is it more frustrating then having to come here and beg for help every time a basic feature of C++ confuses you?
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 11, 2013, 10:40:26 am
Yes! :D That said I will admit it looks like the only way I'm going to be able to become independent as a programmer is rely on the book like others have said so I'm still going to keep at it.

Every time though I read the damn book I end up wanting to do this, particularly when it comes to variables: https://www.youtube.com/watch?v=Z_vxMgiRPxw

Didn't I post on this thread that one of my friends even felt sorry for me for having to read a book like this? Lmao :p
Title: Re: Lethn's Programming Questions Thread
Post by: Mosseman on October 11, 2013, 03:33:11 pm
Yes! :D That said I will admit it looks like the only way I'm going to be able to become independent as a programmer is rely on the book like others have said so I'm still going to keep at it.
Good!  You're learning very slowly at the moment but keep reading your book (as others have said: use ONE resource at a time while you're learning).  It looks like making GUI apps is the only way you're keeping yourself motivate to do this, so if toying with SFML is the you've gotta do it, then it's the way you gotta do it.  I just wish, for your sake, that you'd stick to a good tutorial/book.

Quote
Every time though I read the damn book I end up wanting to do this, particularly when it comes to variables: https://www.youtube.com/watch?v=Z_vxMgiRPxw
Variables are easy.  Wait until you start using pointers (essential to know).  Wrapping my head around that concept was difficult for me.
Title: Re: Lethn's Programming Questions Thread
Post by: Ancurio on October 13, 2013, 02:35:13 pm
Well the C++ primer book I was recommended on this thread is very good but it's so frustrating to read, I think I'm just going to have to devote some proper time studying it bit by bit :S, I've gotten through a chunk of it but I'm only about two chapters in.

If you want to create games, but aren't interested in (or even repulsed by) programming, you could just use something like GameMaker (http://www.yoyogames.com/studio).
Title: Re: Lethn's Programming Questions Thread
Post by: Lethn on October 13, 2013, 04:06:33 pm
I like games and I do like the C++ language :) I started learning C++ and SFML because games are all either made in game engines or just clones of one another now. Just recently I played Rome 2 Total War and Battlefield 4 and I was amazed at how despite the shortcuts these supposedly professional game developers took there were still huge problems even though they bought or had pre-made engines themselves. I also think part of the problem with using game engines is that a lot of the time they're inflexible and are only good at doing one job. My game ideas that I have planned for later will definitely require something more sophisticated.

So yeah, no matter how much I might bitch :P I'm still going to get through that book I hope :D.