RunPigsRun: the code organization.

dp-300x70.png

As this is my second project in Javascript, I’ve manage to achieve code organization/conventions, which helps me to move through code quickly and make it less error prone. I was mainly inspired by some games from https://github.com/photonstorm/phaser-examples. There will be nothing revolutionary nor even advanced here.

Classes

I’m a fanatic of decomposing code into classes, every time, everywhere. Class should be concrete, specialized, well named and decomposed into specialized functions. If class is getting big, part of its functionality should be extracted into another classes.

Everything above is crystal clear, yet generally JS is strangely considered as a language, where everything should be accessible from everywhere, and code is just one big sequence of monstrous functions which are so, so, so… SO hard to read. Sometimes it’s even impossible to track paired brackets. Anyway: readability first… as the famous quoute says:

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

Generally I’m organizing code into directories to simulate something like packages… Next: I’m writing quite a lot of constructor classes. New concept = new class. New specialized functionality = new class.

If a new function is not depending on a class, I’m putting it in a different file. E.g. having MovementManager class, some help functions are needed like movementDirectionOpposite (returning opposite direction), which is used only by MovementManager. Hence this function is not using class, it lands in a separate file moveFunctions.js.

Object orientation

I’m carefully tracking how classes are connected with composition and how they are communicating with each other, so general objective oriented programming principles are followed. Drawing UML class diagrams is a helpful way of tracking if the code organization is kept clean.

Composition vs inheritance

I’m not using inheritance through prototypes, as I agree, that inheritance is (generally) only good for type casting done in other languages. For now, composition solves every problem and makes code easily understandable.

Constants

