Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - ingwik

Pages: 1 [2] 3 4 5
16
Graphics / Re: Pictures do not display, help please.
« on: May 25, 2012, 09:15:37 pm »
You've made a bunch of newbie errors, I have put CHANGE at each row that I've changed for you.
*Remember to clear screen right before you redraw
*Keep the draw routine inside the App open routine, else it will just draw once.
*I don't know why you restricted the frame rate to just 10? I commented out anyway.
*You have to draw the background first, and then the other sprites. If you do as you did, you draw the players and then the background on top of them so the background will cover them.
*You never placed the background anywhere, usually you put it on coordinates 0,0.
*Make a habit of putting as much comments as possible in the code, it makes it a lot easier to follow
*I never bothered to do any other changes than to make the images visible, from now, you're on your own but you have the altered code below. I tested the code with random pictures from Internet and they displayed as expected.
------------------------------------------------------------------------------------------------------------

#include <iostream>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
using namespace std;

int main()
{
   sf::Sprite Sprite; //Holds person image-person1 to 3
   sf::Image person[3]; //Holds the 3 different person images
   sf::RenderWindow App(sf::VideoMode(800, 600, 32),"Test");
   int whichimage = 0; //start person with image 1?
   sf:: Clock timer;
   sf:: Event Event;

   sf:: Sprite Sprite2; //Holds background
   sf:: Sprite Sprite3; //Holds ground
   sf:: Image background; //Is given to Sprite2
   sf:: Image ground; //Is given to Sprite3


   if(!person[0].LoadFromFile("person1.jpg")) {};
   if(!person[1].LoadFromFile("person2.jpg")) {};
   if(!person[2].LoadFromFile("person3.jpg")) {};
   if(!background.LoadFromFile("background.jpg")) {};
   if(!ground.LoadFromFile("ground.jpg")) {};

   person[0].CreateMaskFromColor((sf::Color::White),0);
   person[1].CreateMaskFromColor((sf::Color::White),0);
   person[2].CreateMaskFromColor((sf::Color::White),0);

   Sprite.SetImage(person[0]);

   Sprite.SetPosition(50.f, 255.f);//Here starts the person
   Sprite2.SetImage(background);
   Sprite2.SetPosition(0.0f, 0.0f); //CHANGE added a place to draw background
   Sprite3.SetImage(ground);
   Sprite3.SetPosition(0.f, 548.f); //Here is the ground

   // App.SetFramerateLimit(10); //CHANGE removed, maximum framerate? why 10???

  while (App.IsOpened())
   { //App opened start
     if (App.GetInput().IsKeyDown(sf::Key::Right))
      { //Right key start
         Sprite.SetX(Sprite.GetPosition().x+10);

        if(Sprite.GetPosition().x > 700)
        {
        Sprite.SetX(Sprite.GetPosition().x - 10);
        }

        if(Sprite.GetPosition().y > 400)
       {
       Sprite.SetX(Sprite.GetPosition().y - 10);//ground
       }

      if (timer.GetElapsedTime() >= 1.f)
      {
      go:
      Sprite.SetImage(person[+1]);
      if (++whichimage > 2)
      {
      whichimage = 0;
       }

      Sprite.SetImage(person[whichimage]);
      timer.Reset();
      }else{goto go;}

    } //end of right key press


   if (App.GetInput().IsKeyDown(sf::Key::Left))
    { //Begin left key press
       Sprite.SetX(Sprite.GetPosition().x-10);
      if(Sprite.GetPosition().x < -10)
      {
      Sprite.SetX(Sprite.GetPosition().x+10);
      }

      if(Sprite.GetPosition().y > 400)
      {
      Sprite.SetX(Sprite.GetPosition().y - 10);
      }

      if (timer.GetElapsedTime() >= 1.f)
      {
      go2:
      Sprite.SetImage(person[+1]);

      if (++whichimage > 2)
      {
       whichimage = 0;
      }
      Sprite.SetImage(person[whichimage]);
      timer.Reset();
      }else{goto go2;}

    }//End of left key pressed

   if(App.GetEvent(Event))
   {
    if (Event.Type == sf::Event::Closed)
    App.Close();
   }

   App.Clear(sf::Color::White); //CHANGE added to the end of cykle

   App.Draw(Sprite2); //Background
   App.Draw(Sprite3); //Ground
   App.Draw(Sprite); //Person CHANGE is drawn after ground and background

   App.Display();
  } //CHANGE, moved so the draw routine is within app opened
    return 0;

}

17
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 20, 2012, 03:58:55 pm »
You're right Laurent, network programming was a bridge to far for me. I thank you for the patience you've showed me and the time you have spent on trying to solve my problems.

//Ingemar

18
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 20, 2012, 12:47:38 pm »
I'm giving up any tries to continue this kind of projekt. I just can't find a way to make it work. Here, I have narrowed down the code to a bare bone. If you hit space, you send the info to the other PC. It's not more complicated than that, but I've tried both with two copies on the same PC and with two different PC:s om the same network and it is nigh impossible to recieve anything and I can't send if I'm a server. As a client sending is just fine.

