2015-12-11 3 views
0

Имея небольшую проблему, вы получаете некоторые монеты для создания многопользовательской игры с использованием eureca.io websockets. У меня есть игроки, работающие в многопользовательском режиме и от удаленных подключений, но я не могу заставить монеты генерировать через соединение, чтобы они отображались в одном месте на всех подключениях к игрокам. Я использую phaser для создания игры и eureca и движка для моего веб-соединения. У меня есть монеты, которые появляются на странице без проблем, но всякий раз, когда присоединяется новый игрок, монета всегда отображается в другом месте, мне интересно, как я могу заставить их генерировать через соединение. Мой код игры ниже:Многопользовательские монеты

Игровой код

var myId = 0; 
var background; 
var blueSquare; 
var player; 
var coins; 
var goldCoin; 
var squareList; 
var coinList; 
var cursors; 
var score; 
var highScore; 

var ready = false; 
var eurecaServer; 

var eurecaClientSetup = function() { 
var eurecaClient = new Eureca.Client(); 
eurecaClient.ready(function (proxy) {  
    eurecaServer = proxy; 
}); 
eurecaClient.exports.setId = function (id) 
{ 
    myId = id; 
    create(); 
    eurecaServer.handshake(); 
    ready = true; 
} 
eurecaClient.exports.kill = function (id) 
{ 
    if (squareList[id]) { 
     squareList[id].kill(); 
     console.log('Player has left the game ', id, squareList[id]); 
    } 
} 
eurecaClient.exports.spawnBlueSquare = function (i, x, y) 
{ 
    if (i == myId) return; 

    console.log('A new player has joined the game'); 
    var blsq = new BlueSquare(i, game, blueSquare); 
    squareList[i] = blsq; 
} 
eurecaClient.exports.spawnCoins = function (c, x, y) 
{ 
    console.log('A coin has been generated'); 
    var cn = new GenerateCoin(c, game, coin); 
    coinList[c] = cn; 
} 
eurecaClient.exports.updateState = function (id, state) 
{ 
    if (squareList[id]) { 
     squareList[id].cursor = state; 
     squareList[id].blueSquare.x = state.x; 
     squareList[id].blueSquare.y = state.y; 
     squareList[id].blueSquare.angle = state.angle; 
     squareList[id].update(); 

     coinList.cursor = state; 
     coinList.blueSquare.x = state.x; 
     coinList.blueSquare.y = state.y; 
     coinList.update(); 
    } 
} 
} 

BlueSquare = function (index, game, player) { 
this.cursor = { 
    left:false, 
    right:false, 
    up:false, 
    down:false, 
} 

this.input = { 
    left:false, 
    right:false, 
    up:false, 
    down:false, 
} 

var x = 0; 
var y = 0; 

this.game = game; 
this.player = player; 
this.currentSpeed = 0; 

this.isBlue = true; 

this.blueSquare = game.add.sprite(x, y, 'blueSquare'); 
this.blueSquare.anchor.set(0.5); 

this.blueSquare.id = index; 
game.physics.enable(this.blueSquare, Phaser.Physics.ARCADE); 
this.blueSquare.body.immovable = false; 
this.blueSquare.body.collideWorldBounds = true; 
this.blueSquare.body.setSize(34, 34, 0, 0); 

this.blueSquare.angle = 0; 

game.physics.arcade.velocityFromRotation(this.blueSquare.rotation, 0,   this.blueSquare.body.velocity); 
} 

BlueSquare.prototype.update = function() { 
var inputChanged = (
    this.cursor.left != this.input.left || 
    this.cursor.right != this.input.right || 
    this.cursor.up != this.input.up || 
    this.cursor.down != this.input.down 
); 
if (inputChanged) 
{ 
    if (this.blueSquare.id == myId) 
    { 
     this.input.x = this.blueSquare.x; 
     this.input.y = this.blueSquare.y; 
     this.input.angle = this.blueSquare.angle; 

     eurecaServer.handleKeys(this.input);  
    } 
} 
if (this.cursor.left) 
    { 
     this.blueSquare.body.velocity.x = -250; 
     this.blueSquare.body.velocity.y = 0; 
    } 
    else if (this.cursor.right) 
    { 
     this.blueSquare.body.velocity.x = 250; 
     this.blueSquare.body.velocity.y = 0; 

    } 
    else if (this.cursor.down) 
    { 
     this.blueSquare.body.velocity.x = 0; 
     this.blueSquare.body.velocity.y = 250; 
    } 
    else if (this.cursor.up) 
    { 
     this.blueSquare.body.velocity.x = 0; 
     this.blueSquare.body.velocity.y = -250; 
    } 
    else 
    { 
     this.blueSquare.body.velocity.x = 0; 
     this.blueSquare.body.velocity.y = 0; 
    } 
} 

BlueSquare.prototype.kill = function() { 
this.alive = false; 
this.blueSquare.kill(); 
} 

GenerateCoin = function (game, goldCoin) { 

this.game = game; 
this.goldCoin = goldCoin; 

x = 0; 
y = 0; 

this.coins = game.add.sprite(x, y, 'coin'); 
game.physics.enable(this.coins, Phaser.Physics.ARCADE); 
this.coins.body.immovable = true; 
this.coins.body.collideWorldBounds = true; 
this.coins.body.setSize(16, 16, 0, 0); 
} 

