Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Quick tips

Update field only if it’s new value

Recently I wanted to find out how to update field only if the updated value would be new (as in – different from the current one).

After a bit of googling I managed to find the solution which I’m now presenting here for anyone that may need a solution for such an use case:

UPDATE table SET db_field=(CASE db_field WHEN NULL THEN 'new_value' ELSE db_field END);

 

Angular

Angular CodeSchool Notes

Here are my notes from a free CodeSchool tutorial sponsored by Google:

Things I wish I were told about Angular.js.

Binding

<!DOCTYPE html>
<html>
	<head>
		<title>AngularJS Tutorials</title>
	</head>
	<body>
		<div ng-app="">
			<input type="text" ng-model="data.message">
			<h1>{{data.message}}</h1>
		</div>
		<script type="text/javascript" src="angular.js"></script>
	</body>
</html>

Controllers

<html>
	<body>
		<div ng-app="">
			<div ng-controller="FirstCtrl">
				<h1>{{data.message + " world"}}</h1>
				<div class="{{data.message}}">
					Msg...
				</div>
			</div>
		</div>
		<script type="text/javascript" src="angular.js"></script>
		<script type="text/javascript" src="main.js"></script>
	</body>
</html>
//main.js
function FirstCtrl($scope){
$scope.data = {message: "Hello"};
}

Dot

https://www.youtube.com/watch?v=DTx23w4z6Kc

The initial setup:

<div ng-app="">
  <input type="text" ng-model="data.message">
  <h1>{{ data.message }}</h1>

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message }}</h1>
  </div>

  <div ng-controller="SecondCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message }}</h1>
  </div>
</div>
function FirstCtrl($scope) {

}

function SecondCtrl($scope) {

}

In this setup, all three instances of data.message are bound to each other through the first data.message, which is in the scope of the entire application.

If we were to replace the instances of data.message with just message,

<div ng-app="">
  <input type="text" ng-model="message">
  <h1>{{ message }}</h1>

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="message">
    <h1>{{ message }}</h1>
  </div>

  <div ng-controller="SecondCtrl">
    <input type="text" ng-model="message">
    <h1>{{ message }}</h1>
  </div>
</div>

It breaks the scope inheritance that was binding all the data.message instances. Now, each new ng-model of message is creating a new instance of message, and so each model will be an unbound instance. So, important to note here is the data.message which will be available to all of the controllers!

Sharing data between controllers

https://www.youtube.com/watch?v=HXpHV5gWgyk

The initial setup:

<div ng-app="">
  <input type="text" ng-model="data.message">
  <h1>{{ data.message }}</h1>

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message }}</h1>
  </div>

  <div ng-controller="SecondCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message }}</h1>
  </div>
</div>
function FirstCtrl($scope) {

}

function SecondCtrl($scope) {

}

With this setup, data.message is defined outside of either controller, scoped to the entire ng-app. The bindings within each of the controller divs both point to that ‘parent’ model. Because of this, all 3 instances of the data.message input are bound to each other because of the first instance, which is globally scoped in the application.

If one were to remove the first model that does not reside in a controller, there is no parent model for either controller to bind to, so each instance of data.message will be scoped within its respective controller. Thus, neither data.message will be bound to the other.

We’d like to share the data model between the two controllers without creating a parent scope. This requires a service within a formally defined Angular application.

<div ng-app="myApp">

  <div ng-controller="FirstCtrl">
var myApp = angular.module('myApp', []);

myApp.factory('Data', function () {
  return { message: "I'm data from a service" };
});

function FirstCtrl($scope) {

This Data service can be injected into each of the controllers as a parameter. By doing this, we are now attaching the data.model to an app service, which repairs the binding between the two controller models.

Stackoverflow thread on this.

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body ng-app="myApp">
	<div ng-controller="FirstCtrl">
		<input type="text" ng-model="data.message">
		<h1>{{ data.message }}</h1>
	</div>

	<div ng-controller="SecondCtrl">
		<input type="text" ng-model="data.message">
		<h1>{{ data.message }}</h1>
	</div>
	
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
	<script type="text/javascript" charset="utf-8">
		angular.module('myApp', [])

		.factory('Data', function () {
		  return { message: "I'm data from a service" };
		})

		.controller('FirstCtrl', function ($scope, Data){
			$scope.data = Data;
		})

		.controller('SecondCtrl', function ($scope, Data){
			$scope.data = Data;
		});
	</script>
</body>
</html>

Method on a scope

function SecondCtrl($scope, Data) {
  $scope.data = Data;

  $scope.reversedMessage = function() {
    return $scope.data.message.split("").reverse().join("");
  };
}

Bootstraping https://docs.angularjs.org/guide/bootstrap

Changing the data in the service and then showing it again, the ultimate example which eluded me for some time (Plunkr):

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body ng-app="myApp">
	<div ng-controller="FirstCtrl">
		<input type="text" ng-model="data.msg">
		<h1>{{ data.msg }}</h1>

		<button type="" ng-click="sayItBack()"></button>
	</div>

	<div ng-controller="SecondCtrl">
		<input type="text" ng-model="data.msg">
		<h1>{{ data.msg }}</h1>
	</div>
	
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
	<script type="text/javascript" charset="utf-8">
		angular.module('myApp', [])

		.service('Data', function () {
			this.data = {};
			this.data.msg = "Howdy!";

			this.getMsg = function() {
			    return this.data;
			};

			this.setMsg = function(city){
				this.data.msg = city;
			};
		})

		.controller('FirstCtrl', function ($scope, Data){
			$scope.data = Data.getMsg();

			$scope.sayItBack = function(){
				Data.setMsg("Hello to you too!");
			}			
		})

		.controller('SecondCtrl', function ($scope, Data){
			$scope.data = Data.getMsg();
		});
	</script>
</body>
</html>
Stack Overflow

Options found in locals object in ejs

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I got the following error when running the project from GitHub: “options found in locals object. The option(s) is copied to the option object. This behavior is deprecated and will be removed in EJS 3”

I tried to update the ejs and express modules to the newest versions but the notice persists. I googled, ofc, and the only thread about it is this, but it doesn’t help.

Does anyone know more about this?

For reference, here is the whole important code:

app/views/index.ejs

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>

<body>
    <h1><%= title %></h1>
    <img src="img/logo.jpg" alt="Hack Hands logo">
</body>
</html>

app/controllers/index.server.controller.js

exports.render = function(req, res) {
    res.render('index', {
        title: 'MEAN MVC'
    });
};

app/routes/index.server.route.js

module.exports = function(app) {
    var index = require('../controllers/index.server.controller');
    app.get('/', index.render);
};

app/config/express.js

var express = require('express');
module.exports = function() {
    var app = express();

    app.set('views', './app/views');
    app.set('view engine', 'ejs');

    require('../app/routes/index.server.routes.js')(app);

    app.use(express.static('./public'));

    return app;
};

server.js

var port = 1337;
var express = require('./config/express');
var app = express();
app.listen(port);
module.exports = app;
console.log('Server running at http://localhost:' + port);

The answer, by Timothy Gu, was:

tl;dr: Upgrade to the latest version of EJS. It removes all warnings about options and locals.

whoami

I’m a collaborator (or the collaborator in @micnic’s comment above) in EJS v2. I only started maintaining EJS after version 2.0.3 (or something like that) was released, so I don’t know a lot about how the API changes took place.

History

EJS v2’s renderFile function, used by Express.js, now has the signature

function(path[, options[, locals]], cb)

But for compatibility with and Express.js, which calls all functions as

function(path, locals, cb)

with options mixed into the locals object, EJS automatically picks out the locals with option-y names and treat them as options.

But because the Express.js signature is also the function signature of EJS v1, we also print a warning if any option in locals is copied to options, urging developers to use the new signature with locals and options separated (it was actually me who added the warning).

However, Express.js users do not have a choice in terms of calling convention, so the warning is always present in Express.js.

Some users did complain: #34 #36.

At first, @mde (who is the main maintainer of EJS) pushed a fix, which correctly disables warnings on Express.js, and Express.js only.

But then, the person in #36 still complained, as he was using filename as the name of a local, and when the optiony local is copied to options a warning is printed.

At last, @mde was like “f*** this shit” and removed all the deprecation warnings, including an uncontroversial and legitimate one, and released version 2.2.4 (the legitimate warning was restored by me after the release).

Future

@dougwilson (an Express.js maintainer) said he was interested in a separation of options and locals in Express.js v5, just like in EJS v2. I did volunteer to make that change, but then I got busy so yeah.

Books

Time management made simple by Brian Tracy

I listened to the book Time management made simple by Brian Tracy via Audible and honestly this is one of the best I’ve read/listened on this subject.

Make a decision. Every positive change in your life begins with a clear decision that you’re going to do something or stop doing something. Either fish or cut bait.

Self-discipline is the ability to make yourself do what you should do when you should do it whether you feel like it or not.

Develop a clear goals and objectives. Be clear on what is it that you want to achieve.

Plan every day in advance.

6P = prior proper planning prevents poor performance

Working from a to do list will improve your performance by 25% very first day you start practicing it. Think on paper.

ABCDE method for setting priorities.

Select your most valuable desk and then discipline yourself to work on the single task until it is complete.

Eat that frog!

If the first thing you do each morning to get up and eat to live frog, you can be sure that nothing worst will happen all day long. Your frog is the ugliest job you have to do which is most important.

Work from a clean workspace.

Used travel time effectively! Always listen to educational material.

Zero-based thinking – is there anything in my life knowing what I know now I wouldn’t get into today if I had to do it again.

Set clear posteriorities – before you start doing something new you have to stop doing something old.

Keep your life in balance! The reason why you’re working you so that you can earn enough money to enjoy your family, health and the important parts of your personal life.

In life, relationships are everything. For 85% of your success in life will come from your happy relationships with all others. Only 15% happiness will come from your achievement from your work.

It’s quantity of time at home that counts, and quality of time at work.

Everything is hard before it’s easy. Goete

Only 21 days are needed to form a habit.

One minutes spent in planning saves 10 minutes in execution.

If I didn’t read this, will there be any negative consequences? If no – throw it away. It goes the same for information which you can get it elsewhere at a later time.

Doing something extremely well, the need not be done at all is a useless waste of time.

Effectiveness is doing the right things and efficiency is doing the things right.

The person you see is the person you will be. Imagine constantly yourself as a perfect, and you will mold your mind so.

When everyone knows that there’s an award at the end of the road the people around you will be more supportive and it will be even encourage you to work on your job until finished.

Whatever you can do, or dream you can – begin it! Boldness has genius power and magic in it. Goete

Seven years spent in bathroom. Six years eating. Five years waiting in line. Four years cleaning your house. Three years in meetings. One you searching for things. Eight months opening junk mail. Six months of waiting in the red lights. 125 days brushing your teeth. Four minutes per day conversing with your spouse. 30 seconds per day conversing with your children.

Be willing to make a decision and act on it. Be willing to make a mistake if necessary other than to hesitate or delay. The others are so afraid of a mistake that they do nothing.

John C. Gardener once wrote “Mastery it is not something that strikes instantly like a thunderbolt, but the gathering forward to it moves steadily through time, like the weather.”

To earn more, you must learn more.

Read at least one hour per day in your chosen field.

All readers are leaders.

Adult brain only learns something which is immediately applicable.

We only understand something to the degree which we are able to explain it to another person.

Delegate every job that can be done by someone else with a lower hourly rate did you earn.

Would you quit your current job if you got $10 million.

It doesn’t really matter where you’re coming from, it only matters where you’re going.

More child sees you’re committed about him doing his homework, the more it becomes committed to school work.

But she’s ill – she’s not the woman you married. Yes, but I’m still the man she married.

Don’t look at how much you already put in – invest on how the cards are now.

Never given to the temptation to clear the small things first!

Article – if it’s not immediately applicable to you, throw it away.

NodeJS

Codeschool Express.js Notes

Building blocks of Express.js on CodeSchool,  notes below… If you’re interested for more in depth tutorial about Node.js and Express, make sure you check out the 2nd tutorial (free, OFC) in a MEAN series I made for HackHands named Delving into Node.js and Express web framework.

Level 1

Install Express with npm:

npm install express

Simples web server which responds with Howdy!

var express = require('express');
var app = express();

app.get('/', function(req, res){
    res.json("Howdy!");
});

app.listen(1337); //tcp port btw

Test with curl (-i switch prints the headers):

curl -i http://localhost:1337

Redirecting the requests:

res.redirect(301, '/newLink');

Level 2

Static middleware to serve files from folder public.

app.use(express.static('public'));
app.use(function(req, resp, next){
    ...some work, when done call Ghost buster, erm, no
    next();
});

Level 3

app.get('/blocks', function(request, response) {
    //request.query.limit
    //if the request was like /api?limit=10
});
app.get('/blocks/:name', function(request, response) {
    //request.params.name
});

Level 4

//npm install body-parser

var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false });
//false forces the use of the native querystring Node library