If someone smarter can find the bug, I'll be happy.


 
Code: [Select]
#include <iostream>
 #include <SFML/System.hpp>
 #include <SFML/Graphics.hpp>
 #include <SFML/Window.hpp>
 #include <SFML/Network.hpp>
 //#include <vector>
 #define SFML_STATIC //No extra DLL-filer
 
 class spelare
 {
 public:
  sf::Int32 ID; //0=pojke, 1=ko (sf::Uint8) ger ascii tecken
  sf::Int32 hastighetX; //Hastighet i X-led, kan vara negativ
  sf::Int32 hastighetY; //Hastighet i Y-led, kan vara negativ
  sf::Sprite sprite; //Bilden som representerar pojken eller kon
 };

  // Server = handles boy
  // Client = handles cow

 //--------------------------------------------------------------
 // Create packet structure
 //--------------------------------------------------------------
 
 sf::Packet &operator <<(sf::Packet &Packet, const spelare &C)
 {
    return Packet << C.ID << C.hastighetX << C.hastighetY;
 }
 
 sf::Packet &operator >>(sf::Packet &Packet, spelare &C)
 {
    return Packet >> C.ID >> C.hastighetX >> C.hastighetY;
 }
 

 // Create a global TCP socket
 sf::SocketTCP spelsocket;

  //Functions
  void RunClient(unsigned short Port);
  void RunServer(unsigned short Port);

  void PlayerSend(class spelare &s);
  void PlayerRecieve( class spelare &s);

 //---------------------------------------------------------
 // Program start
 //---------------------------------------------------------
 int main (int argc, char **argv)
 {  

 char Who = 'Z'; //Are you a client or a server?
//Create a boy
 spelare pojke;
 pojke.hastighetX = 100;
 pojke.hastighetY = 100;
 pojke.ID=0;
 
 //Create a cow
 spelare ko;
 ko.hastighetX = 500;
 ko.hastighetY = 500;
 ko.ID=1;


 //--------------------------------------------------------
 // Show local adress, probably 192.168.x.x or 10.100.x.x or 169.254.x.x
 //-------------------------------------------
  sf::IPAddress Address1 = sf::IPAddress::GetLocalAddress();
  std::string IP1 = Address1.ToString();
  std::cout<<"Your local IP = " << IP1 << std::endl << std::endl;
 
 //Create a port
    const unsigned short Port = 2435;

    // Client or server ?------------------------------------------------
    std::cout << "Do you want to be a server ('s') or a client ('c') ? ";
    std::cin  >> Who;

    if (Who == 's')
        RunServer(Port);
    else
        RunClient(Port);

  spelsocket.SetBlocking(false); //Recieve without stop
 
   std::string caption;
     if (Who == 's')
        caption= "SERVER ";
    else
        caption= "CLIENT ";
 
  sf::RenderWindow App(sf::VideoMode(800, 600, 32), caption);

 while(App.IsOpened())
 { //Gameloop
  sf::Event Event;
       
 while (App.GetEvent(Event))
  { //while 2
 
     if (Event.Type == sf::Event::Closed) //hit [x] symbol?
        App.Close();
 
     if (Event.Type == sf::Event::KeyPressed)
            { //if 1
              if (Event.Key.Code == sf::Key::Escape) // ESC tangenten = close
              App.Close();

            if (Event.Key.Code == sf::Key::Space)
           {
            if (Who == 's')//server
            {
             PlayerSend(pojke); //Send info about boy
             PlayerRecieve(ko); //Recieve info about cow
             }
             else //client
            {
            PlayerSend(ko); //Send info about cow
            PlayerRecieve(pojke); //Recieve info about boy
            }
         }
      } //end if 1
 } //end, while 2
 

} // end Gameloop
 return 0;
 
 } //end  program

 void RunClient(unsigned short Port)
{
    // Ask for server IP
    sf::IPAddress ServerAddress;
    do
    {
        std::cout << "Write down IP to connect to: ";
        std::cin  >> ServerAddress;
    }
    while (!ServerAddress.IsValid());
    if (spelsocket.Connect(Port, ServerAddress) != sf::Socket::Done)
        return;
    std::cout << "Connecting to server " << ServerAddress << std::endl;

 }
 //Serverfunktionerna

  void RunServer(unsigned short Port)
 {
    if (!spelsocket.Listen(Port))
        return;
    std::cout << "Server is listening to port " << Port << ", wait for connect... " << std::endl;

    //Wait for connect
    sf::IPAddress ClientAddress;
    sf::SocketTCP Client;
    spelsocket.Accept(Client, &ClientAddress);
    std::cout << "Client connected : " << ClientAddress << std::endl;
 }


    void PlayerSend(class spelare &s)
{
sf::Packet paquetout;
spelare P; //Dummy player to save info in

P.ID = s.ID;
P.hastighetX = s.hastighetX;
P.hastighetY = s.hastighetY;
paquetout << P;
if (spelsocket.Send(paquetout) != sf::Socket::Done)
{
std::cout<<"Packet can't be sent"<<std::endl;
return;
}
else
{
std::cout<<"Packet is sent"<<std::endl;
std::cout<<"########################## " << std::endl;
std::cout<<"ID = " << P.ID << std::endl;
std::cout<<" X = " << P.hastighetX << std::endl;
std::cout<<" Y = " << P.hastighetY << std::endl;
std::cout<<"########################## " << std::endl;
}
}
  void PlayerRecieve(class spelare &s)
  {
   spelare R; //Dummy player to extract info to
   sf::Packet paquetin;
   if (spelsocket.Receive(paquetin) != sf::Socket::Done)
    {
        std::cout << "Packet is lost" << std::endl;
       return;
    }
    else  
   {
    std::cout<<"Packet is recieved"<<std::endl;
    paquetin >> R;
      std::cout<<"00000000000000000000000000000000 " << std::endl;
      std::cout<<"ID = " << R.ID << std::endl;
      std::cout<<" X = " << R.hastighetX << std::endl;
      std::cout<<" Y = " << R.hastighetY << std::endl;
      std::cout<<"00000000000000000000000000000000000 " << std::endl
    }

  }


