Node JS html Game - node.js

<!doctype html>
<html>
<head>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
var name='';
var socket = io.connect('http://localhost:8000');
$(document).ready(function() {
//var app = require('http').createServer(handler),
//io = require('socket.io').listen(app);
//app.listen(8000);
//var url = 'http://localhost:8000';
//var socket = io.connect(url);
//socket.connect();
//socket.on('movement', function() {socket.send();
//console.log('Connected!');});
while (name == '') { name = prompt("What's your name?",""); }
var left =5;
var top = 5;
var width =20;
var height =20;
var rcolor= get_random_color();
var ctx = $('#cgame')[0].getContext("2d");
ctx.fillStyle = rcolor;
ctx.fillRect(left, top, width, height);
ctx.lineWidth = 10;
$(document).keydown(onkeydown);
socket.emit('movement', function onkeydown(left,top, width, height)
{
var kycode;
if (evt!= null)
{
kycode = evt.keyCode;
ctx = $('#cgame')[0].getContext("2d");
switch(kycode)
{
case 37: //left
if(left >> ctx.left){
call: clear();
left--;
call:draw();
//alert("Hi left");
break;
}
case 38: //up
if(top >> ctx.top)
{
call: clear();
top--;
call:draw();
//alert("Hi Up");
break;
}
case 39://right
if((left+width) << (ctx.width+ctx.left) )
{
call: clear();
left++;
call:draw();
//alert("Hi right");
break;
}
case 40:
{
call: clear();
top++;
call:draw();
//alert("Hi down");
break;
}
Default:
{
alert("Hi");
break;
}
}
}
}
);
function get_random_color()
{
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ )
{
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
function clear()
{
ctx.width = ctx.width;
ctx.height = ctx.height;
ctx = $('#cgame')[0].getContext("2d");
ctx.clearRect(0,0,cgame.width,cgame.height);
}
function draw()
{
ctx.width = ctx.width;
ctx.height = ctx.height;
ctx = $('#cgame')[0].getContext("2d");
ctx.fillRect(left, top, width, height);
}
socket.emit('register', name );
$('#Name').hide();
$('#Game').hide();
$('#start').hide();
});
</script>
</head>
<body>
<label id="Game">Welcome to Node JS Gaming</label>
<input type='text' id ='Name'>
<input type='button' id="start" value= 'login' Onclick="welcome()" >
<div>
<canvas id= "cgame" style="border:1px solid #000000; width: 100%; height: 100%;"; onkeydown ="onkeydown"></canvas>
</div>
</body>
</html>
Attempted socket code:
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket)
{
socket.on('movement',function(left,top, width, height){});
socket.broadcast.emit('movement', {
});
});
}
);
//io.sockets.emit();
I have to pass the left top width and height values to the server so that the value is reflected on another client. Say for example, two clients are Chrome and Mozilla, whenever a user presses up, down, left or right the corresponding rectangle has to be moved. Similarly it should happen for other users as well.
I don't know how to pass the values. Sorry for being so naive; I am a beginner in node.js.
Please let me know what the appropriate code is for the server side.

Please see this question regarding a game that is very similar to what you are trying to achieve
EDIT: Just realised that that question omits the actual multiplayer section. My implementation of that code was as follows (not full code, only the important bits)
Client Side:
socket.on('message', function(msg) {
msg = JSON.parse(msg);
players[msg.player] = new Player(msg.name, msg.x, msg.y, msg.width, msg.height, msg.color);
});
In the Player class:
draw : function(){
context.fillStyle = this.color; // context is canvas.getContext('2d');
context.fillRect(this.x, this.y, this.width, this.height);
}
Now also on the client side you can have:
function update() {
context.clearRect(0, 0, 700, 300); // clearing the canvas (width = 700, height = 300)
for( var player in players ) {
players[player].draw();
}
}
var FPS = 60;
setInterval(update, 1000/FPS);
In my experience you'd be better off doing the actual moving of the players coordinates on the server side. So client presses Left -> sent via socket -> server adjusts players x to x-=1 and sends it back where it's then drawn.
Note that this is a crude version of the code required

Related

All fillTexted text crammed in one place in HTML5 canvas

