Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

JAVASCRIPT SAMPLES - TIC TAC TOE GAME & DYNAMIC TABLE CREATION IN JSP

Hello Buddies.

It's time to play tic-tac-toe, but this time, not with pen and paper. 
We will create our own page that allows us to play tic-tac-toe and determines the winner.

You can get the complete code here -

https://github.com/namitsharma99/game-tic-tac-toe






So what should we start with?

Here we go -



<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> < !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http - equiv = "Content-Type" content = "text/html; charset=UTF-8" > <!-- Latest compiled and minified CSS --> < link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > <!-- jQuery library --> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" > < /script> <!-- Latest compiled JavaScript --> < script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script> < link rel = "stylesheet" href = "./stylish.css" / > < title > GaMe - BeGiN < /title> < script type = "text/javascript" > function createTable() { document.getElementById("rules") .setAttribute("style", "display: block"); document.getElementById("createT").setAttribute("style", "display: none"); document.getElementById("destroyT").setAttribute("style", "display: block"); var theTable = document.getElementById("myDivTable"); var createdTable = document.createElement("table"); createdTable.setAttribute("class", "whatATable"); createdTable.setAttribute("border", "1"); var tabBody = document.createElement("tbody"); createdTable.appendChild(tabBody); for (var i = 0; i < 3; i++) { var myRow = document.createElement("tr"); tabBody.appendChild(myRow); for (var j = 0; j < 3; j++) { var myCol = document.createElement("td"); myCol.setAttribute("class", "whatACell"); // var myText = document.createTextNode("Cell "+ i + "," + j); // as alternative var myButton = document.createElement("input"); myButton.setAttribute("id", i + "," + j); // myButton.setAttribute("value","Cell "+ i + "," + j); // myCol.appendChild(myText); // as alternative myCol.appendChild(myButton); // myCol.setAttribute("id", i + "," + j); myRow.appendChild(myCol); } } theTable.appendChild(createdTable); } function evaluate() { // alert('hello!'); var a00 = document.getElementById("0,0").value; var a01 = document.getElementById("0,1").value; var a02 = document.getElementById("0,2").value; var a10 = document.getElementById("1,0").value; var a11 = document.getElementById("1,1").value; var a12 = document.getElementById("1,2").value; var a20 = document.getElementById("2,0").value; var a21 = document.getElementById("2,1").value; var a22 = document.getElementById("2,2").value; if ((a00 != '' && a01 != '' && a02 != '' && (a00 == a01 && a01 == a02)) || (a10 != '' && a11 != '' && a12 != '' && (a10 == a11 && a11 == a12)) || (a20 != '' && a21 != '' && a22 != '' && (a20 == a21 && a21 == a22)) || (a00 != '' && a10 != '' && a20 != '' && (a00 == a10 && a10 == a20)) || (a01 != '' && a11 != '' && a21 != '' && (a01 == a11 && a11 == a21)) || (a02 != '' && a12 != '' && a22 != '' && (a02 == a12 && a12 == a22)) || (a00 != '' && a11 != '' && a22 != '' && (a00 == a11 && a11 == a22)) || (a02 != '' && a11 != '' && a20 != '' && (a02 == a11 && a11 == a20)) ) { alert('We have a winner!'); } } $(document).keyup(function (event) { // alert('Handler for .keypress() called. - ' + event.charCode); evaluate(); }); function destroyTable() { location.reload(); } < /script> < /head> < body class = "extraContainer" > < div class = "container" align = "center" > < hr > < button onclick = "createTable()" id = "createT" class = "btn btn-success" > Create Table < /button> < hr > < div id = "rules" style = "display: none" > < h3 > Only X or 0 allowed! < /h3> < /div> < hr > < div id = "myDivTable" > < /div> < hr > < button onclick = "destroyTable()" id = "destroyT" style = "display: none" class = "btn btn-danger" > Destroy Table < /button> < hr > < /div> < /body> < /html>


We have 2 beautiful snippets here, if you could just observe the jsp code.

1. First of all, createTable(). It shows you how to create a table in the jsp dynamically.
   (Sounds useful isn't it. You can use it elsewhere as well)

2. Then comes the evaluate() method, that will evaluate if any valid triplet is created or not with every keypress.

Short and simple, and rest upto you.

I don't say it's the most efficient way, but surely it is an easy way, that along with its implementation will make you comfortable with javascript methods.

Do share you versions of the game or tips to do better coding for the buddies.

Happy Coding!!

JAVASCRIPT SAMPLES - HUNGRY SNAKE

Hello Buddies.

Trying to make a simple snake like game using basic javascript and jquery this time.

The complete code is available here -


https://github.com/namitsharma99/hungrySnake





Here we go -

Logic we need to maintain while coding -

1. Arrow keys will redirect the snake into desired direction, and snake keeps on moving on its own.
2. As soon as our snake will eat up the food, that food will be removed from the screen, and a new food will be showed somewhere on the screen, using random function.
3. This will give a score up.
4. But as soon as we hit the wall, in any of the 4 directions, game gets over.
5. Reset button will reset the game.






Key-points to consider in the code -

1. Arrow keys direction -

switch (event.keyCode) { case 27: reset(); break; case 37: $("#snake0").stop() moveLeft(); break; case 39: $("#snake0").stop() moveRight(); break; case 38: $("#snake0").stop() moveUp(); break; case 40: $("#snake0").stop() moveDown(); break; }



2. Food generation and swallowing methods as follow -

function generateFood() { var max = 380; var min = 0; var randomPosX = Math.random() * (max - min) + min; var randomPosY = Math.random() * (max - min) + min; $("#food0").css({ top : randomPosY, left : randomPosX, position : 'absolute' }); }
function foodSwallowed() { var snakePos = $("#snake0"); var positionOfSnake = snakePos.position(); var leftOfSnake = positionOfSnake.left; var topOfSnake = positionOfSnake.top; var foodPos = $("#food0"); var positionOfFood = foodPos.position(); var leftOfFood = positionOfFood.left; var topOfFood = positionOfFood.top; if (Math.abs(leftOfFood - leftOfSnake) < 20 && Math.abs(topOfFood - topOfSnake) < 20) { score += 100; $("#scoreDisplay").val(score); generateFood(); } }

So, once you get the code flow, your snake is ready to flow :P

Try something better and share in the comment section for the buddies.

Happy Coding!

JAVASCRIPT SAMPLES - SHOOTING GAME

Hello Buddies.

Trying a simple shooting game using mouse cursor and javascript.

pirate-icon.png

Complete code is available here -

https://github.com/namitsharma99/shoot-em-all





Here goes the code -


<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>sHoOt-Em-Up</title>
<style>
         #myArena {
         /* cursor: crosshair; */
         cursor: crosshair
         }
         .enemy {
         cursor: crosshair
         }
      </style>
<script
         src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
         src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
         $(document).ready(function(){
          generateEnemyPos();
          $("#myArena").click(function(event){
          console.log("shot fired!");
          checkCasuality(event);
          });
         });
         
         function generateEnemyPos() {
         var max = 400;
         var min = 100;
         var randomPosX = Math.random() * (max - min) + min;
         var randomPosY = Math.random() * (max - min) + min;
         $("#enemy0").css({
          top : randomPosY,
          left : randomPosX,
          position : 'absolute',
          display: 'block'
         });
         }
         
         function checkCasuality(event) {
         // alert(event.pageX+":"+event.pageY);
         var fireX = event.pageX;
         var fireY = event.pageY;
         
         var enemyPos = $("#enemy0");
         var positionOfEnemy = enemyPos.position();
         var leftOfEnemy = positionOfEnemy.left;
         var topOfEnemy = positionOfEnemy.top;
         var enemyCenterX = leftOfEnemy + 25;
         var enemyCenterY = topOfEnemy + 25;
         
         if (Math.abs(fireX - enemyCenterX) < 20 && Math.abs(fireY - enemyCenterY) < 20){
          alert ("killed");
         }
         }
      
</script>
</head>
<body>
<div>
<div id="myArena"
            style="height: 500px; width: 500px; background-color: green; position: relative; left: 0; top: 0">
            style="height: 500px; width: 500px; background-color: green; position: relative; left: 0; top: 0">
<div id="enemy0" class="enemy"
               style="height: 50px; width: 50px; display: none">
               style="height: 50px; width: 50px; display: none">
<img alt="enemy" src="pirate-icon.png" width="100%" height="100%">
</div>
</div>
</div>
</body>
</html>


We have a simple logic, the mouse cursor's coordinates should match the image's coordinates including the scope of error margin :P

Once you click in that range, you win !

As simple as that.

Give a try and come up with something good. It would be a definite confidence booster for people new to UI scripting.


Happy Coding!



JAVASCRIPT SAMPLES - RACING CARS - SIMPLE GAME

Hello Buddies.

This one is a simple javascript code written to get look and feel of a very basic racing game.

The complete code is available here -

https://github.com/namitsharma99/game-racing-car


So what do we want to implement?

It is something like this -



And how do we start?
Here it goes -