//Ingemar

19
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 04:06:36 pm »
hmm. I have boiled it down to the " != sf::Socket::Done" routine. I need help to understand the diference between handling structs and simple numbers.

According to the examples on the homepage, this is the correct way to handle a recieving packet:

Code: [Select]
char Buffer[128];
std::size_t Received;
if ([Socketname].Receive(Buffer, sizeof(Buffer), [Packetname]) != sf::Socket::Done)
{
    // Error...
}


So, if I follow the code from the code example for sending structs between computers, I should use:
Code: [Select]
if ([Socketname].Receive([Packetname]) != sf::Socket::Done)
 return;


If I want to just check, I use this mixed code:
Code: [Select]

if ([Socketname].Receive([Packetname]) != sf::Socket::Done)
{
    // Error...
}


And here is the culprit that has annoyed me for hours. I'm getting the Error this way, but since the "return" statement is missing next code executes and I end up having the same movement for both sprites. I've checked what's going into the sending function and all values are fine. It's the recieving that doesn't work. If I use the routine that waits for a "return" value, I won't get anything to sprite no 2 and no other sprite is moved other than the one the player control on the local PC.

The odd thing is that if I use a very simple handle of structs in the game:

Sending:
Code: [Select]
sf::Int32 entete;
sf::Int32 chaine2;
sf::Int32 chaine3;

 if (Who == 's')
entete = 100;
 else
entete = 500;

 if (Who == 's')
chaine2 = 100;
 else
chaine2 = 500;

  if (Who == 's')
chaine3 = 100;
 else
chaine3 = 500;

sf::Packet paquet1;

spelare Bob;
Bob.ID = entete;
Bob.hastighetX = chaine2;
Bob.hastighetY = chaine3;
paquet1<< Bob;


Recieving
Code: [Select]
sf::Packet paquet2;
paquet2 >> Bob;


Everything actually works, even though it's handled outside the function and inside the Main code. The server (s) sends correct values and recieves the correct values from the client, without any kind of check if the socket is done.

So the question is; why is the game stopping at:
Code: [Select]
if ([Socketname].Receive([Packetname]) != sf::Socket::Done)
 return;

When it never halts in the send routine:
Code: [Select]
if ([Socketname].Send([Packetname]) != sf::Socket::Done)
 return;

It seems as if the recieving socket is never Done even when it's put in non-blocking mode.

If I remove this row from the function, nothing works (obviously), but as I said, it do work outside the function in the example above without check if the socket is ready or not.

I can obviously circumvent this issue by handling all calls inside the main loop and not using the socket check in a function at all, but I really want to understand what's going wrong here.

//Ingemar

20
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 03:49:14 pm »
I have it in the game loop just before the movement. Speed is set to 100 * adjustment (ElapsedTime) to make me be able send integers for the velocity over the network. The function sets the speed on the other players sprite in X and Y, like this:

Code: [Select]
if (server == true)
PlayerRecieve(cow);
else
PlayerRecieve(boy);

boy.sprite.Move(boy.hastighetX * ElapsedTime,boy.hastighetY * ElapsedTime);
cow.sprite.Move(cow.hastighetX * ElapsedTime,cow.hastighetY* ElapsedTime);


If no change has been, PlayerRecieve wont do a thing and the speed is kept. The values for speed in X and Y are saved inside the class.

Quote from: "Laurent"

By the way, you don't have to set the non-blocking mode everytime, once at init time is enough.


Good to know, I'll change the code.

21
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 03:33:54 pm »
Sorry Laurent, I think I've read about blocking and non-blocking calls in the forum and not in the lessons for 1.6 network.

My code isn't working. Why? I just don't know and it is so frustrating since I think I have followed your examples to create working code for a simple two player game.  But as I said, the code just stop at the check if it's done. No cout at all is sent to the player after that and the other sprite doesn't move. Just as if it never actually gets any packets.

Code: [Select]

void PlayerRecieve(class spelare &s)
  {
  spelsocket.SetBlocking(false); //Don't halt
  sf::Packet Received; //Create local packet
  spelare R; //Create local player
  if (spelsocket.Receive(Received) != sf::Socket::Done)
  return;

  if (Received >> R) //If packet isn't empty?
     {
      s.hastighetX = R.hastighetX; //give player new speed
      s.hastighetY = R.hastighetY;
      std::cout << "Recieved: " << std::endl; //Just for checking
       }
       else
      {std::cout << "Nothing recieved: " << std::endl;} //Just for checking
 }


//Ingemar

22
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 02:54:15 pm »
I am seriously trying to understand. I really do appreciate the help you are giving me Laurent. My biggest problem is that all other sides of C++ programming and game programming are covered one way or the other in hundreds of e-books out on the Internet, but network programming is hardly mentioned anywhere. That puts me in an awkward situation where I try to learn from the few sources that are around, and try to implement that slim knowledge to SFML that has a standard of its own. I do my best, have patience with me please.

And yes, after sitting in front of a PC and being programming a long time with few breaks, you do silly mistakes. Putting blocking to false before recieving the packet made the game run as it should again.

One thing that I don't understand though is why no code at all is executed after
Code: [Select]
if (spelsocket.Receive(Received) != sf::Socket::Done)
 return;

The code breaks and not a single line of code or any couts of any kind is sent to the screen. If you, or any one else can give a hint, I think I can have a chance to make it run as it should .

I'm a "doer" when coming to programming. If I get a piece of code that works, I can build on that and continue to make more and more advanced routines. The problem is that I need to see just one working example, that's what I'm working with, and asking for, here.

//Ingemar

23
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 02:44:09 pm »
Something is odd, even if I shrink the code for recieving to:
Code: [Select]
 void PlayerRecieve(class spelare &s)
  {
 sf::Packet Received;
 if (spelsocket.Receive(Received) != sf::Socket::Done)
 return;
 spelsocket.SetBlocking(false);
}


The program freeze, turns white and nothing else happens. It doesn't matter if I set blocking to true or false. Odd, really odd, and I have no clue about how to fix it.

24
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 02:30:06 pm »
Obviously, you see something that I don't Laurent:

*I create a player dummy
*I create a packet
*I check if I recieve something
*If I recieve something I get a message
*If I don't recieve anything, I get another message
*I Give the player the values from the dummy struct
*I keep doing it as long as the information keep coming

Where do I extract before recieving?

if I put this at the very beginning in the recieve function. The program ends before any messages and the screen freeze after connect and window creation but before any graphic is shown:
Code: [Select]
sf::Packet Received;
 if (spelsocket.Receive(Received) != sf::Socket::Done)
 return;


//Ingemar

25
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 12:40:03 pm »
Quote from: "Laurent"
Don't reuse packets, especially between send and receive, and especially with non-blocking sockets! Just create one whenever you need to (right before sending / receiving).


New try, I removed the global packet and creates a packet inside the function instead.

Code: [Select]
void PlayerSend(class spelare &s)
{
sf::Packet ToSend;
 ToSend << s.ID << s.hastighetX << s.hastighetY;

 if (spelsocket.Send(ToSend) != sf::Socket::Done)
        return;
}


And the recieving end:

Code: [Select]
void PlayerRecieve(class spelare &s)
  {
 spelsocket.SetBlocking(false);
 spelare R;
 sf::Packet Received;

 if (Received >> R)
    {
        if (R.ID == 0)
       {std::cout << "Boy recieved from server: " << std::endl;}
       else if(R.ID == 1)
      {std::cout << "Cow recieved from server: " << std::endl;}
      else
     {std::cout << "Garbage recieved from server: " << std::endl;}
    }
  else
    {std::cout << "Nothing recieved from server: " << std::endl;}
      s.hastighetX = R.hastighetX;
      s.hastighetY = R.hastighetY;

   if (spelsocket.Receive(Received) != sf::Socket::Done)
 return;
  }

I'm constantly getting "Nothing recieved from server: " even when I try to run both a server and a client on my own, single machine. Any idea?

//Ingemar

26
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 10:52:55 am »
I changed the code to use just one TCP socket. But I am not sure if I’m supposed to use one packet that move back and forth, or use one packet to send and one other packet to receive.

Now, I have these as globals:

Code: [Select]
//Create one global packet
 sf::Packet RegularPacket; //Id, x and y velocity

 // Create one global TCP socket
 sf::SocketTCP spelsocket;


The send function looks like this now:

 
Code: [Select]
void PlayerSend(class spelare &s)
{
spelare C = {s.ID, s.hastighetX, s.hastighetY};
RegularPacket << C;

if (C.ID == 0)
{std::cout << "Boy sent to client: " << std::endl;}
else if (C.ID == 1)
{std::cout << "Cow sent to client: " << std::endl;}
else
{std::cout << "Garbage sent to client: " << std::endl;}

if (spelsocket.Send(RegularPacket) != sf::Socket::Done)
        return;
}



And the receive function looks like this:

 
Code: [Select]
void PlayerRecieve(class spelare &s)

  {
spelsocket.SetBlocking(false); //Prevents connection otherwise
spelare C;

if (RegularPacket >> C)
   {
    if (C.ID == 0)
    {std::cout << "Boy received from server: " << std::endl;}
    else if(C.ID == 1)
   {std::cout << " Cow received from server: " << std::endl;}
 else
{std::cout << "Garbage received from server: " << std::endl;}

//Let the player sprite claim the values from the sent class/struct
s.hastighetX = C.hastighetX;
s.hastighetY = C.hastighetY;

// RegularPacket.Clear();
    }
else
{std::cout << " Nothing received from server: " << std::endl;}

if (spelsocket.Receive(RegularPacket) != sf::Socket::Done)
return;

  }