Constant variables are indicated by using uppercase. Used also in function arguments, to not to accidentally modify unwanted object, which was a reason of many hard to track errors (example of such struggle: http://adam.skobo.pl/?p=754).

When a value (int/string) is used more than one time, then it’s frozen with Object.freeze. E.g defining GameObject types:

GameObjectType = Object.freeze({
        VOID: "void", // for empty fields
        HUT: "hut",
        HERO: "hero",
        ROAD: "road",
        BRIDGE: "bridge",
        WATER: "water",
        SIGN: "sign",
        TOOL_BOUNCER: "t_bouncer",
        TOOL_DUMMY: "t_dummy"
});
GOT = GameObjectType; // alias

Later instead of writing:

if (OBJECT.type === "hero") {

a constant is used…

if (OBJECT.type === GOT.HERO) {

… which assures, that no typo is made.

Further reading

I’m aware that some further reading awaits to improve code organization and its readability and my current Javascript knowledge needs a lot of improvement. Candidates for a study in a nearest future:

  • JavaScript: The Good Parts, Douglas Crockford
  • JavaScript Patterns, Stoyan Stefanov
  • Maintainable JavaScript, Nicholas C. Zakas
  • Speaking JavaScript. An In-Depth Guide for Programmers, Axel Rauschmayer

written in Emacs with org2blog mode

Beeminder: a healthy sting.

dp-300x70.png

Previously described Rescuetime is doing almost a perfect job. You can track Your daily productivity and weekly goals (remember how You can create ‘Software Development’ objective?). But what if You fail to achieve Your personal vow, to work on a software project X hours a week? Ha! Nothing! Maybe You feel a little bad, that’s all.

I’ve heard that in one office, when someone had sworn, he had to put some cash in a jar. It’s the same like saying to someone ‘punch me, if I ever do X again’. Or when You make an agreement with someone, to not to come back to a bad habit (smoking maybe?) as long as he/she does something similar, which is important to You, in return. A public agreement… someone is watching You, so it’s harder to break the rules!

How about something guarding our goal to spend X hours a week on a software development? Let me introduce You to …

… “A kick in the pants!”

website_logo_mid_type.jpg

Beeminder is a service allowing to create weekly goals on doing anything quantifiable. Users have to report their progress on a website or with a dedicated mobile application. Current status can be tracked, by reading how much we have to do, to make our objectives valid. If we are approaching the deadline, Beeminder starts to go crazy and reminds us to get to work by sending emails and by displaying regular popups on a mobile (e.g 12h left for Goal X). This is how the goals summary look like on a mobile:

bee.jpg

It’s crystal clear what the status is. Some data has to be reported manually (like how much we’ve read today) and some is gathered by Beeminder automatically, when we are using supported external service.

“Follow through or pay the price.”

Now this is a part, which may seem controversial, or rather ‘stupid’, as say most of the people for whom I’ve told about Beeminder. How user is punished for not reporting data on time? By money taken away from the credit card. We are setting how much will be lost, and these are small, but yet motivating amounts (like 5$, 10$). There has to be that little noticeable punishment.

Personally I’m not so motivated by the money loss (but to be honest, it’s taking some part in a Beeminder challenge too). Rather by the failure, which is felt, when application is showing skull and crossbones on a goal entry icon. Then an extra week is added to the deadline, so the user has a bigger chance to stay on a goal track. And it feels bad, because the wonderful rhythm of a regular work is lost.

“Light a fire under your own butt…”

When it’s about goals, which cannot be verified by a Beeminder, users can be tempted to log a false data. But then: what’s the point of using this service anyway?

As mentioned, there are also services, which will report data automatically and one of them is the previously introduced Rescuetime. Software Development goal can be connected with Beeminder and voilà! There is no escape now from not spending a set time with our project.

I’ve had a couple of situations, when I had to rush back home, to work a required amount of time with Run Pigs Run. I’m sure that many times I would give up. Definitely my progress would be less effective.

And still: I’ve set not so challenging amount of daily time: only 1.5 hours! Of course i can work e.g 4.5 hours on Sunday and have more flexible week. It has to be mentioned, that Rescuetime is quite accurate… probably very accurate. It’s not enough to be focused on a specific program. Client checks if You’re typing something or moving mouse. Sometimes a 5 minute break is taken, sometimes we have to stop and think… Both services know no mercy! Only active time is recorded, so sometimes extra 20-30% time with writing is needed to meet goal’s requirements.

“BEEhave yourself!”

If it’s about dajsiepoznac.pl contest, I’m also using Beeminder to track how many posts I’ve written. Goal: two posts a week. It’s a good way to be sure, that at least this amount is released.

In bee end…

I realize that the part with money loss could be the only part which makes You to not even take Beeminder into consideration. And it’s understandable. The thing which service’s authors are describing as ‘interesting’ (watch the Nice Lady’s introduction video on a website) is probably the thing which could scare the most. As I’ve mentioned: it’s working for me, I’m always pledging the lowest 5$, but it’s not the main reason, why I’m using this service. It’s just a good piece of software with a handy reminder and accurate measurement tool which can be integrated with other services.

Rescuetime. To the rescue.

dp-300x70.png

I would like to share some informations about one of the tools I’m using to keep the track of my progress on my ‘Run Pigs Run’ project.

As an introdcution: I think that this description of some ‘productive’ evenings can sound very familiar to many of us.

The story.

You’re reserving the whole evening to work on something. On Your hobby project (‘Dajsiepoznac’ project, maybe?), on Your homework etc. You’ve already refused Your friends to go out, because ‘sorry, I’ve got work to do’. And You start. Editor started, music playlist chosen, coffee ready… You’re really pumped up, this will be a productive evening. Start. It’s going pretty well, until the first problems occur. You’re suddenly not so very enthusiastic and it’s not a nice feeling: it appears that You have to do some extra work to push Your progress further. Maybe extra research is needed, maybe using new programming tool requires to read some documentation, maybe a bug appeared and You even have no idea how to start to fix it. So to forget about all that, You’re switching quickly to Youtube/FB/whatever to ease the stress. After 15 minutes You’re coming back. Working 5 minutes to make some progress… good, You’re feeling better. Maybe a little reward: switching back to entertaining article/video. Back to work. And so on.

Maybe I’ve described this in a bizarre way, but this is how it looked a lot of times in my case. Nowadays I’m more aware, but still similar situations happen. I had always asked myself: how much of this evening was really productive? And many times I was terrified, realizing that probably If I was more focused and more willing to sweat, I would do the same work in about 2 hours. Of course I’m generalizing, but I gained a real enlightenment on how much sugar is in sugar, when I started o use Rescuetime.

The solution.

I don’t think You’ll find a better tool to measure Your productivity. Rescuetime gathers information about which program is currently active and measures time You’ve spend on it. Using RT for a half a year now, I can say it’s a quite accurate tool. Programs and websites are categorized into ‘Very Productive’, ‘Productive’, ‘Neutral’, ‘Distracting’ and ‘Very Distracting’.

In the end of the day You can see (in a form of nice graphs) on what really You’ve spend your time. And it can be quite surprising, when reality appears to be different than what we sometimes define as a ‘productive day’.

Focus

Rescuetime provides also ‘Focus Mode’, which will block any distracting websites in Your browser for some period of time. Popup is displayed, when focus time is over. So You can browse documentation, read tutorials and so on, but e.g social networking sites will be blocked. Omitting this function, ‘Focus Mode’ is just a time measuring tool. But this is a key to a real productivity: just turn on the clock with an attitude ‘I’m really focusing right now’. It can be surprising how much can be done in just 30 minutes of uninterrupted work. It’s a good idea to organize programming session in this way: 30-40 minutes of hard work, break, repeat. And when the popup ‘Focus Session is over’ appears… it’s a really nice feeling. And sometimes focus session is going so well, that we will naturally want to extend it.

Make goals (the best part)

Rescuetime allows to create goals, e.g ‘X hours a day on activities in category Y’. If You want to measure Your time spent on a software development, create category ‘Software Development’ and customize list of programs/websites which are falling into this category. For my current project things in ‘Software Development’ category are: ‘Sublime’, ‘Tiled’, ‘Umlet’, ‘http://127.0.0.1/runpigsrun/’, ‘Emacs’ (for taking notes).

Screenshot-07.03.2016-080655.jpg

And now You can honestly tell Yourself: ‘I’ve spent X hours on a software development’.

written in Emacs with org2blog mode

Dajsiepoznac: about the project.

dp-300x70.png

The reason

I’ve started ‘RunPigsRun’ (probably temporary title) about two months ago, I’m developing it quite regularly. But: a lot work ahead. https://github.com/adamskopl/runpigsrun

Project is written in Javascript, the language I’m still learning (I’ve learnt the basics from here http://eloquentjavascript.net/). I’m using the Phaser framework. I’ve finished one project in this framework, it’s available here: http://skobo.pl/safedrive.

My aim is to:

  • write a not so complicated game
  • it has to be entertaining
  • it has to look nice (I’ll have i big help at this point)
  • it has to be finished entirely

The rules

The gameplay will take place on the levels composed from tiles (10×10). Level is occupied by pigs, wolves, roads, obstacles, traps and other objects. Player can start the game and observe its course. Pigs start to run (hence the game’s title: clever, eh??), wolves start to chase them and so on. Without the intervention, pigs end their existence by drowning/ being caught by wolves/and maybe by other, more spectacular ways. The player’s task is to use available tools and rescue all the pigs by helping them leaving the level. E.g. pigs are running into the water: put a trampoline to make them jump over. Or put a signpost, which will direct pink heroes on the safe path.

Current progress:

Untitled.jpg

I know it does not look appealing, and I don’t care. It’s meaningless to focus on that in the beginning. Gameplay has to be programmed in the first place. Special effects, graphics and other biscuit in the end. I’m using free tilesets downloaded from here.

The style and inspiration

If it’s about the plot… has anyone played ‘Pooyan’? It’s a NES game about shooting wolves falling down holding balloons. It had a marvelous animation with wolf chased by pigs with drums and.. (maybe just check it out https://www.youtube.com/watch?v=AGPOMYpOSfc). Anyway: it’s only about the general atmosphere of the gameplay and the never ending, world wide conflict between pigs and wolves.

nes_pooyan_1.gif

If it’s about the more important part – the mechanics – maybe someone played ‘The Incredible Machine’ (https://www.youtube.com/watch?v=dl1LvFDgCio)? Well, I haven’t. But: I’ve seen my friend playing, when I was something like 9 years old and I still remember the idea. Customize the level with available tools, start game and wait, if configuration, which You’ve chosen, will do the trick.

hqdefault.jpg

written in Emacs with org2blog mode

Hello Dajsiepoznac.

dp-300x70.png

Recently I’ve sent my project “Run Pigs Run” as an entry for polish “Daj Się Poznać” (“Get Yourself To Know”) contest, organized by Maciek Aniserowicz. It has already over 200 registered projects. Long story short: as a participator I have to:

  • work regularly on my project for about three months, counting from the beginning of march
  • write at least two posts weekly about progress/thoughts/programming quirks connected with my work on a project

I’m very thrilled about the idea, hope to stick to the plan.

written in Emacs with org2blog mode

Hello reference.

Switching daily from C++ (day work) to JS (hobby project) results in happily careless programming. I’m so thrilled with duck typing, that in some functions it’s seems to be obvious, that passed object argument is a reference and yet, when I’m writing function using a reference only to check something, sometimes I’m forgetting that I’m performing an operation on a “living being”:

TilesManager.prototype.getAdjacent = function(gamePos, direction) {
	switch (direction) {
		case MovementDirections.U:
			gamePos[1]--;
			break;
		case MovementDirections.R:
			gamePos[0]++;
			break;
		case MovementDirections.D:
			gamePos[1]++;
			break;
		case MovementDirections.L:
			gamePos[0]--;
			break;
	}
	return this.get(gamePos[0], gamePos[1]);
}

gamePos modified outside. A moment ago function was receiving two numbers (not objects) posX, posY and everything was a-ok (pass by value).

Ok, “let’s make gamePos uppercase (ergo suggest DON’T F TOUCH THIS), make a copy at the beginning and use it instead:

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = GAME_POS;
	switch (direction) {
		case MovementDirections.U:
			gamePos[1]--;
			break;

No. Still having a reference: the gamePos IS the GAME_POS. So let’s make a copy. Stackoverflow to the rescue.

As a js beginner I’m surprised: there is no ‘proper’ way to clone objects. Conclusion from the Stack (I’ve packed solution into a function):

function cloneProperties(TO_CLONE) {
	return JSON.parse(JSON.stringify(TO_CLONE));
}

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = cloneProperties(GAME_POS);

Only properties copied, no functions. Will do. Phew. Valuable lesson.

SafeDrive project

A project written in Javascript with a Phaser framework (http://http://phaser.io/).
A presentation is showing dangerous/illegal traffic situation according to the Polish traffic law.

Project is published here: http://skobo.pl/safedrive

Source code: https://github.com/adamskopl/safeDrive

All graphics by Anna Skobodzińska (http://anna.skobo.pl, anna@skobo.pl).

Nothing more to add : ).
Just start clicking.

(it’s best to test it here): http://skobo.pl/safedrive

Cubicforest: progress report and gameplay rules.

A little report on my work on Cubicforest.

Unfortunately from the beginning of October my life was completely upside down to the end of December and I couldn’t find time and energy for continuing the project. But I will start new commits soon.

Last time I was working on levels resolver. Being surprised by the number of combinations of the possible game courses, I’ve realized, that a class solving levels is necessary.

Let’s say we have a simple level:

cubic_example.png

The rules of Cubicforest are as follows:

  1. Player is moving to any accessible tile, having 3 points of movement. Player can end its movement with building an item.
  2. After player the enemy’s movement is taking place (3 points of movement also). It’s AI is simple to pain: every enemy, one after one, is moving to end on a tile nearest to the nearest hero.
  3. Player loses if enemy ends its movement on a Player’s tile and wins if every Player’s character has ended movement on a Portal item (which has to be built by a player).

Getting back to the example. Player can end movement by putting one of 2 items or none of them. So the combinations for turns are:

  1. Player’s first turn: player can move on 7 tiles (including the one he’s starting from). He can also put items, so it gives 21 choices on a first turn (7 tiles to move, plus we can put on every tile an item – 7 + 7*2 choices).
  2. Enemy’s first turn: Enemy can move 3 tiles, so if player moved in a first turn more than 2 tiles away, he will loose. Otherwise the game continues.
  3. Assuming that player has not lost, the number of possible choices in a player’s first turn shrinks to 3 fields, so with items we have 3 + 3*2 = 9 choices. Player places a trap, so level after enemies movement could look like this:

    cubic_example_turn2.png

  4. Now if player wants to live, he has to move somewhere else. In the next turn enemy will follow its pray, and he will meet a trap and disappear. Player has 3 fields where he can move, plus he can put a portal item (which gives him a victory). So: 6 choices.

With this simple example we can see, that coming up with level riddles is a complicated task, because of the number of available choices in every turn. In above example in first turn player has 9 valid choices, and then 6, or 15 or another number, depending on chosen field and item options. So it gives (very approximately) 54 choices in only two turns. And this is a very simple level, with only 1 player character and one enemy.

Conclusion: testing Cubicforest levels it’s very time consuming. It’s better to be willing to sweat and program a tool, which will check if it’s event possible to win designed level.

Having 60% of the resolver done, I’ve used Memento design pattern, to remember level’s every possible objects combinations and to recover any game’s state. In this way Resolver class is looking for every possible combination of player’s moves, but only to some level. I want maps, which can be solved in a reasonable number of turns.

Little demonstration of the current version with commentary: