Problem with Impact pong demo and Node/socket

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
patrick.bell
Posts: 19
Joined: Thu May 10, 2012 2:34 am

Problem with Impact pong demo and Node/socket

Post by patrick.bell »

Hi guys,

I'm not having much luck getting this Impact demo of Pong to work well with Node and Socket.io.

I'm basically at the stage (the end of video 7 of 'hallsofvalhalla's' video tutorials) of having the 2nd paddle controllable by another browser instance (i.e. another client/player) but I'm receiving an error and the 2nd player entity isn't loading, nor is the 1st player's position and movements updating on the 2nd player's screen.

The error I receive in Firebug (firefox) is pointing at a the line:

Code: Select all

var netplayers = ig.game.getEntitiesByType( EntityOtherplayer );
and the error is: 'ig.game' is null.

Here is my code so far. Note, I'm only posting the index.html, app.js, main.js and the paddle-player.js files as they are the only ones that probably matter.

First off, my index.html

Code: Select all

<!DOCTYPE html>
<html>
<head>
	<script src="http://localhost:8025/socket.io/socket.io.js"></script>
	<title>Impact Game</title>
	<style type="text/css">
		html,body {
			background-color: #000;
			color: #fff;
			font-family: helvetica, arial, sans-serif;
			margin: 0;
			padding: 0;
			font-size: 12pt;
		}
		
		#canvas {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			margin: auto;
			border: 1px solid #555;
		}
	</style>

	<script type="text/javascript" src="lib/impact/impact.js"></script>
	<script type="text/javascript" src="lib/game/main.js"></script>
</head>
<body>
<script type="text/javascript">
	  var namerand  = Math.floor(Math.random()*999);
	var playername = "player" + namerand;
	 
	  var socket = io.connect('http://localhost:8025');

socket.on('message', function (data) {
       var player = ig.game.getEntitiesByType( EntityPaddlePlayer )[0];
	 if(player)
	 {
	 player.messagebox = player.messagebox + '\n' + data + ' disconnected';
	 }
      });	 
	 
	 
socket.on('playermove', function (positiony,thisgamename) {
     var otherplayer = ig.game.getEntitiesByType( EntityOtherplayer );
    
    if(otherplayer)
    {
     for(var i in otherplayer)
	 {
	 if(thisgamename == otherplayer[i].gamename)
	 {
    // otherplayer[i].pos.x = positionx;
     otherplayer[i].pos.y = positiony;
    
	otherplayer[i].animation = currentanimation;
	 }}}
      }); 
	 
		 
	  socket.on('netreplayer', function (playerlist) {
        var netplayers = ig.game.getEntitiesByType( EntityOtherplayer );
//////////////loop to see if players exist
	if(netplayers){
		  for(var i in netplayers)
	 {
		  netplayers[i].kill();
	 }}
	 
	for(var i in playerlist)
	 {
	 if(playername != playerlist[i])
	 {
		  ig.game.spawnEntity( EntityOtherplayer, 50, 250, {gamename:playerlist[i]} );
	 }
	 }

/////////////////////////////////
      });
	  
	  
 socket.on('addplayer', function (playerlist,otherplayername) {
	  var player = ig.game.getEntitiesByType( EntityPaddlePlayer )[0];
	 player.messagebox = player.messagebox + '\n' + otherplayername + ' joined';
	 for(var i = 0;i<playerlist.length;i++)
	  {
		if(player.gamename != playerlist[i])
	 {  
		 ig.game.spawnEntity( EntityOtherplayer, 50, 150, {gamename:playerlist[i]} );
		
      
	 }}
	
      });
 

 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	</script>

	<canvas id="canvas"></canvas>
</body>
</html>
Next up, my app.js:

Code: Select all

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
 

app.listen(8025);

var playerlocation = 0;
var playerlist = [];



function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  
     
  
socket.on('recievedata', function (positiony,gamename) {
   
     socket.broadcast.emit('playermove',positiony,gamename);
    
    
  }); 

  
   
  
  
  socket.on('initializeplayer', function (newplayername) {
 
    socket.clientname = newplayername;
     playerlist.push(newplayername);
 io.sockets.emit('addplayer',playerlist,newplayername);
   
   
  });
 socket.on('disconnect', function(){
   delete playerlist[socket.clientname];
 for(var i in playerlist)
 {
  if(playerlist[i] == socket.clientname)
  {
    playerlist.splice(i, 1);
  }
 }
socket.broadcast.emit('message',socket.clientname);
 socket.broadcast.emit('netreplayer',playerlist);
 
 
});
 

 
});
next is my paddle-player.js:

Code: Select all

ig.module(
	'game.entities.paddle-player'
)
.requires(
	'impact.entity'
)
.defines(function(){

	var ismove = 0;
	var speed = 100;
	var playername = "playername";
	
	EntityPaddlePlayer = ig.Entity.extend({
		size: {x: 64, y: 128},
	messagebox: "",
		type: ig.Entity.TYPE.A,
		nettimer: 10,
	name: "player",
	gamename: playername,
		messageboxtimer: 200,
		
		checkAgainst: ig.Entity.TYPE.NONE,	
	collides: ig.Entity.COLLIDES.FIXED,
	
	animSheet: new ig.AnimationSheet( 'media/paddle-red.png', 64, 128 ),
	
	init: function( x, y, settings ) {
	this.parent( x, y, settings );
	
	//add animations
	this.addAnim( 'idle', 1, [0] );
	
	socket.emit('initializeplayer', this.gamename);
	},
	
	//movement keys
	update: function() {
		
		if( ig.input.state('up') ) {
			this.vel.y = -100;
		}
		else if( ig.input.state('down') ) {
			this.vel.y = 100;
		}
		else {
			this.vel.y = 0
		}
		
		
		if(this.nettimer < 1)
		{
			this.nettimer = 5;
		socket.emit('recievedata', this.pos.y, this.gamename);
		}
		this.nettimer = this.nettimer -1;
		
		this.parent();
	
		}
		
		
		
});

//otherplayer
EntityOtherplayer = ig.Entity.extend({
	size: {x: 64, y: 128},
	
		type: ig.Entity.TYPE.B,
		
	speed: 100,
	name: "otherplayer",
	gamename: "",
	checkAgainst: ig.Entity.TYPE.B,
	collides: ig.Entity.COLLIDES.FIXED,
	
		animSheet: new ig.AnimationSheet( 'media/paddle-blue.png', 64, 128 ),
		
	init: function( x, y, settings) {
			this.parent( x, y, settings);
			
		this.addAnim( 'idle', 1, [0] );
		},
			netmoveplayer: function()
			{		
				this.pos.y = positiony;
			},
			
	update: function() {
		
		if( ig.input.state('up') ) {
			this.vel.y = -100;
		}
		else if( ig.input.state('down') ) {
			this.vel.y = 100;
		}
		else {
			this.vel.y = 0
		}
		if(this.nettimer < 1)
		{
			this.nettimer = 5;
		}
	}
			

});

})
And finally, my main.js

Code: Select all

ig.module( 
	'game.main' 
)
.requires(
	'impact.game',
	'impact.font',			
	'game.levels.main',
	'game.entities.paddle-player'
)
.defines(function(){

MyGame = ig.Game.extend({
	
	// Load a font
	font: new ig.Font( 'media/04b03.font.png' ),
	
	
	init: function() {
		ig.input.bind( ig.KEY.UP_ARROW, 'up' );
		ig.input.bind( ig.KEY.DOWN_ARROW, 'down' );
		
		this.loadLevel( LevelMain );
	},
	
	update: function() {
		// Update all entities and backgroundMaps
		this.parent();
		
		// Add your own, additional update code here
		var player = this.getEntitiesByType( EntityPaddlePlayer ) [0];
		
	},
	
	draw: function() {
		// Draw all entities and backgroundMaps
		this.parent();
		
		var player = this.getEntitiesByType( EntityPaddlePlayer ) [0];
		player.messageboxtimer = player.messageboxtimer -1;
		
		if(player.messageboxtimer < 1)
		{
			player.messageboxtimer =100;
			var newtext = "";
			var newsplit = player.messagebox.split("\n")
			for(var i = 0;i < newsplit.length; i++)
			{
				if(i > 1)
				{
					newtext = newtext + "\n" + newsplit[i];
				}
			}
		player.messagebox = newtext;
		}
		
		this.font.draw( player.messagebox, 350, 10);
	}
});
ig.main( '#canvas', MyGame, 60, 768, 480, 1 );

});
I know this is a huge post and a bit of a pain to have to look over, but I would really appreciate any help given.
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: Problem with Impact pong demo and Node/socket

Post by Ark »

Is socket.io even defined? Uhmm does chrome console displays an error? I suggest for you to debug with chrome. Also if you're on your own computer I assume you use the server.bat file that halls gave, and it should display socket.io started, and if you load your game does it still opens? Or does it closes? if it closes then the problem is with your app.js.

hope that as helpful, good luck!
Orgullo Catracho
patrick.bell
Posts: 19
Joined: Thu May 10, 2012 2:34 am

Re: Problem with Impact pong demo and Node/socket

Post by patrick.bell »

I have it working now, it was simply a case of making the different entities controllable seperatly. For example, when I opened the first browser I could control the 1 entity on screen just fine. When the second browser was open, I could control the same entity but the new entity would update position on the 1st browser, so it was getting confused.

I just need to figure out why the are not controllable seperatly...

As for Chrome, I'm about to try it now. Also, socket.io is working just fine and is not the issue here.
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: Problem with Impact pong demo and Node/socket

Post by Ark »

Uhm There's something that's not right, on your paddle-player.js is that the EntityPaddlePlayer and EntityOtherPlayer have

Code: Select all