My problem now is that the boy is sending and also receiving himself (and so is the cow). It means that the cow and the boy sprites move in the same pattern for each player but the computers have no contact with each other, or at least so it seems.

I’ve tried to clear the packet with “// RegularPacket.Clear(); “ after the values have been given to the sprite/class, assuming that the reason for the unchanged ID value is that the same package is sent back and forth. But I’m really not sure about why it doesn’t seem to change ID when it obviously change X and Y values.’

Any input to the problem would be highly appreciated.

//Ingemar

27
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 19, 2012, 08:20:09 am »
So, what I have to do is to create a socket outside the functions in main or as a global and then use the same socket within all functions?

Or, am I supposed to make two different sockets? One to send and one to recieve? i.e.:

sf::SocketTCP Server;
and
sf::SocketTCP Client;


Thanks Laurent, for your quick answer.

//Ingemar

28
Network / Simple TCP connect between 2 PC's doesn't work
« on: March 18, 2012, 10:02:57 pm »
Environment: Win 7 Enterprise 64, VC++ 2010 express, SFML 1.6

I'm trying to make a simple game. A boy is running from a cow. The boy is running on the server PC and the cow is running on the client. It's a simple test to see if it's possible to run a two player game over a LAN. I've followed the tutorials but somehow, I'm stuck.

The class both inherit from (could as well has been a struct, I think):
Code: [Select]
class spelare
 {
 public:
  sf::Uint8   ID; //0=boy, 1=cow
  sf::Int32 hastighetX; //velocity, x
  sf::Int32 hastighetY; //velocity y
  sf::Sprite sprite; //Sprite with pic
 };


The packet, more or less a copy from the lesson:
Code: [Select]
sf::Packet &operator <<(sf::Packet &Packet, const spelare &C)
 {return Packet << C.ID << C.hastighetX << C.hastighetY;}

 sf::Packet &operator >>(sf::Packet &Packet, spelare &C)
 { return Packet >> C.ID >> C.hastighetX >> C.hastighetY;}


Function for a server, this function seems to work just fine.
 
Code: [Select]
void RunServer(unsigned short Port)
 {
    sf::SocketTCP Server;

    if (!Server.Listen(Port))
        return;
    std::cout << "Listen on port " << Port << ", wait for connect... " << std::endl;

    sf::IPAddress ClientAddress;
    sf::SocketTCP Client;
    Server.Accept(Client, &ClientAddress);
    std::cout << "Client connected : " << ClientAddress << std::endl;
 }


And the client, seems to work too.
Code: [Select]
void RunClient(unsigned short Port)
{
    sf::IPAddress ServerAddress;
    do
    {
        std::cout << "IP to connect to? : ";
        std::cin  >> ServerAddress;
    }
    while (!ServerAddress.IsValid());
    sf::SocketTCP Client;

    if (Client.Connect(Port, ServerAddress) != sf::Socket::Done)
        return;
    std::cout << "Connected to server " << ServerAddress << std::endl;
 }


These two functions are run once, at the startup before any windows are shown. I suppose they will be valid for the rest of the session.

Then, I have a function to send the packet with information. Since I never recieve anything, I'm not really sure if it works, but I think something is sent...

Code: [Select]
 void PlayerSend(class spelare &s)
{
    spelare C = {s.ID, s.hastighetX, s.hastighetY};
    sf::Packet RegularPacket; //Packet created
    sf::SocketTCP Client; //Socket created
    RegularPacket << C; //Packet recieve it's three values

   if (C.ID == 0)
  {std::cout << "Boy sent to client: " << std::endl;}
  else
  {std::cout << "Cow sent to client: " << std::endl;}

    if (Client.Send(RegularPacket) != sf::Socket::Done)
        return;
}


And finally, the recieving function that doesn't seem to work at all.

Code: [Select]
void PlayerRecieve(class spelare &s)
  {
  sf::Packet RegularPacket; //Packet created
  sf::SocketTCP Client;
 //Client.SetBlocking(false);
  spelare C; //Create new C
 
      if (Client.Receive(RegularPacket) != sf::Socket::Done)
   return;
 //Nothing below this point ever activates

    if (RegularPacket >> C)
    {
        if (C.ID == 0)
    {std::cout << "Boy recieved from server: " << std::endl;}
   else
    {std::cout << "Cow recieved from server: " << std::endl;}

    }
   else //No regular packet C recieved
    {std::cout << "Nothing recieved from server: " << std::endl;}
  }


The "PlayerSend" function fires every time an arrow key is pressed so it should be possible for the other PC to have the player moved.

The "PlayerRecieve" function is fired just before the cow and boy are moved. As it is now, it's possible for the client to move the cow and the server to move the boy and it seems as if the two computers are connected somehow.

I can't find what I'm doing wrong. I have followed the tutorial but obviously I have made something wrong. If someone else who is better than I can show me what might be wrong, I'll apprciate it a lot.

Yours sincerely

Ingemar

(The complete code, even though the comments are in swedish, can be found here at the bottom of the page)

29
SFML projects / Simple game showing collision detects, with source.
« on: February 08, 2012, 11:44:47 am »
This game is the first more or less complete game I’ve done. It’s produced to show two different ways of collision detect: bounding box and radius calculation. You just change one row of code by un-comment it to see how it works. As it is now, it checks the coordinates for the mouse; originally the functions checked two sprites and some remnants from that remain in the radius computing. Bear with that.

The game was created as a demonstration game in the Swedish high school, so I hope you’ll understand the names of the variables even though they aren’t English. I’ve commented as much as possible of the code, just to clarify how it works.

How do you make a game out of it?
*I used SFML 1.6, I assume you can use the same code for 2.0 without problem.
*Copy the code and paste it into an SFML project.
*Get the picture of the flags (just one) and save it in the project folder
*Compile and run
*When the name of the Nordic country or area appears, you click on the corresponding flag. If you choose wrong, or click on the background, you’ll get error points.
*A red and a green staple show how many correct, and how many erroneous clicks you’ve made. At 27 of either the game is over.

The debug version is considerable slower than the release version, so use the release version if you want to use it as a game, or change the velocity value at the move command (one place in the code) to make all move faster.

//Ingemar

Code: [Select]
//Get the picture of the flags here:
// http://www.biblioteken.fi/File/d8811b0a-b714-4911-a69f-d634b8b952a8/width/397/height/119/nordiskt_flaggor.jpg

// You’ll get different flags from the Nordic countries
// moving on the screen, click on the corresponding country - flag ,
// hit SPACE for a new country.

#include <iostream>
#include <vector>
#include <string>
#include <SFML\System.hpp>
#include <SFML\Graphics.hpp>
#include <SFML\Window.hpp>

#define SFML_STATIC //No extra DLL-files

using namespace std;

class flagga  //The flag class
{
public:
//Arraynumber = unique, hastighet = speed, flagga_x and y = coordinates
flagga (int  arraynummer, float hastighet, float flagga_x, float flagga_y);
~flagga(){};

int arraynummer; //Which country corresponds
float  hastighet; //How fast is the flag moving
float flagga_x; // Where is it in X
float flagga_y; // Where is it in Y

sf::Sprite flaggsprite; //The sprite used
};
//Pre-generated values at contruction time.
flagga::flagga (int  ut_arraynummer, float ut_hastighet, float ut_flagga_x, float ut_flagga_y)
{
       arraynummer=ut_arraynummer;
       hastighet=ut_hastighet;
       flagga_x=ut_flagga_x;
       flagga_y=ut_flagga_y;
}

//Check bounding box hit
bool Box_check_hit(float musx, float musy, sf::Sprite &maolsprite);
//Check radius hit
bool Cirkular_check_hit (float musx, float musy, sf::Sprite &maolsprite);