I want to display an hexagonal grid where each cell displays its coordinate in the system (thus the top leftmost cell will have a1 written in it, the one immediately right to it will have b1 written in it, etc).
The code below is meant to achieve this (and nearly does it).
However all the texts are crammed in one small place (even though I specified the location on line 48 of the code, and this location seems correct since the rest of the image is fine). What am I doing wrong ?
<html>
<head>
<meta charset="utf-8">
<title>Hex board</title>
<script type="text/javascript">
var r = 20;
var w = r*2*(Math.sqrt(3)/2);
var ctx;
var mainWidth = 850;
var mainHeight = 600;
var dim = 11;
var i,x,y, txt;
var alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
function textFromCoordinates(x,y)
{
return(alphabet[x]+(y+1));
}
function drawHexagon(c, x, y, r)
{
c.beginPath();
c.moveTo(x, y-r);
for(i=0; i<6; i++) {
c.lineTo(x+r*Math.cos(Math.PI*(1.5+1/3*i)), y+r*Math.sin(Math.PI*(1.5+1/3*i)));
}
c.closePath();
c.fill();
c.stroke();
}
function draw()
{
ctx.clearRect(0, 0, mainWidth, mainHeight);
ctx.lineWidth = 1;
ctx.strokeStyle = "white";
for(y=0; y<dim; y++)
{
for(x=0; x<dim; x++)
{
ctx.fillStyle = "rgb(" + (x+241) + "," + (y+220) + ",178)";
drawHexagon(ctx, (x+y)*w - (y-4)*(w/2), (y+2)*1.5*r, r);
txt = textFromCoordinates(x,y);
ctx.font = 'italic 40pt Calibri';
ctx.fillStyle = "black";
ctx.moveTo((x+y)*w - (y-4)*(w/2), (y+2)*1.5*r);
ctx.fillText(txt,mainWidth/dim,mainHeight/dim);
}
}
}
function load()
{
var canvas = document.getElementById("output");
ctx = canvas.getContext("2d");
draw();
}
</script>
</head>
<body onload="load()">
<canvas style="position:absolute,top:0px,left:20px" width="850" height="600" id="output">Canvas not supported...</canvas>
</body>
</html>
You need to draw the text at the same coordinates as the hexagon:
ctx.fillText(txt,(x+y)*w - (y-4)*(w/2),(y+2)*1.5*r);
Also I've changed the font to a smaller size, and I'm aligning it around the center:
ctx.font = 'italic 16px Calibri';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
I hope this is what you need.
var r = 20;
var w = r*2*(Math.sqrt(3)/2);
var ctx;
var mainWidth = 850;
var mainHeight = 600;
var dim = 11;
var i,x,y, txt;
var alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
function textFromCoordinates(x,y)
{
return(alphabet[x]+(y+1));
}
function drawHexagon(c, x, y, r)
{
c.beginPath();
c.moveTo(x, y-r);
for(i=0; i<6; i++) {
c.lineTo(x+r*Math.cos(Math.PI*(1.5+1/3*i)), y+r*Math.sin(Math.PI*(1.5+1/3*i)));
}
c.closePath();
c.fill();
c.stroke();
}
function draw()
{
ctx.clearRect(0, 0, mainWidth, mainHeight);
ctx.lineWidth = 1;
ctx.strokeStyle = "white";
for(y=0; y<dim; y++)
{
for(x=0; x<dim; x++)
{
ctx.fillStyle = "rgb(" + (x+241) + "," + (y+220) + ",178)";
drawHexagon(ctx, (x+y)*w - (y-4)*(w/2), (y+2)*1.5*r, r);
txt = textFromCoordinates(x,y);
ctx.font = 'italic 16px Calibri';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "black";
ctx.fillText(txt,(x+y)*w - (y-4)*(w/2),(y+2)*1.5*r);
}
}
}
function load()
{
var canvas = document.getElementById("output");
ctx = canvas.getContext("2d");
draw();
}
load()
canvas{border:1px solid}
<canvas style="position:absolute,top:0px,left:20px" width="850" height="600" id="output">Canvas not supported...</canvas>

.svg asset in three.js 3d space