app.post('/api', parseUrlencoded, function(request, response) {
var blocks = { ... };
var newBlock = request.body;
});

Level 5

app.route('/cities')
.get(function (request, response) {
})
.post(parseUrlencoded, function (request, response) {
});

Instead of

app.get('/apiEndpoint', function (request, response) {
});
app.post('/apiEndpoint', parseUrlencoded, function (request, response) {
});

Using the router to put in different file:

var router = express.Router();

router.route('/', router)
  .get(function (request, response) {
  })
  .post(parseUrlencoded, function (request, response) {
  });

router.route('/:name', router)
  .get(function (request, response) {
  })
  .delete(function (request, response) {
  });

app.use('/cities', router);
Books

The Egg – Andy Weir

Awesome Andy Weir and his The egg. If you like this, you may like his The Martian which will be a movie in 2015. The Youtube adaptation:

You were on your way home when you died.

It was a car accident. Nothing particularly remarkable, but fatal nonetheless. You left behind a wife and two children. It was a painless death. The EMTs tried their best to save you, but to no avail. Your body was so utterly shattered you were better off, trust me.

And that’s when you met me.

“What… what happened?” You asked. “Where am I?”

“You died,” I said, matter-of-factly. No point in mincing words.

“There was a… a truck and it was skidding…”

“Yup,” I said.

“I… I died?”

“Yup. But don’t feel bad about it. Everyone dies,” I said.

You looked around. There was nothingness. Just you and me. “What is this place?” You asked. “Is this the afterlife?”

“More or less,” I said.

“Are you god?” You asked.

“Yup,” I replied. “I’m God.”

“My kids… my wife,” you said.

“What about them?”

“Will they be all right?”

“That’s what I like to see,” I said. “You just died and your main concern is for your family. That’s good stuff right there.”

You looked at me with fascination. To you, I didn’t look like God. I just looked like some man. Or possibly a woman. Some vague authority figure, maybe. More of a grammar school teacher than the almighty.

“Don’t worry,” I said. “They’ll be fine. Your kids will remember you as perfect in every way. They didn’t have time to grow contempt for you. Your wife will cry on the outside, but will be secretly relieved. To be fair, your marriage was falling apart. If it’s any consolation, she’ll feel very guilty for feeling relieved.”

“Oh,” you said. “So what happens now? Do I go to heaven or hell or something?”

“Neither,” I said. “You’ll be reincarnated.”

“Ah,” you said. “So the Hindus were right,”

“All religions are right in their own way,” I said. “Walk with me.”

You followed along as we strode through the void. “Where are we going?”

“Nowhere in particular,” I said. “It’s just nice to walk while we talk.”

“So what’s the point, then?” You asked. “When I get reborn, I’ll just be a blank slate, right? A baby. So all my experiences and everything I did in this life won’t matter.”

“Not so!” I said. “You have within you all the knowledge and experiences of all your past lives. You just don’t remember them right now.”

I stopped walking and took you by the shoulders. “Your soul is more magnificent, beautiful, and gigantic than you can possibly imagine. A human mind can only contain a tiny fraction of what you are. It’s like sticking your finger in a glass of water to see if it’s hot or cold. You put a tiny part of yourself into the vessel, and when you bring it back out, you’ve gained all the experiences it had.

“You’ve been in a human for the last 48 years, so you haven’t stretched out yet and felt the rest of your immense consciousness. If we hung out here for long enough, you’d start remembering everything. But there’s no point to doing that between each life.”

“How many times have I been reincarnated, then?”

“Oh lots. Lots and lots. An in to lots of different lives.” I said. “This time around, you’ll be a Chinese peasant girl in 540 AD.”

“Wait, what?” You stammered. “You’re sending me back in time?”

“Well, I guess technically. Time, as you know it, only exists in your universe. Things are different where I come from.”

“Where you come from?” You said.

“Oh sure,” I explained “I come from somewhere. Somewhere else. And there are others like me. I know you’ll want to know what it’s like there, but honestly you wouldn’t understand.”

“Oh,” you said, a little let down. “But wait. If I get reincarnated to other places in time, I could have interacted with myself at some point.”

“Sure. Happens all the time. And with both lives only aware of their own lifespan you don’t even know it’s happening.”

“So what’s the point of it all?”

“Seriously?” I asked. “Seriously? You’re asking me for the meaning of life? Isn’t that a little stereotypical?”

“Well it’s a reasonable question,” you persisted.

I looked you in the eye. “The meaning of life, the reason I made this whole universe, is for you to mature.”

“You mean mankind? You want us to mature?”

“No, just you. I made this whole universe for you. With each new life you grow and mature and become a larger and greater intellect.”

“Just me? What about everyone else?”

“There is no one else,” I said. “In this universe, there’s just you and me.”

You stared blankly at me. “But all the people on earth…”

“All you. Different incarnations of you.”

“Wait. I’m everyone!?”

“Now you’re getting it,” I said, with a congratulatory slap on the back.

“I’m every human being who ever lived?”

“Or who will ever live, yes.”

“I’m Abraham Lincoln?”

“And you’re John Wilkes Booth, too,” I added.

“I’m Hitler?” You said, appalled.

“And you’re the millions he killed.”

“I’m Jesus?”

“And you’re everyone who followed him.”

You fell silent.

“Every time you victimized someone,” I said, “you were victimizing yourself. Every act of kindness you’ve done, you’ve done to yourself. Every happy and sad moment ever experienced by any human was, or will be, experienced by you.”

You thought for a long time.

“Why?” You asked me. “Why do all this?”

“Because someday, you will become like me. Because that’s what you are. You’re one of my kind. You’re my child.”

“Whoa,” you said, incredulous. “You mean I’m a god?”

“No. Not yet. You’re a fetus. You’re still growing. Once you’ve lived every human life throughout all time, you will have grown enough to be born.”

“So the whole universe,” you said, “it’s just…”

“An egg.” I answered. “Now it’s time for you to move on to your next life.”

And I sent you on your way.

Miscellaneou$

MacBook 12 keyboard fiasco

I love you Apple and all, but honestly I don’t know dafuq was it with the person who approved this keyboard – namely the keys for up/down/left/right. I mean, have you ever used this?! Like, in real life, no just an image in Photoshop?!

Jeez, imagine typing on a full scale size keyboard for 20 years and now, what do you know, someone makes this utter garbage, arrrgh! On one of my previous laptops (HP G6) they made the same mistake and never went back to it again.

I didn’t like the small movement keys on Air either, but that was manageable since all were the same size, but with this – tears and pain :/

I see people hitting the SHIFT key waaay more often now :/. Blame the 20 year muscle memory 😛

On the bright side of life, iWatch  looks nice – we’ll just have to wait a bit longer till they do something with the battery.

Stack Overflow

Group by hour in mysql but include the first value from the hour+1 also

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Say you have data like this:

  time  value
  10:00   5
  10:15   12
  10:30   15
  10:45   27
  11:00   29

And a query like this:

SELECT MAX(value)- MIN(value), HOUR(time)FROM mytable GROUP BY HOUR(time);

You will get:

 value  time
   22   10

But, I would need it to include the value at 11:00, thus the result being 24 (29-5), and not 22. Is there a way to do this in SQL or do I have no other choice than to do this manually in the code level (so, without the grouping, just fetching the data and manually substracting).

The answer, by ATP_JD, was:

Depending on how consistent your data is, you might be able to do this with a self join, like so:

SELECT HOUR(a.`time`)AS grouper,
GREATEST(MAX(a.value),IFNULL(MIN(b.value),0))- MIN(a.value)AS diff
FROM mytable a
LEFTJOIN mytable b ONIF(HOUR(a.time)<=23, HOUR(a.time)+1,0)= HOUR(b.time)GROUP BY grouper

The LEFT JOIN on the same table allows you to get the next hour’s value for comparison purposes.

http://sqlfiddle.com/#!9/fe72a/16

Ionic, Quick tips

Handling Ionic CORS issue

CORS = Cross origin resource sharing – a pain in the butt when trying to do an ajax request when developing locally.

For local testing I ended up using a Chrome plugin: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en.

The site http://enable-cors.org/ gives a lot of info on how to solve the cors issue if you control the API server. Namely, for Apache: http://enable-cors.org/server_apache.html.

But, TBH, all this ended up not working for me, so what I did was I created a “proxy” .php page which is called first (not calling the json file directly) and the PHP code for that page looks like this:

<?php
	header('Access-Control-Allow-Origin: *'); 
	echo file_get_contents("myJSON.json");
?>

edit: I answered a similar question on StackOverflow and I wrote a full tutorial with downloadable project from Github about this.

Stack Overflow

Wait for click before starting the game in Phaser

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

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>

I found the answer to this one myself:

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');

 

Page 39 of 51« First...102030«38394041»50...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak