Wednesday, 3 May 2017

adding multiplayer and a readable database into my snake game

hi i am creating a snake game using jquery and html,

i need to add multiplayer functionality and some kind of system which allows users to log in and store there high score.

for simplicity the game does not need to end and i would prefer to try and keep the games code as it is, although i do understand that the code may need changing.

could anybody help me further as i am currently stuck in getting the server fully working.

the code must use socket.io, node.js and mysql.

here is my index.js file.

// creating the server variables to use throughout code.
var express = require('express');
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);

// starting file serve with the public folder
app.use(express.static('public'));

// lo if conncetion is made
io.on('connection', function (socket) {
console.log("Someone has connected!");
});

// server started message
server.listen(8081, function(){
console.log("Server started.")
});


var myLogger = function (req, res, next) {
console.log('Logged a request.');
next();
}

app.use(myLogger);


app.get('/', function (req, res) {
res.send('http://127.0.0.1:8081/snake.html for the snake game');
})


app.listen(8081);

here is my snake game html file.

<html>
<title> Snake Game Yo </title>
    <head>
    <script src="socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>   
    <link rel="stylesheet" href="snakestyle.css">


    <script>

    // // // // // socket io

var socket = io.connect('http://localhost:8081');

    // // // // // //

     /*
    // // // // // //
    // MY SQL SIDE
    var mysql = require("mysql");

    var connection = mysql.createConnection({
        host: "localhost",
        port: 3306,
        user: "root",
        password: "",
        database: "snake"   
    });

    connection.connect();

    connection.query("SELECT * FROM sample", function(error, results, fields) {
        if (error) { console.log(error); }
        for (i = 0; i < results.length; i++)
            {
                console.log(results[i].username);
                console.log(results[i].score);
                console.log("----");
            }
        });
    connection.end();

    /*
    // create player
    var player = { 
    username: "nathan",
    High score: 5,
    };
    connection.query("INSERT INTO sample SET ?",
    player,
    function(err){ if(err) console.log(err) });
    */


    // end on my mysql
    // // // // // // // 
    //*/


        var fps = 10;
        var cells = 50;

        var i = 5;
        var j = 5;
        // Player 1 (keybaord)
        var snake1 = {
        <!-- creating var direction to be used with future code -->
        <!-- the var will change the delta speed of the snake -->
            Direction: "right",
            lastKeyPressed: 0
        };



        // creating snake array
        var snake1Array = [];



        // creates a Pill for the snake to consume at a random position
        var pill = {
            x: Math.floor((Math.random()* 49) +1),
            y: Math.floor((Math.random()* 49) +1),
        }       

        // var score is used to display current score on the page
        var score = 0;


        $(document).ready(function(){

            <!-- left=37 right=39 up=38 down=40 -->
            <!-- Uses Which to determin what key was pressed -->
            <!-- != code is used to prevent snake "eating" it self -->
        $("body").keydown(function(event){

            if (event.which == 37 && snake1.Direction != "right"){
                snake1.Direction = "left";
            }
            if (event.which == 39 && snake1.Direction != "left"){
                 snake1.Direction = "right";
            }           
            if (event.which == 40 && snake1.Direction != "up"){
                 snake1.Direction = "down";
            }
            if (event.which == 38 && snake1.Direction != "down"){
                snake1.Direction = "up";
            }



            <!--  shows keypressed in log  -->
    //      snake1.lastKeyPressed = event.which;
    //      console.log(event);


        });

            requestAnimationFrame(draw);

        $("body").click(function(){
            $(this).animate({
                    width: '100%'
                    }, function(){
                        $("body").css("background-color", $(this).css("background-color"));
                    });
                });


        });



        function draw() {

            setTimeout(function() {


                var cvs = $("canvas").get(0);
                var ctx = cvs.getContext("2d");


                ctx.clearRect(0, 0, cvs.width, cvs.height);


            snake1Array.unshift({
                x: i,
                y: j,

            });


            //Snake 1 colour & creation
                        for(q = 0; q < snake1Array.length; q++)
            {           
                ctx.fillStyle="#42bff4";
                ctx.fillRect(snake1Array[q].x*cvs.width/cells,
                             snake1Array[q].y*cvs.height/cells,
                             cvs.width/cells,
                             cvs.height/cells);
            }

            if (snake1Array.length > score+1)
            {
                snake1Array.pop();
            }


            // Pill colour & creation
                ctx.fillStyle="#119120";
                ctx.fillRect(pill.x*cvs.width/cells,
                            pill.y*cvs.height/cells,
                            cvs.width/cells,
                            cvs.height/cells);              

                <!-- Moving the snake direction -->
                if (snake1.Direction == "right")
                {
                    i++;
                }
                if (snake1.Direction == "left")
                {
                    i--;
                }
                if (snake1.Direction == "up")
                {
                    j--;
                }
                if (snake1.Direction == "down")
                {
                    j++;
                }



                <!-- Wall Collision -->
                if (i<0)
                    {
                    i=0;
                }
                    if (i>49)
                {
                    i=49;
                }
                    if (j<0)
                {
                    j=0;
                }
                    if (j>49)
                {
                    j=49;
                }

                <!-- Pill collision -->
                if (i == pill.x && j == pill.y)
                {
                    pill.x = Math.floor((Math.random()* 49) +1);
                    pill.y = Math.floor((Math.random()* 49) +1);
                    score++;
                    $("p").remove(0)
                    $("body").append("<p>Current Score: "+ score);
                };

                requestAnimationFrame(draw);

                //console.log(snake1.Direction);
                //console.log(snake1Array[0]);
            }, 1000/fps);
        }

    </script>

    </head>


    <body>

    <canvas width="500" height="500" style="border: solid black 1px">
        Sorry, no canvas support!
    </canvas>


        </select>
    </div>

        <p>Current Score: </p>

    </body>
</html>

as you have gathered i am currently getting a error on the node side which looks like this

snake>node index.js Server started. events.js:160 throw er; // Unhandled 'error' event ^

Error: listen EADDRINUSE :::8081
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at Server._listen2 (net.js:1258:14)
    at listen (net.js:1294:10)
    at Server.listen (net.js:1390:5)
    at EventEmitter.listen (D:\Web Year2\xampp_App\htdocs\snake\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (D:\Web Year2\xampp_App\htdocs\snake\index.js:36:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)



via Binnerz92

No comments:

Post a Comment