I'm trying to load a .svg asset into my three.js scene, as a flat vector layer; I found this example with SVGLoader and SVGRenderer from another post, but I can't make it work.
The svg loaded is stuck in 2d space and not responding to camera movement, I can't access its position.
I tried to switch to WebGLRenderer, but the svg doesn’t get loaded.
The option of loading it as sprite would be good, but I would want the sprite to not face the camera and stay still in 3d space.
var svgManager = new THREE.SVGLoader();
var url = 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Europe_laea_location_map.svg';
function svg_loading_done_callback(doc) {
init();
svg(new THREE.SVGObject(doc));
ico();
animate();
};
svgManager.load(url,
svg_loading_done_callback,
function() {
console.log("Loading SVG...");
},
function() {
console.log("Error loading SVG!");
});
var AMOUNT = 100;
var container, camera, scene, renderer;
function init() {
scene = new THREE.Scene();
renderer = new THREE.SVGRenderer();
renderer.setClearColor(0x00ff00);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1100;
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableZoom = true;
window.addEventListener('resize', onWindowResize, false);
}
function svg(svgObject) {
svgObject.position.x = 510;
svgObject.position.y = -110;
svgObject.position.z = 0;
scene.add(svgObject);
}
function ico() {
geometry = new THREE.IcosahedronGeometry(100, 1)
material = new THREE.MeshNormalMaterial({});
ico = new THREE.Mesh(geometry, material);
ico.position.y = -300;
scene.add(ico);
ico2 = new THREE.Mesh(geometry, material);
ico2.position.y = 500;
ico2.position.x = -500;
ico2.position.z = -50;
scene.add(ico2);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update;
render();
}
function render() {
renderer.render(scene, camera);
}
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%
}
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<div id="container"></div>
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/renderers/SVGRenderer.js"></script>
<script src="https://threejs.org/examples/js/renderers/Projector.js"></script>
<script src="https://threejs.org/examples/js/loaders/SVGLoader.js"></script>
<script src="https://threejs.org/examples/js/libs/stats.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
The SVGLoader and SVGRenderer are two different things. The first loads an SVG file and converts it to three.js shapes (albeit with some limitations, i.e. can read very simple SVGs, does not render strokes but only filled objects, etc), while the latter renders three.js primitives using SVG elements instead of WebGL. In a sense, they are opposites of each other.
So, first of all, you'd need to use the WebGLRenderer for your case.
Then, you need to change the SVG loading callback. It receives an array of paths with which you can render the SVG.
See the changes in functions svg_loading_done_callback, init and svg, and run it in JSFiddle:
var svgManager = new THREE.SVGLoader();
var url = 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Europe_laea_location_map.svg';
function svg_loading_done_callback(paths) {
init();
svg(paths);
ico();
animate();
};
svgManager.load(url,
svg_loading_done_callback,
function() {
console.log("Loading SVG...");
},
function() {
console.log("Error loading SVG!");
});
var AMOUNT = 100;
var container, camera, scene, renderer;
function init() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x00ff00);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1100;
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableZoom = true;
window.addEventListener('resize', onWindowResize, false);
}
function svg(paths) {
var group = new THREE.Group();
group.position.x = 510;
group.position.y = -110;
group.position.z = 0;
for ( var i = 0; i < paths.length; i ++ ) {
var path = paths[ i ];
var material = new THREE.MeshBasicMaterial( {
color: path.color,
side: THREE.DoubleSide,
depthWrite: false
} );
var shapes = path.toShapes( true );
for ( var j = 0; j < shapes.length; j ++ ) {
var shape = shapes[ j ];
var geometry = new THREE.ShapeBufferGeometry( shape );
var mesh = new THREE.Mesh( geometry, material );
group.add( mesh );
}
}
scene.add( group );
}
function ico() {
geometry = new THREE.IcosahedronGeometry(100, 1)
material = new THREE.MeshNormalMaterial({});
ico = new THREE.Mesh(geometry, material);
ico.position.y = -300;
scene.add(ico);
ico2 = new THREE.Mesh(geometry, material);
ico2.position.y = 500;
ico2.position.x = -500;
ico2.position.z = -50;
scene.add(ico2);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update;
render();
}
function render() {
renderer.render(scene, camera);
}
PS: Check the SVG Loader to see what it's able to parse

p5.js and node.js sync the position of x and y for little blobs

