Building a Reactions Tester Game with JavaScript

Preamble

I want to do another walk through of some more code, in which I’ve learned to create a basic game powered by JavaScript. Because not only did I follow video tutorials to write code alongside what I was being taught, but I was encouraged to attempt to solve problems myself through in tutorial challenges before the instructor showed me his solution.

I did okay! Sometimes I got it right, sometimes I didn’t quite do another and sometimes I overcomplicated things for myself when I needn’t have. It makes me feel that although I’m improving, I’m still learning to engage the brain and what the where’s of how to solve these problems…. But I’m still not getting it quite right, which is some ways is disheartening but in others encouraging.

When I say these things about my skills, I don’t say them to undersell myself or put myself down. It’s a sign of where I’m at. It’s a sign of how many brain works. I’m at the stage where I look at code and understand what it takes to make a fairly bog standard Javascript game.. but still looking at the heavens when I’m sat trying to write it. I feel like I’m improving all the time the more hours I put in.

So that end it’s time for another code walkthrough, the goal of which is consolidate what I’ve learned and hopefully help others learn something new too.

The code by the way is based on that taught on the Udemy Complete Web Developer course. It’s a basic reactions tester game. There are probably a few different wayts to approach the problem. I did mine a bit differently to what was demonstrated and here it is below.

Reactions Game Code.