int main(int argc, char **argv)
{ //Main starts

/* Fill in variables within main */
double muskoordinat_x = 0.0f; //mouse x
double muskoordinat_y = 0.0f; //mouse y
unsigned int flagg_i = 0; //list item counter
int landsnummer  = 5; //What country will we get
std::string landsnamn = "Hit the swedish flag - \n[SPACE] for new flag"; //Name of the country
sf::String uttext; //Text to be printed on screen
int flaggans_hastighet = 0.0f;
int Raett = 0; //How many correct hits?
int Fel = 0; // How many incorrect hits?


/* Load the picture of all the flags */
sf::Image flaggbild; //Create an empty image holder named flaggbild
if (!flaggbild.LoadFromFile("nordiskt_flaggor.jpg")) return EXIT_FAILURE;
//Fill it with the picture: nordiskt_flaggor.jpg

std::vector<flagga> Flagglista; //Create a vector with class instances

//Add the flags with custom velocity
int r1, r2 =0;
r1 = 1.0f;
r2 = 10.0f;

flaggans_hastighet = sf::Randomizer::Random(r1, r2);
Flagglista.push_back( flagga (0, flaggans_hastighet, 400.0f, 100.0f) ); // (0=Denmark)
                           //0=Denmark, velocity, 400= xposition 100 = yposition
flaggans_hastighet = sf::Randomizer::Random(r1, r2);
Flagglista.push_back( flagga (1, flaggans_hastighet, 400.0f, 150.0f) ); //Place a new flag in the vector (1=Faroe Islands)
flaggans_hastighet = sf::Randomizer::Random(r1, r2);
 Flagglista.push_back( flagga (2, flaggans_hastighet, 400.0f, 200.0f) ); //Place a new flag in the vector (2=Iceland)
 flaggans_hastighet = sf::Randomizer::Random(r1, r2);
  Flagglista.push_back( flagga (3, flaggans_hastighet, 400.0f, 250.0f) ); //Place a new flag in the vector (3=Finland)
       flaggans_hastighet = sf::Randomizer::Random(r1, r2);
        Flagglista.push_back( flagga (4, flaggans_hastighet, 400.0f, 300.0f) ); //Place a new flag in the vector (4=Norway)
        flaggans_hastighet = sf::Randomizer::Random(r1, r2);
         Flagglista.push_back( flagga (5, flaggans_hastighet, 400.0f, 350.0f) ); //Place a new flag in the vector (5=Sweden)
         flaggans_hastighet = sf::Randomizer::Random(r1, r2);
          Flagglista.push_back( flagga (6, flaggans_hastighet, 400.0f, 400.0f) ); //Place a new flag in the vector (6=Sapmi)
          flaggans_hastighet = sf::Randomizer::Random(r1, r2);
           Flagglista.push_back( flagga (7, flaggans_hastighet, 400.0f, 450.0f) ); //Place a new flag in the vector (7=Aaland)
               flaggans_hastighet = sf::Randomizer::Random(r1, r2);
                Flagglista.push_back( flagga (8, flaggans_hastighet, 400.0f, 500.0f) ); //Place a new flag in the vector (8=Greenland)

/* Create render window that can’t be resized */
sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Guess the flags of the Nordic countries", sf::Style::Close);


for (flagg_i=0; flagg_i < Flagglista.size(); flagg_i++)
  { //Walk through the list
       //Give the image to the sprite and put it on the game board
       Flagglista.at(flagg_i).flaggsprite.SetImage(flaggbild); //give the picture to the sprite

       //Choose correct part of the sheet to show.
       // Since all flags have different size and uneven positions
       // all flag coordinates must be handmade,
       // size is 70x50 for all
       if ( Flagglista.at(flagg_i).arraynummer == 0)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(4,2,74,52));

       if ( Flagglista.at(flagg_i).arraynummer == 1)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(82,2,152,52));

       if ( Flagglista.at(flagg_i).arraynummer == 2)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(155,2,225,52));

       if ( Flagglista.at(flagg_i).arraynummer == 3)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(233,2,303,52));

       if ( Flagglista.at(flagg_i).arraynummer == 4)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(322,2,392,52));

       if ( Flagglista.at(flagg_i).arraynummer == 5) //Nästa rad
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(36,66,106,116));

       if ( Flagglista.at(flagg_i).arraynummer == 6)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(124,66,194,116));

       if ( Flagglista.at(flagg_i).arraynummer == 7)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(200,66,270,116));

       if ( Flagglista.at(flagg_i).arraynummer == 8)
               Flagglista.at(flagg_i).flaggsprite.SetSubRect(sf::IntRect(285,66,355,116));

       Flagglista.at(flagg_i).flaggsprite.SetPosition(Flagglista.at(flagg_i).flagga_x, Flagglista.at(flagg_i).flagga_y);
   } //End of walking through the flag list



while (App.IsOpened())
 { //while 1 start, game loop in action

      sf::Event Event; //Check if mouse or keyboard is used
      while (App.GetEvent(Event))
        { //while 2, check events
        if (Event.Type == sf::Event::Closed) //Hit [x] symbole?
        App.Close(); // close the program

        if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)) //ESC key pressed
        App.Close(); // close the program

                 if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space)) //SPACE tangent
                 {
 if (landsnamn == "CORRECT!" || landsnamn == "ERROR!")
  { //string doesn’t contain a name of a country
  landsnummer  = sf::Randomizer::Random(0, 8); //Välj ett land
  if (Flagglista[landsnummer].arraynummer == 0)
  landsnamn = "Denmark";
  if (Flagglista[landsnummer].arraynummer == 1)
  landsnamn = " Faroe Islands ";
  if (Flagglista[landsnummer].arraynummer == 2)
  landsnamn = "Iceland";
  if (Flagglista[landsnummer].arraynummer == 3)
  landsnamn = "Finland";
  if (Flagglista[landsnummer].arraynummer == 4)
  landsnamn = "Norway";
  if (Flagglista[landsnummer].arraynummer == 5)
  landsnamn = "Sweden";
  if (Flagglista[landsnummer].arraynummer == 6)
  landsnamn = "Sapmi";
  if (Flagglista[landsnummer].arraynummer == 7)
  landsnamn = "Aaland";
  if (Flagglista[landsnummer].arraynummer == 8)
  landsnamn = "Greenland";
  } //string doesn’t contain a name of a country
 }

     //Where did you click the mouse?
     if (Event.MouseButton.Button == sf::Mouse::Left)
        { //left mouse button
         muskoordinat_x = App.GetInput().GetMouseX();
         //What x-coordinate did we clik on?
        muskoordinat_y = App.GetInput().GetMouseY();
         //What x-coordinate did we clik on?

        for (flagg_i=0; flagg_i < Flagglista.size(); flagg_i++)
           { //Walk through the flag list and check for hits
           //Bounding box
           if (Box_check_hit(muskoordinat_x, muskoordinat_y, Flagglista.at(flagg_i).flaggsprite) == true)
         
           //Radius
           //if (Cirkular_check_hit(muskoordinat_x, muskoordinat_y, Flagglista.at(flagg_i).flaggsprite) == true)
              {//if we got a hit
               if (Flagglista.at(flagg_i).arraynummer == landsnummer)
               { //Correct guess
                landsnamn = "CORRECT!”;
                Raett = Raett + 1;                                
                } //end of correct guess
                else
                if (Flagglista.at(flagg_i).arraynummer != landsnummer)
                { //Incorrect guess
                landsnamn = "ERROR!";
                Fel = Fel + 1;
                } // end of incorrect guess
              }//end of hit    
            } //End of walking through the list

          if (landsnamn != "CORRECT!" && landsnamn != "ERROR!")
           Fel = Fel + 1; // Hit beside all flags
          } //end left mouse button

        } //End of while 2, check events

           if (Raett > 26) //Winner
                   landsnamn="YOU WON!";
           if (Fel > 26) //You loose
                    landsnamn="LOOSER!";

      uttext.SetText(landsnamn);//String with country
      uttext.SetFont(sf::Font::GetDefaultFont());
      uttext.SetSize(50);
      uttext.SetPosition(20.f, 20.f); //place the string on the game board


      /* Show the game for the player  */

    for (flagg_i=0; flagg_i < Flagglista.size(); flagg_i++)
        { //Walk through the list
        if(Flagglista.at(flagg_i).flaggsprite.GetPosition().x < 0 || Flagglista.at(flagg_i).flaggsprite.GetPosition().x > 800 - 70)
//Flag is outside the edge
         {
         Flagglista.at(flagg_i).hastighet = Flagglista.at(flagg_i).hastighet * -1; //Change direction
          }
       Flagglista.at(flagg_i).flaggsprite.Move(Flagglista.at(flagg_i).hastighet * 0.033,0); //Move the flag
          0.33 to change the velocity to a lower, float, value
        } //End of walking through the list


      App.Clear(sf::Color(100, 100, 100)); //Dark grey background

      /*Show the sprites */

      App.Draw(sf::Shape::Rectangle(0,570,10 + (Raett * 30), 580, sf::Color(0, 255, 0) )); //Green, grows with correct answers
      App.Draw(sf::Shape::Rectangle(0,585,10 + (Fel * 30), 595, sf::Color(255, 0, 0) )); //Red, grows with wrong answers or miss clicks
      //Win/loose at 27 correct/errors

       App.Draw(uttext); //Show the country name


      for (flagg_i=0; flagg_i < Flagglista.size(); flagg_i++)
      { //Walk through the list
        //Draw the flags
        App.Draw(Flagglista.at(flagg_i).flaggsprite);
      } //End of walk through the list

      App.Display(); //Show the game board or the player

} //while 1 ends, end of game loop

