Jump to content

  • Log In with Google      Sign In   
  • Create Account


Mr C

Member Since 04 Jan 2007
Offline Last Active Private
-----

Topics I've Started

C#/XNA socket programming question

14 March 2013 - 06:58 PM

Hi all. I didn't want to make a post about this but google has proven rather unhelpful.
 
I am in school for Game Programming and I am working on an XNA based tech demo for a class. I am trying to teach myself UDP socket programming with the goal of eventually making multiplayer game. Right now my grasp on socket programming is rudimentary at best though through example I have written a simple chat server/client. I would love to be able to use Lidgren for this but as it is a tech demo I need to write all the code myself, which I am fine with.
 
The end goal of my project is to have two sprites moving around the screen, one separate clients controlled by a server. Right now, I just want my server to tell me which key I am sending it. As of now, all I get is:
 
Received a broadcast from 192.168.x.xxx:59145
Message: NONE
 
On any key press, which at least means it is getting to my server.
 

KeyboardState keyboardState = new KeyboardState();
 
            if (Keyboard.GetState().GetPressedKeys().Length > 0)
            {
                // Default movement is none
                if (!keyboardState.IsKeyDown(Keys.W) || !keyboardState.IsKeyDown(Keys.A) || !keyboardState.IsKeyDown(Keys.S) || !keyboardState.IsKeyDown(Keys.D))
                {
                    MoveDir = MoveDirection.NONE;
                }
                if (keyboardState.IsKeyDown(Keys.W))
                {
                    MoveDir = MoveDirection.UP;
                }
                if (keyboardState.IsKeyDown(Keys.A))
                {
                    MoveDir = MoveDirection.LEFT;
                }
                if (keyboardState.IsKeyDown(Keys.S))
                {
                    MoveDir = MoveDirection.DOWN;
                }
                if (keyboardState.IsKeyDown(Keys.D))
                {
                    MoveDir = MoveDirection.RIGHT;
                }
 
                byte[] send_buffer = Encoding.ASCII.GetBytes(MoveDir.ToString()); 
 
                try
                {
                    sending_socket.SendTo(send_buffer, sending_end_point);
 
                }
                catch (Exception send_exception)
                {
                    exception_thrown = true;
                    Console.WriteLine(" Exception {0}", send_exception.Message);
                }
                if (exception_thrown == false)
                {
                    Console.WriteLine("Message has been sent to the broadcast address");
                }
                else
                {
                    exception_thrown = false;
                    Console.WriteLine("The exception indicates the message was not sent.");
                }
            }
 
That is the chunk of relevant code inside my XNA update function. MoveDir is declared at the start of my file as an instance of Movedirection. 
 

  // Move direction enumerator
    enum MoveDirection
    {
        UP,
        DOWN,
        LEFT,
        RIGHT,
        NONE
    }
is my enum
 
I don't think it matters but my server code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace Server
{
    public class UDPListener
    {
        private const int listenPort = 11000;
 
 
        static int Main(string[] args)
        {
            bool done = false;
 
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            string recieved_userName;
            string received_data;
            byte[] receive_name_array;
            byte[] receive_byte_array;
            receive_name_array = listener.Receive(ref groupEP);
           
 
            try
            {
                while (!done)
                {
                    
                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Console.Write("Message: {0}\n", received_data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            listener.Close();
            return 0;
        }
 
    }
}
 
Anyways, like I said I am new to this and trying to figure it all out. My level of experience is a college level data structures course. XNA does not support "true keyboard input" (http://dream-forever.net/Blog/2011/08/29/getting-true-keyboard-input-into-your-xna-games/) and I know there HAS to be a simpler way to get this done besides what is suggested in that post. I don't need it to be pretty, just to work. 
 
If this is a dumb question, I apologize for wasting peoples time. Thanks for any help.
 
Edit: I was unsure if I should post this here or in the networking section, since it has XNA specific stuff I chose here, please move if it is out of place.

I feel really dumb, but I am stuck on this (changing direction of a sprite)

23 April 2010 - 10:08 PM

Hey, I am currently working on making a pong clone (for learning purposes). I have it to the point where both paddles and the ball are onscreen, both paddles can be controlled, and there are checks in place to make sure nothing goes off screen. However when I added the ball, I ran into problems. I can get it to move at the start fine (as the code below shows), and it stops where its supposed to (well, close enough anyways). The problem is I cannot for the life of me figure out how to get it to change direction. I know its going to be something stupid but I have been working on this for awhile now and I feel I have gotten to the point where I should ask for help. Note: This project is being done with SFML in Code::Blocks, if that information makes any difference.
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    // Create the main rendering window
   sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Pong");
   App.SetFramerateLimit(60); // Limits framerate

   // Next 3 lines display window size in console
   std::cout << App.GetHeight();
   std::cout << "\n";
   std::cout << App.GetWidth();

   sf::Image bluePaddle;
   sf::Image redPaddle;
   sf::Image ball;


// next 3 (currently 2) if's load images and displays error message if there is a problem
   if (!bluePaddle.LoadFromFile("bluePaddle.png"))
    {
    std::cout << "Error, bluePaddle.png failed to load";
    }
   if (!redPaddle.LoadFromFile("redPaddle.png"))
    {
    std::cout << "Error,redPaddle.png failed to load";
    }
   if (!ball.LoadFromFile("ball.png"))
    {
    std::cout << "Error, ball.png failed to load";
    }

// set blue paddle sprite and values
sf::Sprite bluePaddleSprite(bluePaddle);
bluePaddleSprite.SetY(200);

// set red paddle sprite and values
sf::Sprite redPaddleSprite(redPaddle);
redPaddleSprite.SetX(784);
redPaddleSprite.SetY(200);

// set the ball's sprite and values
sf::Sprite ballSprite(ball);
ballSprite.SetX(250);
ballSprite.SetY(250);

    // Start game loop
    while (App.IsOpened())
    {

        // Process events
        sf::Event Event;
        while (App.GetEvent(Event))
        {
            // Close window : exit
            if (Event.Type == sf::Event::Closed)
                App.Close();

            // A key has been pressed
            if (Event.Type == sf::Event::KeyPressed)
            {
                // Escape key : exit
                if (Event.Key.Code == sf::Key::Escape)
                    App.Close();
            }
        }
        // Clear the screen
        App.Clear(sf::Color(0, 0, 0));

//next 2 if's for bluePaddles border gaurds (collision detection, makes sure it stays in bounds)
      if (bluePaddleSprite.GetPosition().y < 0)
        {
        bluePaddleSprite.SetY(0.5);
        }

      if(bluePaddleSprite.GetPosition().y > App.GetHeight()-bluePaddle.GetHeight())
        {
        bluePaddleSprite.SetY(455);
        }

//nest 2 ifs are for redPaddles vorder gaurds (same as blue)

      if (redPaddleSprite.GetPosition().y < 0)
        {
        redPaddleSprite.SetY(0.5);
        }

      if(redPaddleSprite.GetPosition().y > App.GetHeight()-redPaddle.GetHeight())
        {
        redPaddleSprite.SetY(455);
        }


//-> start of code dealing with ball. This bit will deal with ball movement/collision/etc

     ballSprite.Move(150 * App.GetFrameTime() * -1, 0);

     if (ballSprite.GetPosition().y < 0)
        {
        ballSprite.SetY(0.5);
        }

      if(ballSprite.GetPosition().y > App.GetHeight()-ball.GetHeight())
        {
        ballSprite.SetY(582);
        }

      if(ballSprite.GetPosition().x < bluePaddleSprite.GetPosition().x + 16)
      {
        ballSprite.Move(150 * App.GetFrameTime() * 1, 0);
      }

//<- end of all the work with ball



//this chunk provides the code for player control (movement)

      if (App.GetInput().IsKeyDown(sf::Key::W))  {
         bluePaddleSprite.Move(0, 150 * App.GetFrameTime() * -1);
      } else if (App.GetInput().IsKeyDown(sf::Key::S)) {
        bluePaddleSprite.Move(0, 150 * App.GetFrameTime() * 1);
      }

//this bit is a tester for red before I put in AI, to make sure movement works. (tested working)

      if (App.GetInput().IsKeyDown(sf::Key::Up))  {
         redPaddleSprite.Move(0, 150 * App.GetFrameTime() * -1);
      } else if (App.GetInput().IsKeyDown(sf::Key::Down)) {
        redPaddleSprite.Move(0, 150 * App.GetFrameTime() * 1);
      }


    //Draws the blue Paddle
      App.Draw(bluePaddleSprite);
    //Draws the red paddle
      App.Draw(redPaddleSprite);
    //Draws the ball
      App.Draw(ballSprite);

        // Display window contents on screen
        App.Display();
    }


    return EXIT_SUCCESS;
}

Is my full code. The piece of code in question is:
     ballSprite.Move(150 * App.GetFrameTime() * -1, 0);

     if (ballSprite.GetPosition().y < 0)
        {
        ballSprite.SetY(0.5);
        }

      if(ballSprite.GetPosition().y > App.GetHeight()-ball.GetHeight())
        {
        ballSprite.SetY(582);
        }

      if(ballSprite.GetPosition().x < bluePaddleSprite.GetPosition().x + 16)
      {
        ballSprite.Move(150 * App.GetFrameTime() * 1, 0);
      }


There are a few other bugs, such as that although the ball stops, it stops at the point even if the paddle is not there (leading me to think I made it so its checking the y value of the area the paddle is on, instead of just the paddle). However my biggest problem right now is just getting the ball to change directions on contact. Thank you, and sorry for the trouble.

A good sprite resource I found

20 April 2010 - 12:03 PM

The topic above seems to have been archived, or I would have posted this there. http://www.panelmonkey.org/category.php?id=1 is a site that has a great collection of free to use sprites. http://www.panelmonkey.org/sprite.php?id=146&theme=3 is an example, and when you save the image there is no background. Hope this helps some people.

Better way to swap images in SFML?

20 April 2010 - 11:57 AM

Hey all, I am working on a bit of code and I was wondering if any of you knew a better way to change one image into another then the way I am using. I looked on the SFML site and could not find anything...
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>

int main()
{

//sf::Clock gameClock;
//float timeElapsed = 0;

try {

    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Window");
    sf::Image mageReady;
    sf::Image mageCast;
    sf::Image Fire_Ball;

    if (!mageReady.LoadFromFile("mageReady.png"))
        {
            throw std::string("Your image failed to load");
        }
    if (!mageCast.LoadFromFile("mageCast.png"))
        {
            throw std::string("Your image failed to load");
        }

    if (!Fire_Ball.LoadFromFile("fireball.png"))
        {
        throw std::string("Your image failed to load");
        }

        sf::Sprite mageReadySprite;
        mageReadySprite.SetImage(mageReady);
        mageReadySprite.SetCenter(38, 38);

        sf::Sprite mageCastSprite;
        mageCastSprite.SetImage(mageCast);
        mageCastSprite.SetCenter(38, 38);

        sf::Sprite Fire_Ball_Sprite;
        Fire_Ball_Sprite.SetImage(Fire_Ball);

    bool isNotCasting = true;
    bool isCasting = false;
    bool showFireBall = false;
    bool Running = true;
    while (Running)
    {

        //timeElapsed = gameClock.GetElapsedTime();
        sf::Event myEvent;
        while (App.GetEvent(myEvent))
        {
            // Window closed
            if (myEvent.Type == sf::Event::Closed)
                App.Close();

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

            //show mage cast/spell.
            if ((myEvent.Type == sf::Event::KeyPressed) && (myEvent.Key.Code == sf::Key::C))
            {
            isCasting = true;
            showFireBall = true;
            mageCastSprite.SetX(mageReadySprite.GetPosition().x);
            mageCastSprite.SetY(mageReadySprite.GetPosition().y);
            Fire_Ball_Sprite.SetX(mageCastSprite.GetPosition().x + 10);
            Fire_Ball_Sprite.SetY(mageCastSprite.GetPosition().y -60);
            }

        }
       // Clear the screen (fill it with black color)
        App.Clear(sf::Color(255, 255, 255));

        //draw mage sprite
        if (isNotCasting == true)
        {
        App.Draw(mageReadySprite);
        }
        if (isNotCasting == false)
            {
            isNotCasting = false;
            }

        //draw mage cast
        if (isCasting == true && showFireBall == true)
        {
        isNotCasting = false;
        App.Draw(mageCastSprite);
        App.Draw(Fire_Ball_Sprite);
        }

        // Get elapsed time
        float ElapsedTime = App.GetFrameTime();
        // Move the sprite
        if (App.GetInput().IsKeyDown(sf::Key::Left))  mageReadySprite.Move(-100 * ElapsedTime, 0);
        if (App.GetInput().IsKeyDown(sf::Key::Right)) mageReadySprite.Move( 100 * ElapsedTime, 0);
        if (App.GetInput().IsKeyDown(sf::Key::Up))    mageReadySprite.Move(0, -100 * ElapsedTime);
        if (App.GetInput().IsKeyDown(sf::Key::Down))  mageReadySprite.Move(0,  100 * ElapsedTime);

        if (isCasting == true){

        if (App.GetInput().IsKeyDown(sf::Key::Left))  mageCastSprite.Move(-100 * ElapsedTime, 0);
        if (App.GetInput().IsKeyDown(sf::Key::Right)) mageCastSprite.Move( 100 * ElapsedTime, 0);
        if (App.GetInput().IsKeyDown(sf::Key::Up))    mageCastSprite.Move(0, -100 * ElapsedTime);
        if (App.GetInput().IsKeyDown(sf::Key::Down))  mageCastSprite.Move(0,  100 * ElapsedTime);

        }

        App.Display();


    }

}
catch (std::string message)
{
std::cout << "you fail because " << message;
}
    return 0;
}





Right now I have it so that when the key is pressed it puts the mageCast sprite where the mageReady sprite was, and hides the mageReady. I am looking for either a way to temporarily (or permanently) remove/delete an image when I want. The goal of this little program is to eventually have the mage walk, cast and shoot (show it casting, have the spell move X amount and then delete itself), then go back to the first image (mageReady). Right now I can move with the first image, and "C" will swap it into the second one and place the fireball where I want it. I feel that there must be a better way to do what I am trying to do.. Thanks all. Edit: Does this belong in the Alternative Game Libraries forum? I am not sure, please move if it does, and sorry if this is the wrong place.

Help with a file i/o question

17 April 2010 - 06:43 PM

Hey, I am writing a small program that saves the text the user enters and then displays it when they choose the load option next time they run the program. My problem is this:

ofstream myOutFileStream("save1.txt");
myOutFileStream << "I like cheese";
myOutFileStream.close();

ifstream myInFileStream("save1.txt");
string save1((istreambuf_iterator<char>(myInFileStream)), istreambuf_iterator<char>());
cout << save1;
myInFileStream.close();

That works fine, load the whole "I like cheese" thing no problem. However when I went to make my user version I found I could only get it to open the first word of the string entered. When I tried using cin.getline() it would not even let me enter the text. Here is my current code:
#include <iostream>
#include <string>
#include <fstream>

using std::cin;
using std::cout;
using std::string;
using std::ofstream;
using std::ifstream;
using std::istreambuf_iterator;

int main()
{

int choice;

cout << "Hello user! I was told to greet you in a nice and polite way! Lets be friend?\n";
cout << "So, do you want to create a new file or load the last one?\n";
cout << "1)new 2)load: ";
cin >> choice;
if (choice == 1){
    char text[50];
    cout << "Enter the text: ";
    cin >> text;
    ofstream myOutFileStream("save1.txt");
    myOutFileStream << text;
    myOutFileStream.close();
    }

if (choice == 2){
    ifstream myInFileStream("save1.txt");
    string save1((istreambuf_iterator<char>(myInFileStream)), istreambuf_iterator<char>());
    cout << save1;
    myInFileStream.close();
    }
}

using cin.getline(text,50); did not work as I said. Kind of at a loss. I want the user to be able to type a sentence, save that sentence to a file, then load it and print it. I am pretty sure the problem is on the line "cin >> text" and I know that cin stops at a space (" "), so I know that it is only getting the first word. When I Google'ed getline and such I found http://www.cplusplus.com/reference/iostream/istream/getline/ but for some reason it won't work for me. Any ideas?

PARTNERS