window.onload = function() { 
function countdown(elementName, minutes, seconds) 
{ 
    var element, endTime, hours, mins, msLeft, time; 
    function twoDigits(n) 
    { 
     return (n <= 9 ? "0" + n : n); 
    } 
    function updateTimer() 
    { 
     msLeft = endTime - (+new Date); 
     if (msLeft < 1000) { 
      element.innerHTML = "Game Over!"; 
     } else { 
      time = new Date(msLeft); 
      hours = time.getUTCHours(); 
      mins = time.getUTCMinutes(); 
      element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds()); 
      setTimeout(updateTimer, time.getUTCMilliseconds() + 500); 
     } 
    } 
    element = document.getElementById(elementName); 
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500; 
    updateTimer(); 
}countdown("countdown", 5, 0); 
} 

var game = new Phaser.Game(700, 600, Phaser.AUTO, 'Square Hunt', { preload: preload, create: eurecaClientSetup, update: update, render: render }); 

function preload() { 
game.load.spritesheet('coin', 'assets/coin.png', 18, 18); 
game.load.image('blueSquare', 'assets/blue-square.png'); 
game.load.image('redSquare', 'assets/red-square.png'); 
game.load.image('earth', 'assets/sand.png'); 
} 

function create() { 
game.world.setBounds(0, 0, 1500, 1500); 
game.stage.disableVisibilityChange = true; 

background = game.add.tileSprite(0, 0, 800, 600, 'earth'); 
background.fixedToCamera = true; 

squareList = {}; 

player = new BlueSquare(myId, game, blueSquare); 
squareList[myId] = player; 
blueSquare = player.blueSquare; 
blueSquare.x = Math.floor(Math.random() * 650); 
blueSquare.y = Math.floor(Math.random() * 650); 

blueSquare.bringToTop(); 

game.camera.follow(blueSquare); 
game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300); 
game.camera.focusOnXY(0, 0); 

cursors = game.input.keyboard.createCursorKeys(); 

coinList = {}; 

goldCoin = new GenerateCoin(game, coins); 
coinList = goldCoin; 
coins = goldCoin.coins; 
coins.x = Math.floor(Math.random() * 650); 
coins.y = Math.floor(Math.random() * 650); 

coins.bringToTop(); 
} 

function update() { 
if (!ready) return; 

game.physics.arcade.collide(blueSquare, coins); 

player.input.left = cursors.left.isDown; 
player.input.right = cursors.right.isDown; 
player.input.up = cursors.up.isDown; 
player.input.down = cursors.down.isDown; 

player.input.fire = game.input.activePointer.isDown; 
player.input.tx = game.input.x+ game.camera.x; 
player.input.ty = game.input.y+ game.camera.y; 

background.tilePosition.x = -game.camera.x; 
background.tilePosition.y = -game.camera.y; 

for (var i in squareList) 
{ 
    if (!squareList[i]) continue; 
    var curBlue = squareList[i].blueSquare; 
    for (var j in squareList) 
    { 
     if (!squareList[j]) continue; 
     if (j!=i) 
     { 
      var targetBlue = squareList[j].blueSquare; 
     } 
     if (squareList[j].isBlue) 
     { 
      squareList[j].update(); 
     }   
    } 
} 
} 

function test(){ 
console.log('collsion'); 
} 

function render() {} 

Server.js Файлы

var express = require('express') 
, app = express(app) 
, server = require('http').createServer(app); 

app.use(express.static(__dirname)); 

var clients = {}; 
var EurecaServer = require('eureca.io').EurecaServer; 
var eurecaServer = new EurecaServer({allow:['setId', 'spawnBlueSquare', 'spawnCoins', 'kill', 'updateState']}); 
eurecaServer.attach(server); 

eurecaServer.onConnect(function (conn) {  
console.log('New Client id=%s ', conn.id, conn.remoteAddress); 

var remote = eurecaServer.getClient(conn.id);  

clients[conn.id] = {id:conn.id, remote:remote} 
remote.setId(conn.id); 
}); 

eurecaServer.onConnectionLost(function (conn) { 
console.log('connection lost ... will try to reconnect'); 
}); 

eurecaServer.onDisconnect(function (conn) {  
console.log('Client disconnected ', conn.id); 

var removeId = clients[conn.id].id; 

delete clients[conn.id]; 

for (var c in clients) 
{ 
    var remote = clients[c].remote; 
    remote.kill(conn.id); 
} 
}); 

eurecaServer.exports.handshake = function() 
{ 
for (var c in clients) 
{ 
    var remote = clients[c].remote; 
    for (var cc in clients) 
    {  
     var x = clients[cc].laststate ? clients[cc].laststate.x: 0; 
     var y = clients[cc].laststate ? clients[cc].laststate.y: 0; 

     remote.spawnBlueSquare(clients[cc].id, x, y); 
    } 
} 
} 

eurecaServer.exports.handleKeys = function (keys) { 
var conn = this.connection; 
var updatedClient = clients[conn.id]; 

for (var c in clients) 
{ 
    var remote = clients[c].remote; 
    remote.updateState(updatedClient.id, keys); 

    clients[c].laststate = keys; 
} 
} 
server.listen(8000); 

ответ

1

Вместо генерации монет случайным образом расположенных на каждом клиенте, вы можете создать эту случайную позицию (х и у) на стороне сервера (событие conexion), а затем отправить эту позицию всем клиентам, чтобы они могли сгенерировать монету в том же положении.

+0

О, отлично, что имеет смысл, весь этот сервер javascript для меня является новым, поэтому его голова слегка взорвалась – user3019749

Смежные вопросы