Community   Maps   Forum   Mail   Ladders   Clans   Recent Games
Sign In | Sign Up
<< Back to Programming Forum   

Posts 1 - 16 of 16   
CLOT php+javascript for non programmers: 4/7/2013 14:35:49

Level 59
This thread is intended for folks who don't know how to program but really want to learn.

It comes as follow up to my other thread:

Some folks have been asking me how they can get started coding in general and help out with CLOT development in particular. So i decided to create this thread about it to serve as a guide and answer any questions.

Feel free to ask any seemingly stupid questions, no one is born knowing everything and it's likely answering your question publically will help others reading this thread later on.

A little about me: i'm MSc informatics engineer, i'm not a genius coder, no one ever is really. Been coding since i was 5. After i got my masters i did some academic research work, got tired of it so i worked 9 to 19 on a company, got tired of it. And nowdays i'm doing freelance and working on my own projects.

On about CLOT: i didn't like Fizzer's platform which unknownsoldier had been working on, my main points against it was that i am rusty in python, never touched django and dislike google's app engine limitations. That doesn't mean you can't do great things with this combo. I was just lazy to learn new frameworks at this point and prefered to try my own version more objective oriented. Which turned out to be this:

So if you want to learn how to program to use CLOT you have two choices at this point: learn python + django + app engine or learn php+javascript on this thread.

I'm assuming you know absolutely nothing about programming. If you do my explanations might sound somewhat simplistic or not really following the best practices. That's fine. Feel free to comment anyways or fork my code on github and fix it up.

I'm a big supporter of KISS guidelines (keep it simple stupid) and making it work first and turning it into a framework later. That means i code to achieve something on a working state which id minimally documented to be useful for later repurposing, if when it might be needed.

Lesson number 1: Code fright

If you're ever going to learn how to code you must not be afraid of getting your hands dirty.

Reading a book or some tutorials labelled 'for dummies' is quite useful to learn the basics but you are only going to make real progress when you run into problems and interiorize problem solving by actually writing, running and rewriting code.

That means several things:
1) get used to googling for your own answers before asking questions
2) get used to search documentation fast
3) get used to asking yourself why something doesn't work
4) get used to testing your hypotheses

If something doesn't work you need to ask yourself: Why? And if you don't know the answer immediatly you need to figure out a set of smaller questions on why it might not be working and test those hypotheses. Don't sit around and wait for the answer, think of the most likely reason, test it and repeat the process. For example if a lightbulb isn't lightning when you flick the switch it could be due to several things: the filament might have wore itself up, the lamp could be disconnect from the electricity, the electricity socket may be broken, or maybe the whole electricity board is down. It doesn't so much matter as to why that certain thing might have happened that caused the problem, your main concearn should be discovering why it doesn't work now. Once you figure that part out then you can think on how to prevent it from happening again. In this example you can check if other appliances have electricity, if other lightbulbs work on this lamp, if the lamp works in another electricity socket, etc. And then eventually you will realize it's the lamp itself that is broken and conclude it might be very likely that a couple days ago your visiting cousin broke the lamp and placed it back without telling anyone.

This is the most critical skill for becoming a decent programmer. There are other things important, but this one is critical: if you don't have initiative on critical thinking towards problem solving you will just be staring at a problem and give up.

Luckily for you, if you're reading this it means you probably play warlight somewhat regularly, so you clearly already know the basics of dealing with frustration, critical thinking and problem solving. Hooray for that! So just keep in your mind that when coding you need to be doing that constantly for every step you take.

Lesson number 2: Getting your environment setup. \o/

PHP is a server side scripting language. It's embbeded as a module into the Apache server.

Quickly explain server-client logic now:
You have two programs who want to talk with each other, the server is the one sitting sad and alone in a corner waiting for a client to poke him with a request.

In our case the server will be a service running on a machine (the apache thing i was mentioning before) and the client will be your web-browser. When you enter an address on your browser it looks up the server with that name and asks him for it's contents. In warlight's case it gives you back this amazing game.

If you write http://localhost in the browser window it will try to communicate with your own machine. So if you have a web server running (like apache) you will get a page back. And if you don't it will just tell you the page doesn't exist!