if(ig.input.state('up'))
which means when you press the up key both paddle will move up.

Also a problem I have faced personally is that sometimes when you move lets say the paddle, won't move up exactly as the same on the other client. So to prevent this let the server move both paddle, the one you see and what the other client sees.

// but before I show you the code first eliminate the gamename property on both entities, as they're somewhat unuseful, and also don't use the playerlist because you'll only want two players for now right?

first lets find a way to differentiate between player1 and player2 so that they don't spawn at the same spot.

app.js

Code: Select all

...

var firstPlayer = null;

...

socket.on('initializeplayer', function(newplayername){
if(!firstPlayer){    // if this activates it's the first player.
var posX = 0,
      posY = 100;    // modify this as your need
}
else{
var posX = 100,
      posY = 100;
}
firstPlayer = true;
socket.broadcast.emit('addplayer', newplayername, posX, posY);
})
index.html

Code: Select all

socket.on('addplayer', function (otherplayername, posX, posY) { 
   var p = ig.game.spawnEntity(EntityOtherPlayer, posX, posY);
         p.name = otherplayername;
      });
Also im gonna show to move the entity and prevent using socket.emit('recievedata') because it uses alot of resources, it's sending info almost every fps. something like this should work:

first change the name property ..
EntityPaddlePlayer

Code: Select all

name: playername,
EntityPaddlePlayer update function

Code: Select all

if(ig.input.pressed('up')){
socket.emit('move', this.vel.y, this.name)
}
if(ig.input.released('up'){
socket.emit('idle', this.name);
}
app.js
now lets make the server move the paddle. first lets send the info to the server.

Code: Select all

socket.on('move', function(velY, name){
io.sockets.emit('getMoving', velY, name);
});

socket.on('idle', function(name){
io.sockets.emit('getIdle', name);
});
index.html

Code: Select all

socket.on('getMoving', function(velY, playerName){
var paddle = ig.game.getEntityByName(playerName);
paddle.vel.y = velY;
});
socket.on('getIdle',function(playerName){
var paddle = ig.game.getEntityByName(playerName);
paddle.vel.y = 0;
});
Hope I explained what I tried to say hehe, if you tried this and got a problem uhm let me know ^^
Orgullo Catracho
patrick.bell
Posts: 19
Joined: Thu May 10, 2012 2:34 am

Re: Problem with Impact pong demo and Node/socket

Post by patrick.bell »

Wow, thanks a lot! I though I would just reply now so you don't think I'm not following. I will let you know how I go with the changes!

-First Error when initiating the node server (app.js) apparently 'socket.io' is not defined...
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Problem with Impact pong demo and Node/socket

Post by Jackolantern »

If you used NPM to install Socket.io on Windows, you need to make sure it actually went to where it is supposed to go. I had that problem a few night ago, where for some reason it was getting installed in the same directory as my command-line console, and not in the Node directory. It should go in the nodejs folder of the x86 programs folder, and then mine went node_modules>>npm>>node_modules>>[folder should be here] Not sure if mine is a bit odd that it is inside two node_modules folders, but that is how it set itself up. Go into your nodejs folder and scout around and make sure socket.io is there.
The indelible lord of tl;dr
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: Problem with Impact pong demo and Node/socket

Post by Ark »

uhmm yea make sure what jack said, also does the server.bat file is still open when you open up your game? or does it closes repently? If it closes then there's a syntax error on the app.js file :/
Orgullo Catracho
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: Problem with Impact pong demo and Node/socket

Post by Ark »

Ok another thing I've looked is that maybe no paddle entity will show on the game because the socket.emit('initializeplayer') is on the init function of EntityPaddlePlayer. So in order to run the initializeplayer put it on the main init function instead of the EntityPaddlePlayer. So when the game loads the socket.emit('initializeplayer') will run.
Orgullo Catracho
patrick.bell
Posts: 19
Joined: Thu May 10, 2012 2:34 am

Re: Problem with Impact pong demo and Node/socket

Post by patrick.bell »

Ark wrote:uhmm yea make sure what jack said, also does the server.bat file is still open when you open up your game? or does it closes repently? If it closes then there's a syntax error on the app.js file :/
The server starts up fine now and the socket is running.
patrick.bell
Posts: 19
Joined: Thu May 10, 2012 2:34 am

Re: Problem with Impact pong demo and Node/socket

Post by patrick.bell »

Ark wrote:Ok another thing I've looked is that maybe no paddle entity will show on the game because the socket.emit('initializeplayer') is on the init function of EntityPaddlePlayer. So in order to run the initializeplayer put it on the main init function instead of the EntityPaddlePlayer. So when the game loads the socket.emit('initializeplayer') will run.

So far, when the game loads the first entity (player 1) will spawn but is not controllable. When the 2nd browser loads, the 2nd player doesn't spawn.

Also, 'name: playerName' is not defined?
Post Reply

Return to “Beginner Help and Support”