So we have out base set up in racing.jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>e_CaR-RaC_e</title>
        <link rel="stylesheet" href="./myStyle.css" />
        <link rel="icon" href="car.png" type="image/png">

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).keydown(function(event) {
                switch (event.keyCode) {
                    case 27:
                        resetCar();
                        break;
                    case 37:
                        moveLeft();
                        break;
                    case 39:
                        moveRight();
                        break;
                    case 38:
                        moveUp();
                        break;
                    case 40:
                        moveDown();
                        break;
                }
            });

            function moveLeft() {
                var element = document.getElementById("car");
                element.style.left = parseInt(element.style.left) - 2 + '%';
                $("#car0").stop().animate({
                    top: "-=10px"
                }, 2000, ifCollision());
            }

            function moveRight() {
                var element = document.getElementById("car");
                element.style.left = parseInt(element.style.left) + 2 + '%';
                $("#car0").stop().animate({
                    top: "-=10px"
                }, 2000, ifCollision());
            }

            function moveUp() {
                var element = document.getElementById("car");
                element.style.top = parseInt(element.style.top) - 2 + '%';
                /*attempt to move other car*/
                $("#car0").stop().animate({
                    top: "+=10px"
                }, 2000, ifCollision());
            }

            function moveDown() {
                var element = document.getElementById("car");
                element.style.top = parseInt(element.style.top) + 2 + '%';
                $("#car0").stop().animate({
                    top: "-=10px"
                }, 2000, ifCollision());
            }

            function ifCollision() {
                console.log("checking collision...");
                var car = $("#car");
                var positionOfCar = car.position();
                var leftOfCar = positionOfCar.left;
                var topOfCar = positionOfCar.top;

                console.log("left of car: " + positionOfCar.left + ", top of car: " + positionOfCar.top);

                var car0 = $("#car0");
                var positionOfCar0 = car0.position();
                var leftOfCar0 = positionOfCar0.left;
                var topOfCar0 = positionOfCar0.top;

                console.log("left of car 0: " + positionOfCar0.left + ", top of car 0: " + positionOfCar0.top);


                if (Math.abs(leftOfCar - leftOfCar0) < 40 && Math.abs(topOfCar - topOfCar0) < 40) {
                    alert("Caught!!");
                }
            }
        </script>
    </head>

    <body>

        <div class="container">
            <textarea class="bg">
            </textarea>
            <img id="car" src="police_car.png" style="position: absolute; left: 48%; top: 400%;" height="70" width="50">
            <!-- adding another car -->
            <img id="car0" src="car.png" style="position: absolute; left: 30%; top: 0" height="60" width="30">
        </div>

    </body>

    </html>



A small discussion.

1. We fixed the cars in the div section of the body.
2. Using keyboard events, identify the arrow keys.
3. Based on directions, invoke suitable methods -

                switch (event.keyCode) {
                    case 27:
                        resetCar();
                        break;
                    case 37:
                        moveLeft();
                        break;
                    case 39:
                        moveRight();
                        break;
                    case 38:
                        moveUp();
                        break;
                    case 40:
                        moveDown();
                        break;
                }

4. And finally we have a function that decided whether the Police car has caught the thief's car or not.

               function ifCollision() {

                console.log("checking collision...");
                var car = $("#car");
                var positionOfCar = car.position();
                var leftOfCar = positionOfCar.left;
                var topOfCar = positionOfCar.top;

                console.log("left of car: " + positionOfCar.left + ", top of car: " + positionOfCar.top);

                var car0 = $("#car0");
                var positionOfCar0 = car0.position();
                var leftOfCar0 = positionOfCar0.left;
                var topOfCar0 = positionOfCar0.top;

                console.log("left of car 0: " + positionOfCar0.left + ", top of car 0: " + positionOfCar0.top);


                if (Math.abs(leftOfCar - leftOfCar0) < 40 && Math.abs(topOfCar - topOfCar0) < 40) {
                    alert("Caught!!");
                }

5. Using positions we can set an alert limit, here it is 40.

6. TADA... try this and put your own imagination... see it rolling.

Also, to create the road moving effect, we have used styling like -

.bg {
width: 80%;
height: 600px;
background: url("background.png") repeat-y;
background-size: 100%;
-webkit-animation: displace 0.5s linear infinite;
animation: displace 0.5s linear infinite;
}
@-webkit-keyframes displace {
from { background-position: top;
} to { background-position: bottom; }
}
@keyframes displace {
from { background-position: top;
} to { background-position: bottom; }

}

{ Refer to myStyle.css }

A good use of webkit animation effects. 
A little bit of R&D can help you in figuring out how to use it efficiently.

7.  So what we have here is an arrow keys' driven car game.








Share your thoughts and experiments in the comments below.

Happy Coding!



Featured post

Oracle SQL Scheduled Jobs - An Interesting Approach

  Oracle SQL Scheduled Jobs A DB Scheduler is the best way to automate any backend database job. For instance, if you want to process the p...