So what you need is to install Apache with PHP support. If you're on mac it comes installed by default, you just need to enable it on the System Preferences / Sharing options. If you're on windows you need to install a package like WAMP:

You can find some tutorials, tests and troubleshooting pages on getting server with php working on the internets.

So homework #1: get that server installed!

Once you do you'll have a folder somewhere on your harddrive called /www/ or /Sites/ and if your webserver service is running and your firewall isn't blocking anything you can type on your browser for your localhost and access the pages listed there.

If you now write a helloword.php textfile with
<?php echo 'Hello World!'; ?>
And place it on the webserver folder, you should be able to call http://localhost/helloworld.php and get your message served in the browser

Next lesson: variables and loops
CLOT php+javascript for non programmers: 4/7/2013 18:29:16

Level 59
Before lesson number 3 i should clarify you'll need a decent text editor to code in php. And by decent i mean notepad and microsoft word won't do.

If you're on windows i recommend notepad++, if you're on mac you have textwrangler or textmate. If you're on Linux you already know all this stuff and that's why i'm ignoring you somewhat, and if you're not then try out emacs or vim.

Lesson 3: Variables and loops

I could write you a longer and more comprehensive introduction to programming languages and PHP in particular but i'll leave that for the books you'll read later on.

This is what you need to know at this point in time:

In PHP every word starting with a $ is a variable.
Variables are useful to store data.

Practical example:
$variable = 'hello world';

If you execute this in PHP it means you'll then have a variable called $variable containing the string Hello world, without the apostrophe (also called single-quote).

To print it on screen you need to use the echo command:
echo $variable;

Every command line must end with ;
Failure to do so will send you to a bad place riddled with problems.
You don't want that.

Apostrophes delimit strings. Double quotes work similar to apostrophes delimiting a string but slightly different. For now just know that it's better you are consistent, if you open a string with a single quote, use a single quote to close it.

You can manipulate variables with operators. For example the dot operator concatenates strings:
$hello = 'Hello';
$world = 'world';
echo $hello.' '.$world;

Means you'll print to screen Hello World.

If you want to use special characters like single quotes inside a variable you need to escape it, you do this by using a backslash:

echo 'Hello Wayne\'s World!';

Will give you Hello Wayne's World.
To get a single backslash on a string you type two consecutive backslashes.

Now you know how to concatenate variables! Awesomesauce!

variables can also include other types of values like numbers. The plus operator adds two numbers.
$number_one = 12;
$number_two = 2;
echo $number_one+$number_two;

Will print you 14.

Lesson 4: Loops

The most important loop you need to know is the for loop. Here is an example:

$maxnumber = 12;
for ($i = 0; $i < $maxnumber; $i++) {
echo $i.'<br>';

This will print you a count from 0 to 12.

The for instruction takes 3 arguments seperated by ; and executes the code block that follows it.

The curlybraces delimitate a block of code.

So what the for loop does is the following:
- First and always executes the first argument, in this case $i = 0
- Then checks the condition of the second argument $i < $maxnumber and if it's true execute the codeblock.
- At the end of the codeblock it will execute the third argument $i++ and then repeat the second step.

In practical terms the code is equivalent to
$maxnumber = 12;
$i = 0;
for (; $i < $maxnumber; ) {
echo $i.'<br>';

The loop will repeat until the second argument is false, in our case, when the $i variable increases enough times to be equal (and not lower) then $maxnumber

If you're wondering:
is the same as writing
$i = $i + 1;

++ is called the incremental operator, because it increments. :)

So homework #2: Write a for loop that prints a downcount instead of an upcount.

Next lessons: if statements, functions and arrays.
CLOT php+javascript for non programmers: 4/9/2013 10:51:26

Level 59
Lesson 5: If statements

If statements look something like this:

if ($mypants == 'on_fire') {
echo 'help help, my pants are on fire<br>';
} else {
echo 'wazzup?<br>';
echo 'stay calm and carry on<br>';

So the if statement has an argument and if that argument is true it will execute the block of code that follows. Optionally you can include an else part to the if statement, which only executes when the argument is false.

So in this case, if you had previously defined before the if statement that
$mypants = 'on_fire';
the code would print you out a cry for help and a reassurence to stay calm and carry on.

if the code has no prior definition of $mypants being equal to 'on_fire', either because you never set it, or set it to something else like
$mypants = 'are_wet';
the code would print you out a generic greeting and a reassurence to stay calm and carry on.

you can use any type of comparison on the if statement argument, you can check if a variable is even defined:
if ($mypants) echo 'i have pants!!!';

you can check if something is bigger or smaller:
if ($my_pants_pockets < 2) echo 'i need more pockets!';

a world of fun!

Lesson 6: Functions

you can define a function like so:
function myFunctionName() {
echo 'OMFG i\'m beeing called!';

and then run it anywhere else down the code by calling it

they are useful if you want to do something with multiple lines of code more then once. so instead of copy pasting the block of code you can just wrap it into a function and then just call the function.

you can also call a function with arguments and have them return you a value. for example:

function helloWorld($name) {
return 'Hello world from '.$name;

echo helloWorld('Jake');

functions also allow you to organize your code better. when you have very large blocks of code it's easy to get lost in where each starts and ends, making it quite unreadable and thus very difficult to debug or alter. having functions to do specific jobs enables you to focus on a section of an algorythm to make sure that it's working ok and also test it seperately from the remaining logic. for example:

function putWaterOnPants() {
if ($near_a_river == true) {
} else {

if ($my_pants == 'on_fire') {

also the cool thing with functions is that the language already comes with quite a few:

For example these are all the functions related to handling and manipulating Strings:

It takes time to remember them all, you mostly won't even know most of them exist until you have a specific problem and start googling for a way to solve it only to find examples which use some of those functions.

This might also be a good opportunity to mention that if you're learning php the online manual is your best friend ever and you should consult it heavily for references:

Most programming questions are usually answered with RTFM (read the fucking manual) so if you want to program anything you really should read it.

Next lessons: arrays
CLOT php+javascript for non programmers: 4/9/2013 16:55:31

Frankdeslimste • apex 
Level 58
Nice work PS!
CLOT php+javascript for non programmers: 4/9/2013 17:05:39

Luxis • apex 
Level 51
I believe everyone agrees with Frank, just don't want to clutter the thread :)
CLOT php+javascript for non programmers: 4/9/2013 17:18:51

Level 59
to tell you the truth i would rather see it clutter with questions of folks trying things out and needing some pointers.

but i guess i'll keep doing the lessons until the end regardless. just don't have a clue if i'm getting too hardcore too fast or not. in eithercase, i'm just explaining the basics, you'll still need to read atleast one book on how to program and get used to consult the manual if you want to be able to actually do anything with clot by the end of these lessons.

my plan right now is to go through the basics of php, which we are half way through by now, then explain basics of html and css, then why you actually need a client server separation, then some javascript and finally explain my clot code in detail so folks who might want to fiddle with it have a better understanding of what it's currently doing.

i'll probably take the opportunity more towards the end to either port fizzer's CLOT completely or publically build another ladder/tournament example with slightly more structured code than the current 3v3 random asia ladder that is live now.
CLOT php+javascript for non programmers: 4/9/2013 17:57:45

Frankdeslimste • apex 
Level 58
I just wanted to make sure he knew at least someone liked it. It can get discouraging if nobody even reacts and I want him to continue this.

I'm familiar with the basics, but it is nice to get some refreshing since it been quite a while since I last used PHP.
CLOT php+javascript for non programmers: 4/9/2013 20:58:55

Level 55
Yeah this is interesting. I'll never bother to learn more than this, but it is interesting to read how coding works. I have a new Europe 3v3 template I'd enjoy for a random teammate 3v3 ladder: random cities, 15 wastelands of 2 armies. Europe has 32 bonuses, so in an ideal world of non-overlapping cities and wastelands and equally distributed wastelands, this template is almost a 75% cities, 25% warlords hybrid. Any chance a ladder could be made with this? Or do I have to win your first CLOT to make it happen?
CLOT php+javascript for non programmers: 4/9/2013 21:40:43

Level 59
Qi: well, it could easily be setup, just a matter of changing one line replacing the template id, but i think it would be fairer to have just one of those type of ladders running and have the winner decide. Not sure how to close a season yet, i was thinking letting it run for a month or so, but maybe it'll be better ending whenever someone reaches 10 wins or something. anyways, that's a discussion for the other thread. :)
CLOT php+javascript for non programmers: 4/9/2013 22:18:06

Level 59
Lesson 7: Arrays

Arrays are essentialy data structures for variables.

Following the previous examples imagine you want to describe some pants.
This is how you could initialize the array:
$pants = array( 'price' => 50, 'color' => 'blue', 'owner' => 'me');

Then if you want to access the price you just call the corresponding key
echo 'i paid '.$pants['price'].' bucks for these pants!';

You can even have arrays of arrays.
$closet = array();
array_push($closet, $pants);
echo 'i love my '.$closet[0]['color'].' pants!';

array_push is a function that allows you to push a value into an array. the first argument is the array you want to push into, the second is the value you want to push. in this case we are pushing our $pants into the recently created $closet.

arrays can be indexed by both number or a key.
if you know your array only has number indexes you can check all the members of the array like so:

for ($i=0; $i<$closet.count(); $i++) {

count is a function that exists on all variable object arrays and returns the number of indexes the array has.
var_dump is a special function that lists all the content of a variable/object, it's mostly useful to check all the contents of the arrays fast.

if your array is not indexed by numbers, you can still check all of it's members by key:
foreach ($pants as $key => $value) {
echo 'looking at '.$key.' key<br>';
if ($key == 'owner') echo 'these pants belong to '.$pants[$key].'<br>';

when you want to not only read but also write back to a value of an array inside a foreach loop you need to call it by reference. you do this by adding a & to the variable:
foreach ($pants as $key => &$value) {
if ($key == 'price') {
$value = $value*0.80;
echo 'these pants were actually on sale! 20% off!';

this is needed because when you call the foreach loop it actually clones the contents of the array. so if you are not telling it to affect the original value explicitly, then when the loop ends and the clone is cleaned from memory your original will not be altered and you'll be left wondering what the hell is going on.
CLOT php+javascript for non programmers: 4/11/2013 22:52:41

Level 59
Lesson 8: html

If you followed the previous examples you might have noticed some of the example echo commands i typed had a trailing <br> in it.

This is because of html. php outputs html.
All pages on the internet are html actually.
html is a standard in xml format.

You can look at examples on any page you load with your browser. Most browsers allow you to snoop at the source of the page loaded. On Firefox you go to Tools > Web Developer > View Source on Firefox. On Chrome you go to View > Developer > View Source. On Opera and Safari i'm too lazy to check right now but there are similar menus. I think on Safari you have to enable the view of developer bar in the settings first actually. If instead you are using Internet Explorer, i'm sorry to be the one to break it to you but you really should be using one of the other three, i could write you an essay on why but tl;dr: because it sucks.

Anyways, if you look at the html of any page you'll notice it's just a fancy text file. The basic html looks like
<title>Some title</title>
<p>a paragraph</p>
<div>followed by a div!</div>

The little < and > things are called tags. They don't get get rendered by the browser, they only serve the browser meta data on how to render the page. And an important thing to know about html tags is that all tags should theoretically be closed. When all tags are closed we have a properly formated HTML and everyone is happy. When we don't, the gods might get angry and the browsers will just try to guess how to render it in the best way.

So actually if you write an html page with just:

It will still load and show you the Wazzzup message. Even though the error console might complain there is no html and header and body tags and that your p tag is opened but never closed. But hey, it works.

So, about those <br>'s: <br> stands for break. It's the tag you use when you want to say, this text here, at this exact point should do a line break right about now. So a page with:
Bloody hell<br>Dead Piggy looks so sexy playing 3v3

Will actually be rendered as:
Blood Hell
Dead Piggy looks so sexy playing 3v3

I know what you're thinking now: "The validity of the claim is left for Gui to decide." But what you should actually be asking me is: "but you just said all tags should be closed and you're not closing the <br>!!1"

Yes, quite right, br is a special tag, since it typically contains no content the standard states that all browsers should assume it's automatically closed. Even though to make it proper validated html you should actually type it <br /> which is a shortform to <br></br>. In practical terms just typing <br> works just as fine.

And thus, when i post things via php to a page i use the echo'ing of <br> to make sure the page has line breaks.

Next lesson: random important php stuff that i might be forgetting about and css
CLOT php+javascript for non programmers: 4/12/2013 12:55:11

Level 59
Lesson 9: CSS

CSS is another standard, tightly coupled with HTML.

As i mentioned on the previous lesson HTML is all about tags and using them to structure your content. In the old days of HTML you would have arguments on the tags to give extra metadata information to the browser. Some are still heavily used:

For example the anchor tag is mostly used nowdays with the href argument:
<a href="">link to warlight</a>

And when you're adding images to the document you can define things like the source, width and height:
<img src="" width="100px" height="100px" />

But most HTML5 good practices (the 5 stands for the latest cutting edge version of the standard) tells you that you should define your tags with classes and use a CSS file to describe their styles.

<div class="style1">this block of text is in style1</div>
<div class="style2">this block of text is in style2</div>
<div>this block of text has no style</div>

you can also refer tags by their id, for example:
<div id="gui_dissing">Gui sucks and so do all his alts!</div>

So you are assigning classes and id's to the tags, now you need to style them, and for that you need to make sure your html page includes a css/stylesheet section or is linking to a css file. You can do the later by including such a line on the <head> portion of your html:
<link rel="STYLESHEET" type="text/css" href="client.css" />

Your .css file is a specially arranged text file, you can take a look at it on any browser using the same view source tool as previously. It contains some rules structured like this:
.style1 {
text-align: center;
color: blue;
margin: 2em;
.style2 {
text-align: left;
color: red;
#gui_dissing {
text-align: right;
color: pink;

In fact you could inline the style in the html tags with the style argument:
<div style="text-align: center; color: green;">a green div</div>

But the point of using CSS files is to seperate the content from the cosmetic enhancements. So whenever possible you should assign a class to your tags and style them on the CSS.

CSS rules are plenty, like with some HTML tags, only some of them only work properly on all browsers. There are sites dedicated to informing you what CSS3 (3 is the latest version of the standard) work on what browsers. Plenty of tutorials around aswell, not to mention every single site on the web has it's CSS exposed, so you can also learn by looking at the source of a site you find pretty.

That's it for the basics of html and css. Next lessons back to php for some info on json vs databases, file reading and writing, and then eventually javascript. Feel free to ask questions.
CLOT php+javascript for non programmers: 4/12/2013 22:45:18

Level 59
Lesson 10: JSON and databases

As mentioned before PHP is a script language running on the server side. When you call the page on your browser, the server executes the appointed script and returns you the resulting page. If you refresh the page the script will run again. Now imagine that you want to check the status of some pending games.

You have 3 problems:
- First you need to read from somewhere your list of pending games.
- Then you need to query warlight asking about the game.
- Then you need to store the result somewhere.

There are 2 ways to store data with php. The most common is to have a database service running alongside the web server, typically in some form of SQL. An SQL database can contain various tables of data, it handles several things for you like user authentication, privacy, concurrency, filters, performance, indexing.

If you're running a serious project, it's a good thing to have. The only downside of using databases is that it adds an extra layer of complexity, you have to define your tables, users, define queries and wrap your functions to insert and retrieve data, while making sure your page is not vulnerable to sql injection attacks.

For my test project i didn't really feel like i needed that layer of complexity just yet, so instead of accessing a database i store and load the content from a textfile. it's all public information anyways, so there is no problem in having it accessible.

The format i chose to store the data is JSON. It's a text format originally used to represent javascript objects that quickly became used by other programming languages. A JSON validated file looks something like this:
"datetime":"2013\/04\/05 05:02:33",

This JSON formatted string contains 2 objects with keys datetime and players. In PHP you can call the json_decode() function to transform a string into an accessible array.

So if you do:
$decoded = json_decode($jsonstring, true);
echo $decoded['players'][1]['name'];

You will get Grinche printed on your screen.

The nice thing about JSON is how easy we can manipulate it and pass it back and forth between different languages.

Next lesson, client side programming in javascript.
CLOT php+javascript for non programmers: 4/17/2013 03:15:47

Level 59
Lesson 11: server-client

It's healthy to have a clear distinction between what is run on server side and what is run on client side. In layman terms the server side handles data storage, user authentication and operational logic. If you shift any of those to the client side then you are giving the users the power to mess with your data, troll other users or cheat.

Like i mentioned on a previous lesson, the client side on this case is any browser you call the app in. The server side is where you are hosting your server (it can be the same machine).

PHP only works on the server side. So unless you composite the whole html page with php and serve that to the client, you will need to use javascript to do some code on the client side.

When you look at some HTML you might notice some <script> tags, these are typically blocks of javascript code. Almost all the browsers have a javascript engine built in that interprets javascript code and executes it run-time.

As a note, javascript can also be used on server side, with nodejs, but that's not what we'll be using it as in this case. Javascript on client side can be used to manipulate the HTML programatically. This means we can define variables and functions that will alter the content, style and order of the HTML tags, when we do this the browser notices the changes and updates the homepage immediately, so we can use javascript on client side to animate the page or make it interactive. For example we can: load content dynamically from a server, make some drop down menus, do animations when someone clicks on something, etc.

Lesson 12: JavaScript

First of all JavaScript is not Java, they are two different languages.

You can call it JavaScript or Javascript or javascript of JS, it's all pretty much the same. Actually one of them is an early variant, but it's not being used anymore.

Javascript is usually stored on seperate files with the .js extension, these are normal text files that just happen to be javascript code. And you can include them in your HTML file by adding a script tag like so:
<script type="text/javascript" src="myjavascript.js"></script>

Or simply inlining the code inside the tag.

Javascript looks very similar to PHP in some ways. Like in PHP you don't really have to declare variables until you use them. Most people declare them anyways for code readability and distinguishing local from global variables. And you don't actually assign a type to a variable, it gets re-assigned automatically depending on what you give it. In fact, in javascript everything is pretty much a variable, even functions can be cast as variables.

Here is some example javascript code showing the difference between local and global variables:

var whatiam = "leprechaun";

function cutePie() {
var whatiam = "goldfish";
return whatiam;

console.log( 'am i a ' + whatiam + ' or a ' + cutePie() );

console.log prints to your debug console, all browsers have one, you just have to make it visible. alternatively you can use the alert() function to popup a warning box.

There are some minor, but important differences between php and javascript, you will need to read some books and tutorials to get to know them, it's not possible to explain them all in this short lesson.

It's also important to mention that javascript gets interpreted while the page is beeing read, that means if you're including your javascript on your html head and try to access parts of the body, it might not have loaded yet and thus might through you some errors, the common way to avoid this is to call your main execution function as an argument of the body tag:
<body onload="myFunction()">

The browser will recognize the onload argument and once it's done loading call that javascript function for you.

In my CLOT example (eastasia random 3vs3) we use javascript to check on the server and then load the latest .json file with our entire datas tructure of players and games. Then parse that data structure and build the corresponding tables.

That's it for the basic lessons, if anyone has any questions or special requests for enlightenment please post them. Else there is always the internet.
CLOT php+javascript for non programmers: 7/14/2013 17:27:47

Level 56
Ok, I have a question related to this, but maybe not 100% directly. I know PHP and Javascript to a pretty good degree, so I kinda skimmed your posts and may have missed the answer buried somewhere in a lesson.

How do I host this? I mean, where do I put it so that it can be seen, edited, and used? I have my own website, but it's been a while since I've worked with anything more complicated than basic websites. I understand the coding and the links between the pages, but I don't understand where to put it. I know this sounds pretty stupid, I think I'm just missing something simple here. My site is run through Enjin, but that shouldn't be a problem, as I can upload files to it without a problem. If I make the CLOT can I just upload the files and link to the main page of the clot? Is it that simple? Again, I feel dumb posting this but I haven't done this in like 5 years.
CLOT php+javascript for non programmers: 7/15/2013 14:59:35

Level 59
If Enjin supports php with disk write access, yes, just create a folder for your clot and dump the code there. I don't use Enjin, don't know it's hosting restricitons.

Basically you'll need hosting that supports php. Most hosting solutions do. I can recommend bluehost for example, it costs around 40 euros a year and usually includes registry of a domain for a year. There are many other hosting solutions available.
Posts 1 - 16 of 16   

Contact | About WarLight | Play Risk Online | Multiplayer Strategy Game | Challenge Friends, Win Money | Skill Game | Terms of Service