function getRandomColor() {
var letters = “0123456789ABCDEF”.split(”);
var color = “#”;
for (var i=0; i<6; i++) {
color+= letters[Math.round(Math.random()*15)];
}

Using the split function of JavaScript, a variable is defined that holds a group of numbers in which any one of those values is returned in a single character.

The hash character for a hexadecimal colour code is then assigned as a string value.

Then in the for loop the random letters and numbers are added one by one until a valid hexadecimal character is created. It is then called any number of times when the box is clicked. one different colour for each time it is clicked.

var clickedTime;
var createdTime;
var reactionTime;

The game needs 3 variables. One of these will be a variable for the time the button is clicked, to store a value for the time a new button appears and one to record the reaction time which is the difference in time from the createdTime to the reactionTime. They’re assigned in what’s called global scope, which means it’s available to the whole script and not a single function.

document.getElementById(“box”).style.display=”none”;

function makeBox() {

setTimeout(function() {

if(Math.random()>0.5) {

document.getElementById(“box”).style.borderRadius=”100px”;
}

else {
document.getElementById(“box”).style.borderRadius=”0px”;
}

The first statement at the top of this section, grabs the element by its ID and uses a JavaScript format of CSS to change the style. I could have done it by just applying the default CSS style but because I could, I decided to do the job in JavaScript. To grab the value, it’s done as a string literal rather than a keyword value that you’d use in a normal CSS statement.

Next, a function called make box is defined. Nested directly inside is another function called set timeout in which a number of tasks are performed

var top = Math.random();
top=top*300;

var left = Math.random();
left=left*300;
document.getElementById(“box”).style.top=top+”px”;
document.getElementById(“box”).style.left=left+”px”;

By storing a number between 0 and 1 and multiplying this value by 100 we can get a random position. A position for its top and left CSS position each time the function is called.

JavaScript knows it is looking to use a CSS property because it is defined by 2 “getter” statements applied to the #box element with a “px” string added to the end which lets the script know which identifier is being used.

document.getElementById(“box”).style.backgroundColor=getRandomColor();

document.getElementById(“box”).style.display=”block”;

createdTime=Date.now();

}, Math.random()*5000);

}

First of all this shows us another way of making a function call, selecting the Element as usual by its ID name, and then assigns it to the function (getRandomColor) that selects a random background color for each time the box appears.

document.getElementById(“box”).style.display=”block”; Simply changes the display style of the element to clock, making sure the box appear for each guess.

The last statement sets a random delay time before the function executes, which gives the game its real value as a game. That can appear in anything from 0 to 5 seconds.

document.getElementById(“box”).onclick=function() {
clickedTime=Date.now();

reactionTime = (clickedTime-createdTime)/1000;

//alert(“You did it in ” + reactionTime + ” seconds!”);
document.getElementById(“box”).style.display=”none”;

document.getElementById(“time”).innerHTML=reactionTime+”s”;

makeBox();

This is where the bread and butter of the program happens. At the click of the button (s lot happens by clocking this button, calculations are made and elements are modified to feedback to the user how much time has passed from the appearance of the box to the click of the button.

makeBox();

The function is then called inside and outside the function meaning that the box appears again and again and again, until the user has enough.

complete code

I owe the knowledge I gained to the teaching of the Udemy Web Developer course.

__________________________________

function getRandomColor() {
var letters = “0123456789ABCDEF”.split(”);
var color = “#”;
for (var i=0; i<6; i++) {
color+= letters[Math.round(Math.random()*15)];
}

return color;
}

var clickedTime;
var createdTime;
var reactionTime;
document.getElementById(“box”).style.display=”none”;

function makeBox() {

setTimeout(function() {

if(Math.random()>0.5) {

document.getElementById(“box”).style.borderRadius=”100px”;
}

else {
document.getElementById(“box”).style.borderRadius=”0px”;
}

var top = Math.random();
top=top*300;

var left = Math.random();
left=left*300;

document.getElementById(“box”).style.top=top+”px”;
document.getElementById(“box”).style.left=left+”px”;

document.getElementById(“box”).style.backgroundColor=getRandomColor();

document.getElementById(“box”).style.display=”block”;

createdTime=Date.now();

}, Math.random()*5000);

}

document.getElementById(“box”).onclick=function() {

clickedTime=Date.now();

reactionTime = (clickedTime-createdTime)/1000;

//alert(“You did it in ” + reactionTime + ” seconds!”);
document.getElementById(“box”).style.display=”none”;

document.getElementById(“time”).innerHTML=reactionTime+”s”;

makeBox();

}

makeBox();

Advertisements

A commentary on coding and understanding while loops

A Short commentary on coding

Coding has been given a lot more recognition in recent years as an important skill in modern life. So much so, that young children are now being given lessons in writing basic computer code. As a web designer I think this is a very exciting thing.

When I was at School, IT was an important part of the curriculum but at the heart was not learning to make computers do what we want, but using their tools to perform ICT, like making databases and doing Desk Top Publishing. There was only one computer I was aware of that had a copy of Microsoft Visual Basic, the building blocks of Windows development second I believe to Java.

Further to this a video advert for Treehouse opened with the line

"understanding Technology and being able to control it is now as fundamental as being able to read and write" Ryan Carson Treehouse

and I’ve been thinking on it ever since. I think it’s becoming in increasingly important in this modern digital age.

The web has never been more widely used, more widely accessed. people are stuck to a screen more and more using phones to browse the web. using Java to operate every day machinery, using php on web pages, Javascript to make them interactive and seeing CSS on every web page they see.

It’s also fun!!! Learning to control it is a lot of fun. That said, sometimes I wonder if the School classroom, even the primary school classroom is the place to learn computer code. Which sounds like an incredible U-turn. I remain excited by the fact that more and more people are being exposed to the world of computer coding. But I don’t think it suits everybody.

Everything I’ve learned about code, has been aided by what I’ve learned at college or university. I don’t underestimate the impact a university education had on my education but the way I think of it is like this; University gave me the preparation I needed to learn proper design and what it actually takes to code. But what I’ve learned and am learning about coding hasn’t come from mainstream learning, but from websites like Udemy, Codecadamy and Treehouse.

By all means, teach coding in schools but self-directed learning should be the first and foremost learning curve.

Code Walkthrough:

Now, let’s move on to a more specific topic. While loops.

I’ve given Treehouse the kick for a little while. Just a little while, and I’ve been doing a one-off, lifetime access Udemy course.

There’s 2 things about JS I’m struggling to remember in my muscle memory. The Applying getElementById to a function properly

document.getElementById("guess").onclick=function() {

using getElememtById and combining it with a function is a technique i really should pick up. I’ve practiced for a past couple of days but my muscle memory hasn’t ever picked up quite right.

The while loop has always been a tricky concept with me. Because I don’t really use it as much as a for loop. The while loops I write tend to crash the web browsers I run them in.

This example below is a great example of the use of a while loop because it tests for conditions in a loop that could break out at any time.

1 while(gotit==false) {
2 x=Math.random();
3 
4 x=6*x;
5 
6 x=Math.floor(x);
7 
8 if(document.getElementById("myNumber").value==x) {
9 
10 gotit=true;
11 } else {
12 guesses++; 
13 }
14 
15 }
16 
17 alert("Got it! It was a "+x+". It only took me "+guesses+"guesses!");
18 }

The Syntax is quite easy to understand.

while() {}

A condition, after the while keyword, that tests the value of a variable with actions undertaken as long as the variable does have the given value, in this case it’s a boolean variable. Remember a boolean variable is a variable that can only have 2 values, true and false.

Lines 2 to 4 do things with a particular variable. It generates a random number, using the Math object between 1 and 6, because x has been set to be multiplied by that number.

But like any loop, the syntax is not any good without a means of breaking free from the loop; that is specify what to do when the test condition is met. To do this we use an if statement.

This requires another condition to test, just as we have done with the while loop. The sorts of things you can test in an if statement make them very powerful indeed.

The condition for the if statement being tested is document.getElementById(“myNumber”).value==x, which is grabbing a particular element so it grabs data from the input box and then tests that the value in the x variable is the same as what has been typed in the text box. It could be any value that the user types in but it is expecting a number.

Also, like the loop condition, it’s important to understand how a condition is tested. Typically a property is tested against a value with 2 or 3 equal signs like this.

document.getElementById("myNumber").value==x

So, a statement in which a value is assigned can typically be tested to see if that statement still has the same value. If it does, the statement is a true statement. If not, the value is false.

So if on the occasion that the value the script is the same as the value typed in the input box, then the boolean value is set to true, thereby breaking out of the loop. and reaching the ned of the script. The script adds a guess to the guesses variable the final answer has been reached.

What I’m hoping to take away from this post is an understanding of conditions and loops and the kinds of expressions that can be tested in their use.

Solving the conundrum of a jQuery powered notification bar

I’ve had a puzzle to solve over the past week.  The puzzle… no, the mystery of the otherwise simple to implement, notification bar (a piece of code that goes on the top of any page of any website) good for announcements and notices, that sort of thing.

Very easy to set up. Very hard to get wrong. Well… not as hard as you might think.  It’s very hard to integrate any new CSS code and set of HTML elements into pages with a fully fledged website with its own styles, inheritance and behaviours.  The bulk of it will work, but then you also have to deal with matters of style inheritance.  Because in CSS, elements take on the styles of their parent elements.

The problem in question comes from code in the following tutorial   http://www.akshitsethi.me/how-to-create-simple-notifications-bar-for-your-website/

I won’t copy and paste the code in here as it’s already available on the above page. Give the page a like or a tweet so you can see it and maybe implement it on your own pages.

For days (on and off) I looked and scoped this code to its every last detail.  Every piece of code, every element, every style trying to figure out what was going on with the page. Why the page wasn’t displaying it correctly.

Problem 1

The major problem I had was, that contrary to what was happening in the demo, the menu bar appeared, but rather than seeing the button to close the bar, the button to open it, kept appearing.  Clicking it, would make that “open” button disappear so it was clear to me that jQuery was properly linked.  So no problem there.

The solution was really simple. The file needed to make run the cookie or a local computer wasn’t properly linked.  But if I did that, there was still something not quite right. Which links into problem 2.  There seemed to be a grey area.

We’ve established that the jQuery.cookie.js file needed to be linked and this action worked.

It was definitely making a difference.  The close button is present and correct, with maybe a little but more customisation on the width and height styles needed. The whole notification bar disappeared as it was supposed to a. But then, problem 2 comes to light.

Problem 2

Where the devil did the open button get to when the bar is closed?   I cannot you how many hours I spent checking the code, as before; head to toe trying to work out what was wrong with the code.  Then suddenly, I happened to chance a glimpse at it, hidden under my navigation element which has  background colour styled to it.  The little blighter was there all along.

What happened was it was quite far below what’s called the “stacking order” in elements.  It needed a little more DIY work on my part in order to properly integrate it into my website.  To manipulate the stacking order and make sure the “open” button is always visible. I simply add this to the appropriate style.

z-index: 1;

Eureka!.  The notification bar is now completely visible and functional.  Click open to bring back the bar and push the rest of the page content below the appropriate distance.

Problem 3

Just a couple of different customisation issues to get over and I was all set.

We don’t need so much space on the width and height of the closeButton area so we set it to only 17px of width and height.

#hello_bar .close a#closeButton {
text-indent: -9999px;
display: block;
float: left;
width: 17px;
height: 17px;

snip

But the button is still inheriting styles from its parent element. Namely the padding of anchor elements in another CSS file. So to put this right it was a simple case of

padding: 0 0 0 0;

So all that has happened is not a case of code that is out of date, or jQuery now deprecated and no longer useful. But it was a simple case of making sure the code snippet was completely independent of any inherited style which causes bugs and making sure those bugs were cleared out.

I also made a start on making sure it looked okay on mobile devices and I’ve made progress on that too. But that is another story 🙂