I'm currently making a agar.io like program for my school project using p5.js and node.js for the networking. However I'm having a problem setting all the little blobs in one locations for multiplayer mode because I wrote the program of setting the little blobs on a local javascript(circle.js). I tried to transfer the functions of the local javascript to the server.js(node.js) but when i call it, it only hangs up. This is the screenshot of the directory.
Here is the code of server.js
var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
console.log("Running");
var socket = require('socket.io');
var io = socket(server);
io.sockets.on('connection', newConnection);
function newConnection(socket){
console.log('new connection' + socket.id);
}
function asd(){
fill(255);
ellipse(200, 200, 100 * 2, 100 * 2);
}
Here is the code of the index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>agar.io</title>
<script src="libraries/p5.js" type="text/javascript"></script>
<script src="libraries/p5.dom.js" type="text/javascript"></script>
<script src="libraries/p5.sound.js" type="text/javascript"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="sketch.js" type="text/javascript"></script>
<script src="circle.js" type="text/javascript"></script>
<script src="C:/Users/hp/Desktop/p5.js/Project/agario/server.js" type="text/javascript"></script>
<style> body {padding: 0; margin: 0;} canvas {vertical-align: top;} </style>
</head>
<body>
</body>
</html>
Here is the code of Circle.js
function Circle(positionX, positionY, radius) {
this.position = createVector(positionX, positionY);
this.radius = radius;
this.velocity = createVector(0, 0);
this.show = function() {
fill(255);
ellipse(this.position.x, this.position.y, this.radius * 2, this.radius * 2);
}
this.update = function() {
var newVelocity;
velocity = createVector(mouseX - width / 2, mouseY - height / 2);
newVelocity = createVector(mouseX - width / 2, mouseY - height / 2);
newVelocity.setMag(3);
this.velocity.lerp(newVelocity, 0.2);
this.position.add(this.velocity);
}
this.eat = function(other) {
var distance = p5.Vector.dist(this.position, other.position);
if (distance < this.radius + other.radius) {
var area = Math.PI * Math.pow(this.radius, 2) + Math.PI * Math.pow(other.radius, 2);
this.radius = Math.sqrt(area / Math.PI);
return true;
} else {
return false;
}
}
}
Here is the code of sketch.js
var circle;
var circles = [];
var zoom = 1;
var newZoom;
var socket;
function setup() {
socket = io.connect('http://localhost:3000');
createCanvas(1366, 666);
circle = new Circle(0, 0, 64);
for (var x = 0; x < 410; x++) {
circles[x] = new Circle(random(-width, width * 4), random(-height, height * 4), 20);
}
}
function draw() {
background(60);
translate(width / 2, height / 2);
newZoom = (64 / circle.radius*1.5);
zoom = lerp(zoom, newZoom, 0.1);
scale(zoom);
translate(-circle.position.x, -circle.position.y);
for (var x = circles.length - 1; x >= 0; x--) {
if (circle.eat(circles[x])) {
circles.splice(x, 1);
}
}
circle.show();
circle.update();
for (var x = 0; x < circles.length; x++) {
circles[x].show();
}
asd();
}
As you can see, i tried to call a function on node.js just to try if it is valid to get an information from server.js to have a similar counts and positions of little blobs, my question is how I can make a server that gives an x and y position for the little blobs?
socket.on('mouse',
function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'mouse' " + data.x + " " + data.y);
// Send it to all other clients
socket.broadcast.emit('mouse', data);
// This is a way to send to everyone including sender
// io.sockets.emit('message', "this goes to everyone");
}
);

Phaser: remove a circle previously drawn with drawCircle

In Phaser (2.4.x), I'm drawing a circle around a sprite when it is dragged:
function dragStart(sprite, pointer, dragX, dragY) {
var graphics = game.add.graphics(0, 0);
graphics.lineStyle(6, 0x909090, 0.3);
graphics.drawCircle(dragX, dragY, 200);
}
That works fine, but now I need to remove the circle when the drag ends, and I can't figure that part out:
function dragStop() {
// ?
}
Is it possible to remove graphics? Is there a better or simpler option to draw a circle and remove it later?
You could kill() the object
But be carefull with the scope of the var you want kill (you are defining it inside the function).
Or you could just create the graphic and then show or hide depending of your event (drag)
I leave you a very simple example with both solutions:
var game = new Phaser.Game(500, 500, Phaser.AUTO, 'game');
var mainState = {
create:function(){
var graphics = game.add.graphics(0, 0);
graphics.lineStyle(6, 0x909090, 0.3);
graphics.drawCircle(game.world.centerX+100,game.world.centerY+100, 200);
console.log(graphics);
setTimeout(function(){
graphics.kill();
},2000);
this.graphics2 = game.add.graphics(0, 0);
this.graphics2.lineStyle(6, 0xff0000, 1);
this.graphics2.drawCircle(game.world.centerX-100,game.world.centerY-100, 200);
this.graphics2.visible = false;
this.show_later = game.time.now + 2000;
this.hide_again = game.time.now + 4000;
},
update:function(){
if(this.show_later < game.time.now){
this.graphics2.visible = false;
}
if(this.hide_again < game.time.now){
this.graphics2.visible = true;
}
},
};
game.state.add('main', mainState);
game.state.start('main');
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.min.js"></script>
<div id="game"></div>

Wait for click before starting the game in phaser

The JSFiddle demo is here, but am pasting the code below also. My question is simple (though I can't seem to find any example in how to realize this): right now if you start the game in JSFiddle you will see that the rectangle immediately "falls" down. I would somehow like the game to start when I click with the mouse (basically that nothing happens before the first click of a mouse) - any points on how to accomplish this?
JS:
// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};
// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {
preload: function () {
// Change the background color of the game
this.game.stage.backgroundColor = '#71c5cf';
// Load the bird sprite
this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
},
create: function () {
// Display the bird on the screen
this.bird = this.game.add.sprite(100, 245, 'bird');
// Add gravity to the bird to make it fall
this.bird.body.gravity.y = 1000;
// Call the 'jump' function when the spacekey is hit
var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
space_key.onDown.add(this.jump, this);
this.pipes = game.add.group();
this.pipes.createMultiple(20, 'pipe');
this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
this.score = 0;
var style = {
font: "30px Arial",
fill: "#ffffff"
};
this.label_score = this.game.add.text(20, 20, "0", style);
},
update: function () {
// If the bird is out of the world (too high or too low), call the 'restart_game' function
this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
if (this.bird.inWorld == false) this.restart_game();
},
// Make the bird jump
jump: function () {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
},
// Restart the game
restart_game: function () {
// Start the 'main' state, which restarts the game
this.game.time.events.remove(this.timer);
this.game.state.start('main');
},
add_one_pipe: function (x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pipe
pipe.reset(x, y);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -200;
// Kill the pipe when it's no longer visible
pipe.outOfBoundsKill = true;
},
add_row_of_pipes: function () {
this.score += 1;
this.label_score.content = this.score;
var hole = Math.floor(Math.random() * 5) + 1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
},
};
// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');
CSS:
#game_div {
width: 400px;
margin: auto;
margin-top: 50px;
}
HTML:
<div id="game_div"></div>
So, to not leave this question unanswered and to help further readers, here is the link to the updated jsFiddle where I solved my initial problem, and below is the code from jsFiddle.
However, if one will be interested I suggest taking a look at the freely available code on GitHub which uses game states and has a better structured code.
jsFiddle
CSS:
#game_div {
width: 400px;
margin: auto;
margin-top: 50px;
}
HTML:
<div id="game_div"></div>
JS:
// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};
var gameStarted = false;
// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {
game_start: function(){
if (!gameStarted){
this.bird.body.gravity.y = 1000;
this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
this.label_start.content = "";
}
gameStarted = true;
},
preload: function () {
// Change the background color of the game
this.game.stage.backgroundColor = '#71c5cf';
// Load the bird sprite
this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
},
create: function () {
// Display the bird on the screen
this.bird = this.game.add.sprite(100, 245, 'bird');
// Add gravity to the bird to make it fall
// Call the 'jump' function when the spacekey is hit
this.game.input.onDown.add(this.game_start, this);
this.pipes = game.add.group();
this.pipes.createMultiple(20, 'pipe');
this.score = 0;
var style = {
font: "30px Arial",
fill: "#ffffff"
};
this.label_score = this.game.add.text(20, 20, "0", style);
this.label_start = this.game.add.text(35, 180, "Click to start the show", style);
game.input.onDown.add(this.jump, this);
},
update: function () {
// If the bird is out of the world (too high or too low), call the 'restart_game' function
this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
if (this.bird.inWorld == false) this.restart_game();
},
// Make the bird jump
jump: function () {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
},
// Restart the game
restart_game: function () {
// Start the 'main' state, which restarts the game
this.game.time.events.remove(this.timer);
this.game.state.start('main');
gameStarted=false;
},
add_one_pipe: function (x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pipe
pipe.reset(x, y);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -200;
// Kill the pipe when it's no longer visible
pipe.outOfBoundsKill = true;
},
add_row_of_pipes: function () {
this.score += 1;
this.label_score.content = this.score;
var hole = Math.floor(Math.random() * 5) + 1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
},
};
// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');

Resources