Skip to content

Commit

Permalink
re-modified
Browse files Browse the repository at this point in the history
  • Loading branch information
harish551 committed Jan 6, 2019
1 parent 43de8dc commit cebc778
Show file tree
Hide file tree
Showing 3 changed files with 165 additions and 166 deletions.
49 changes: 26 additions & 23 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,53 @@
//importing modules

let request = require('request');
let path = require('path');
let express = require('express');
let app = express();
let mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/snake-game');

let htmlPath = path.join(__dirname);
app.use(express.static(htmlPath));
mongoose.connect('mongodb://localhost:27017/snake-game'); //connecting to the database

let htmlPath = path.join(__dirname); // setting path for project

app.use(express.static(htmlPath)); // using middilewere

let playerSchema = new mongoose.Schema({

name : String,
score : Number
name: String, // database schema
score: Number
});

let Player = mongoose.model("Player", playerSchema);
let data,db,scores,topfive,str;
let Player = mongoose.model('Player', playerSchema); //modeling database

let data, db, scores, topfive, str;

app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');

});

app.use("/gameover/:name/:score", (req, res) => {
app.use('/gameover/:name/:score', (req, res) => {
req.params.score = +req.params.score;
let playerRecord = new Player(req.params);
data = req.params;
playerRecord.save()
.then(item => {
console.log("score saved to database"+ req.params);
console.log('score saved to database' + req.params);
})
.catch(err => {
console.log(err);
});

res.redirect('http://localhost:8000/gamestats');
res.redirect('http://localhost:8000/gamestats');
});
app.get('/gamestats',function(req,res){
Player.find( function(err,db){
scores = db.map((a) => a.score);
topfive = db.sort((a,b) => b.score - a.score).slice(0,5);
str = topfive.map((obj) => obj.name + ' : ' + obj.score).join('<br/>');
res.send(`<body style = "background : Teal;">

app.get('/gamestats', function(req, res) {
Player.find(function(err, db) {
scores = db.map((a) => a.score);
topfive = db.sort((a, b) => b.score - a.score).slice(0, 5);
str = topfive.map((obj) => obj.name + ' : ' + obj.score).join('<br/>');
res.send(`<body style = "background : Teal;">
<center>
<h1 style = "font-size: 100px ">Game Over</h1>
<h1> Your Score: ${data.score}</h1>
Expand All @@ -55,11 +61,8 @@ app.get('/gamestats',function(req,res){
</body>
`);

});
});
});



app.listen(8000);

require("openurl").open("http://localhost:8000/")
require('openurl').open('http://localhost:8000/')
241 changes: 116 additions & 125 deletions classic_snake.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

const cvs = document.getElementById("snakecanvas");
const context = cvs.getContext("2d");

Expand All @@ -11,166 +10,158 @@ let snake = [];
// intialize snake

snake[0] = {
x : 20 * box,
y : 20 * box
x: 20 * box,
y: 20 * box
};

// intialize food

let food = {
x : Math.floor(Math.random()* (w/box)) * box,
y : Math.floor(Math.random()* (h/box)) * box
}


x: Math.floor(Math.random() * (w / box)) * box,
y: Math.floor(Math.random() * (h / box)) * box
}

let score = 0;

//snake controlling part

let direction;

document.addEventListener("keydown",findDirection);

function findDirection(event){
document.getElementById('instruction').innerHTML = 'press p to pause';
let key = event.keyCode;

if( key == 37 && direction != "RIGHT"){
direction = "LEFT";
}else if(key == 38 && direction!= "DOWN"){
direction = "UP";

}else if(key == 39 && direction!= "LEFT"){
direction = "RIGHT";

}else if(key == 40 && direction!= "UP"){
direction = "DOWN";
}
else if(key == 80){
togglePause();
}
document.addEventListener("keydown", findDirection);

function findDirection(event) {
document.getElementById('instruction').innerHTML = 'press p to pause';
let key = event.keyCode;

if (key == 37 && direction != "RIGHT") {
direction = "LEFT";
} else if (key == 38 && direction != "DOWN") {
direction = "UP";

} else if (key == 39 && direction != "LEFT") {
direction = "RIGHT";

} else if (key == 40 && direction != "UP") {
direction = "DOWN";
} else if (key == 80) {
togglePause();
}
}

// collison of snake with snake body

function collision(head,array){
for(let i = 0; i < array.length; i++){
if(head.x == array[i].x && head.y == array[i].y){
return true;
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
return false;
}
return false;
}

function drawFood(x, y) {

context.fillStyle = "red";
context.fillRect(x, y, box, box);
context.strokeStyle = 'black';
context.strokeRect(x, y, box, box);

}

function drawFood (x,y) {

context.fillStyle = "red";
context.fillRect(x, y, box, box);
context.strokeStyle = 'black';
context.strokeRect(x, y, box, box);

function draw() {

context.fillStyle = 'lightgrey';
context.fillRect(0, 0, w, h);
context.strokeStyle = 'black';
context.strokeRect(0, 0, w, h);

for (let i = 0; i < snake.length; i++) {
context.fillStyle = (i == 0) ? "green" : "yellow";
context.fillRect(snake[i].x, snake[i].y, box, box);

context.strokeStyle = "black";
context.strokeRect(snake[i].x, snake[i].y, box, box);
}

drawFood(food.x, food.y);

//old direction positions
let snakeX = snake[0].x;
let snakeY = snake[0].y;

function draw(){
context.fillStyle = 'lightgrey';
context.fillRect(0, 0, w, h);
context.strokeStyle = 'black';
context.strokeRect(0, 0, w, h);
for( let i = 0; i < snake.length ; i++){
context.fillStyle = ( i == 0 )? "green" : "yellow";
context.fillRect(snake[i].x,snake[i].y,box,box);
context.strokeStyle = "black";
context.strokeRect(snake[i].x,snake[i].y,box,box);
//moving in direction

if (direction == "LEFT") snakeX -= box;
if (direction == "UP") snakeY -= box;
if (direction == "RIGHT") snakeX += box;
if (direction == "DOWN") snakeY += box;

// if the snake eats the food
if (snakeX == food.x && snakeY == food.y) {
score++;
food = {
x: Math.floor(Math.random() * (w / box)) * box,
y: Math.floor(Math.random() * (h / box)) * box
}

drawFood(food.x,food.y);

//old direction positions
let snakeX = snake[0].x;
let snakeY = snake[0].y;

//moving in direction

if( direction == "LEFT") snakeX -= box;
if( direction == "UP") snakeY -= box;
if( direction == "RIGHT") snakeX += box;
if( direction == "DOWN") snakeY += box;

// if the snake eats the food
if(snakeX == food.x && snakeY == food.y) {
score++;
for (let i = 0; i < snake.length; i++) {
if (food.x === snake[i].x && food.y === snake[i].y) {
food = {
x : Math.floor(Math.random()* (w/box) )* box,
y : Math.floor(Math.random()* (h/box) )* box
}
for(let i=0;i<snake.length;i++){
if(food.x === snake[i].x && food.y === snake[i].y){
food = {
x : Math.floor(Math.random()* (w/box) )* box,
y : Math.floor(Math.random()* (h/box) )* box
}
i = 0;
}
}

} else {

snake.pop(); //removing tail of snake
x: Math.floor(Math.random() * (w / box)) * box,
y: Math.floor(Math.random() * (h / box)) * box
}
i = 0;
}
}


//adding new head for snake

let newHead = {
x : snakeX,
y : snakeY
}


// checking game over condition

if (snakeX < 0 || snakeX == w || snakeY < 0 || snakeY == h || collision(newHead,snake)){
clearInterval(game);
alert(` Oops: Game Over \n Your Score: ${score}`);
name = prompt('Enter Your Name ');
if(name == '') name = 'anonymous'
window.location = `http://localhost:8000/gameover/${name}/${score}`;

}

snake.unshift(newHead);

displayScore();
} else {

snake.pop(); //removing tail of snake
}

//adding new head for snake

let newHead = {
x: snakeX,
y: snakeY
}

// checking game over condition

if (snakeX < 0 || snakeX == w || snakeY < 0 || snakeY == h || collision(newHead, snake)) {
clearInterval(game);
alert(` Oops: Game Over \n Your Score: ${score}`);
name = prompt('Enter Your Name ');
if (name == '') name = 'anonymous'
window.location = `http://localhost:8000/gameover/${name}/${score}`;

}

snake.unshift(newHead);
displayScore();
}

// call draw function every 100 ms

let game = setInterval(draw,100);
let game = setInterval(draw, 100);

let paused = false;

function togglePause()
{
if (!paused)
{
paused = true;
clearInterval(game);

} else
{
paused= false;
game = setInterval(draw,100);
}
//function to pause the game

function togglePause() {
if (!paused) {
paused = true;
clearInterval(game);

} else {
paused = false;
game = setInterval(draw, 100);
}

}

let name;
function displayScore(){
document.getElementById('score').innerHTML = score;

function displayScore() {
document.getElementById('score').innerHTML = score;
}
Loading

0 comments on commit cebc778

Please sign in to comment.