Ninja Game


Welcome to your first JavaScript game! Coding is a LOT of fun! In the world of code, we can build anything we imagine, there is truly no limits within code. This game will offer you a chance to build something with our help, to get you started, and help you see the patterns of programming. Remember, it all derives from variables, functions, loops and arrays, for now, we will be using variables and functions.

For this game, we will use variables and functions to move a Ninja on our screen. It's important to keep it simple initially, so we will supply you with some of the code, build it in front of you in the meanwhile, and give you the opportunity to finish the code yourself. After your done, you can re-create this by coding along with me. After a couple of repetitions, you'll be able to build this on your own with little to no looking at the current given code!

Javascript Basics

A browser has a built in javascript interpreter where we can run javascript to tell the browser what to do! For example, let's create the following file called ninja.html where we'll be adding simple html, css, and javascript. For this assignment, you can follow this link and download a pre-made folder with the index.html file as well as the images. You can do this by clicking here.

 


<html>
    <body>
        <div id='background'>
            <div id='character' style='position:absolute; top:100px; left:450px; background-image: url("img/down1.png"); width:59px; height:86px;'></div>
        </div>
        <script type="text/javascript">
            var leftValue = 450, topValue = 100;
            function update(){
                document.getElementById("character").style.left = leftValue+"px";
                document.getElementById("character").style.top = topValue+"px";
            }
            document.onkeydown = function(e) {
                console.log('e: ', e); 
                console.log('e.keyCode: ', e.keyCode);
                if (e.keyCode == 37) { // LEFT
                    leftValue = leftValue - 10;
                }
                else if (e.keyCode == 39) { // RIGHT
                    leftValue = leftValue + 10;         
                }
                else if (e.keyCode == 40) { // DOWN
                    topValue = topValue + 10;
                }
                // ...
                
                update();
            }
        </script>
    </body>
</html>