0

I made a game using JavaScript in HTML. The game is running smoothly. But I want the user to enter the name at first and then start the game. After the game is finished, I want to keep the scores and users in the database. But when I write the following code, the page does not work at all. Where am I making mistakes? No database connectivity problems. Did I write the PHP codes in the wrong place?

Game.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gamedev Canvas Workshop</title>
<style>
    * { padding: 0; margin: 0; }
    canvas { background: #eee; display: block; margin: 0 auto; }
</style>
<script src="randomColor.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
</head>

<body>
<?php
require("Database.php");
if ($_SERVER['REQUEST_METHOD']=="POST"){
    $username = $_POST["Username"];
}

$sql = "INSERT INTO `scoreboard` (`Username`) VALUES ('$username')";

if (mysqli_query($conn, $sql)) {
    //echo "New record created successfully";

} else {
      echo mysqli_error($conn);


?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <canvas id="myCanvas" width="480" height="320"></canvas>
    <label name="Username" id="username-label" style="display:none"></label>
    <?php }?>
    <label name="Score" id="score-label" style="display:none"></label>
</form>

<script>
var username = prompt("İnput the username: ");
document.getElementById("username-label").innerHTML= username;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2; //2
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 5;
var brickColumnCount = 3;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;
var color = "#0095DD";

var bricks = [];
for(c=0; c<brickColumnCount; c++) {
    bricks[c] = [];
    for(r=0; r<brickRowCount; r++) {
        bricks[c][r] = { x: 0, y: 0, status: 1 };
    }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function random_color()
{
    color = randomColor();
}
function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    }
    else if(e.keyCode == 37) {
        leftPressed = true;
    }
}
function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
    }
}
function collisionDetection() {
    for(c=0; c<brickColumnCount; c++) {
        for(r=0; r<brickRowCount; r++) {
            var b = bricks[c][r];
            if(b.status == 1) {
                if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
                    dy = -dy;
                    b.status = 0;
                    random_color(); //brick lere vurdukça top renk değiştircek.
                    score++;
                    document.getElementById("score-label").innerHTML=score;
                    if(score == brickRowCount*brickColumnCount) {
                        alert("YOU WIN, CONGRATS!");
                        <?php
                        require("Database.php");

                            if ($_SERVER['REQUEST_METHOD']=="POST"){
                        $score = $_POST["score-label"];
                            }


                        $sql = "INSERT INTO `scoreboard` (`Score`) VALUES ('$score')";
                        if (mysqli_query($conn, $sql)) {
                             //echo "New record created successfully";

                        } else {
                             echo mysqli_error($conn);
                        }

                        ?>
                        document.location.reload();
                    }
                }
            }
        }
    }
}

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.closePath();
}
function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
function drawBricks() {
    for(c=0; c<brickColumnCount; c++) {
        for(r=0; r<brickRowCount; r++) {
            if(bricks[c][r].status == 1) {
                var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
                var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
                bricks[c][r].x = brickX;
                bricks[c][r].y = brickY;
                ctx.beginPath();
                ctx.rect(brickX, brickY, brickWidth, brickHeight);
                ctx.fillStyle = "#0095DD";
                ctx.fill();
                ctx.closePath();
            }
        }
    }
}

function drawLives() {
    ctx.font = "16px Arial";
    ctx.fillStyle = "#0095DD";
    ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}

function drawScore() {
    ctx.font = "16px Arial";
    ctx.fillStyle = "#0095DD";
    ctx.fillText("Score: "+score, 8, 20);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBricks();
    drawBall();
    drawPaddle();
    drawScore();
    drawLives();
    collisionDetection();

    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
    }
    if(y + dy < ballRadius) {
        dy = -dy;
    }
    else if(y + dy > canvas.height-ballRadius) {
        if(x > paddleX && x < paddleX + paddleWidth) {
            dy = -dy;
        }
        else {
            lives--;
    if(!lives) {
    alert("GAME OVER");
    <?php   
    require('Database.php');                
        if ($_SERVER['REQUEST_METHOD']=="POST"){
            $score = $_POST["score-label"];
        }


        $sql = "INSERT INTO `scoreboard` (`Score`) VALUES ('$score')";
        if (mysqli_query($conn, $sql)) {
        //echo "New record created successfully";

        } 
        else {
            echo mysqli_error($conn);
        }

            mysqli_close($conn);

        ?>
    document.location.reload();
     }
    else {
    x = canvas.width/2;
    y = canvas.height-30;
    dx = 2; //2
    dy = -2; //-2
    paddleX = (canvas.width-paddleWidth)/2;
}
        }
    }

    if(rightPressed && paddleX < canvas.width-paddleWidth) {
        paddleX += 7;
    }
    else if(leftPressed && paddleX > 0) {
        paddleX -= 7;
    }

    x += dx;
    y += dy;

    requestAnimationFrame(draw);
}

draw();
</script>

</body>
</html>

Database.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "game";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully";
?>
AloHA_ChiCken
  • 484
  • 1
  • 5
  • 24
Cenk Camkıran
  • 17
  • 1
  • 2
  • 6
  • Uhm, here's my code ... fix it? Isolate your problem please and provide the smallest subset of code. – webnoob Jan 15 '18 at 12:54
  • That being said, your PHP will run *before* the user is able to enter their name in the browser. PHP is processed on the server. You need to make an AJAX call with the users name and put it in the DB via an API call. – webnoob Jan 15 '18 at 12:54
  • regarding @webnoobs last comment :  `if(score == brickRowCount*brickColumnCount) { [...] document.location.reload(); }` cannot work, because you're including server code inside client code logic... which cannot work. I'd rather reload via js with parameters indicating what to do (https://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript) – St3an Jan 15 '18 at 13:24
  • Never make an sql query like that. You must prepare your query to avoid sql injection. Take a look at http://php.net/manual/en/mysqli.quickstart.prepared-statements.php – Ananta Jan 15 '18 at 13:46

0 Answers0