Flagglista.clear(); //avoid memory leaks

return 0; //last row
} //End of main

/* Function descriptions */

//BOX******************************************************************
bool Box_check_hit(float musx, float musy, sf::Sprite &maolsprite)
                   //mouse x and y, sprite is flag sprite.
// check if we clicked inside a flag
{
bool klickat_inuti = false; //return value
double maolx = maolsprite.GetPosition().x;
double maoly = maolsprite.GetPosition().y;

//Flags are 50 x 70 in size

//  inside left edge/inside right edge/inside top/inside bottom        
if ((musx > (maolx)) && (musx < maolx + 70) && musy  > maoly  && musy < maoly  + 50 )
klickat_inuti = true; //return value

return klickat_inuti;
}

//RADIus***************************************************
bool Cirkular_check_hit (float musx, float musy, sf::Sprite &maolsprite)
                         //mouse x and y, sprite is flag sprite.
//Check if we clicked inside radius (50 * 1.4……)
{
bool har_traeffat = false; //return value
double avstaond = 0.0; //distance to middle point
double traeffavstaond = 0.0; //At what distance will you hit?
double tempx; //distance in x-value
double tempy; //distance in y-value

//get the mouse coordinates
//musx and  musy are the mouse coordinates
//maolx och maoly are the flags coordinates at the center

//Re-calculate it from top left corner to center.
double maolx = maolsprite.GetPosition().x + 35;
double maoly = maolsprite.GetPosition().y + 25;

double maol_radie = (1.4142135623730950488016887242097 * 50) / 2;

//When do we hit?
traeffavstaond = maol_radie;

if (musx == maolx  && musy != maoly ) //both on same line in x
      {
      avstaond = musy - maoly;
      if (avstaond <= traeffavstaond) //within hit distance
      har_traeffat = true;
      }
else if (musy == maoly && musx != maolx ) // both on same line in y
     {
      avstaond = musx - maolx;
      if (avstaond <= traeffavstaond) // within hit distance
      har_traeffat = true;
     }
else if(musx != maolx && musy != maoly) // different places
      { //Use pythagoras theorem
      tempx = musx-maolx;
      tempy = musy-maoly;
      // Calculate hypotenusan/distance by calculating
      // square from x-distance ^2 + y-distance ^2
      avstaond = sqrt ( tempx * tempx + tempy * tempy);
      if (avstaond <= traeffavstaond) //within hit distance
      har_traeffat = true;
      } // End, using pythagoras theorem
else if (musx == maolx && musy == maoly) //The very same spot
      har_traeffat = true;

return har_traeffat;
}

30
System / Only want a function to get called once on a keyDown.
« on: February 03, 2012, 08:52:53 am »
I had a similar problem with the animation from the wiki not working as intended.

Solution: http://www.sfml-dev.org/forum/viewtopic.php?t=5933

The solution was to use enumeration to check if it was already playing and only start an animation sequence if it was false. It was for SFML 1.6 though, even if I doubt it would make a difference.

Pages: 1 [2] 3 4 5