So I have a simple snake game set up in which the score increments +1 every time the player collides with the right piece(you all the know the game). Anyway.
I want the background to change image every multiple of 5 on the score to represent a new level. Is this possible? I'm assuming it would be something along the lines of;
if score > = 5 then
var img = document.getElementById("anid");
ctx.drawImage(img, 0, 0, w, h);
I know the syntax there is very wrong but is the thinking behind it right?
// JavaScript Document
$(document).ready(function(){
//Canvas stuff
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
//Lets save the cell width in a var for easy control
var cw =10;
var d;
var food;
var score;
if (score % 5 == 0) {
//Score is a divisor of 5, new level!
var img = document.getElementById("scream1");
ctx.drawImage(img, 0, 0, w, h);
//do what you want
}
var obstacle;
var snd = new Audio("sfx1.wav"); // buffers automatically when created
var snd2 = new Audio("sfx2.wav");
var snd3 = new Audio("sfx.wav");
var snd4 = new Audio("poke.mp3");
snd4.play();
//Timer
var max_timer = 15;
var current_timer;
var show_timer = (function () {
current_timer--;
$("#timer").text(current_timer);
if (current_timer < 0) {
$("#bonus").empty();
init();
return;
}
});
var timer_interval = setInterval(show_timer, 1000);
//Lets create the snake now
var snake_array; // an array of cells to make up the snake
function init()
{
d = "right";//default direction
create_snake();
create_food();
create_obstacle();
create_obstacle2();
create_obstacle3();
create_obstacle4();
score = 0;
current_timer = max_timer;
//Lets move the snake now using a timer
//Which will trigger the paint function
//Eevery 60ms
if(typeof game_loop != "undefined")
clearinterval(game_loop);
game_loop =setInterval(paint, 60);
}
init();
function create_snake()
{
var length = 5; //Length of the snake
snake_array = []; //Empty array to start with
for(var i = length-1; i>=0; i--)
{
//This will create a horizontal snake starting from the top left
snake_array.push({x: i,y:0});
}
}
//Lets create the food now
function create_food()
{
food = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
//This will create a well with x/y between 0-44
//Because there are 45(450/10) positions
//Accross the rows and columns
}
//Create next level function
function next_level()
{
var img = document.getElementById("scream1");
ctx.drawImage(img, 0, 0, w, h);
}
//Lets create the obstacle now
function create_obstacle()
{
obstacle = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}
//Lets create a second obstacle
function create_obstacle2()
{
obstacle2 = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}
//Lets create a third obstacle
function create_obstacle3()
{
obstacle3 = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}
//Lets create a fourth obstacle
function create_obstacle4()
{
obstacle4 = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}
//Lets paint the snake now
function paint()
{
//To avoid the snake trail we need to paint
//the BGon every frame
//Lets paint the canvas now
var img = document.getElementById("scream");
ctx.drawImage(img, 0, 0, w, h);
//The movement code for the snake to come here
//The logic is simple
//Pop out the tail cell
//Place it in front of the head cell
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//These were the posiiton of the head cell.
//We will increment it to get the new position
//Lets add proper direction based movement now
if(d == "right")nx++;
else if(d == "left")nx--;
else if(d == "up") ny--;
else if(d == "down") ny ++;
//Lets add the game over clauses now
//This will restart the game if the snake hits the wall
//Lets add the code for the body collision
if(nx == -1 || nx == w/cw || ny == -1|| ny == h/cw||
check_collision(nx,ny, snake_array))
{
//restart game
$("#bonus").empty();
snd3.play();
init();
//Lets organise the code a bit now
return;
}
//If snake collides with obstacle, restart game
if (nx == obstacle.x && ny == obstacle.y)
{
$("#bonus").empty();
snd3.play();
init();
return;
}
//If snake collides with obstacle, restart game
if (nx == obstacle3.x && ny == obstacle3.y)
{
$("#bonus").empty();
snd3.play();
init();
return;
}
//If snake collides with obstacle, restart game
if (nx == obstacle4.x && ny == obstacle4.y)
{
$("#bonus").empty();
snd3.play();
init();
return;
}
//If snake collides with obstacle, get more time
if (nx == obstacle2.x && ny == obstacle2.y)
{
current_timer = max_timer
create_obstacle2();
snd2.play();
$("#bonus").append("<h2>Time Bonus!</h2>");
$( '#bonus' ).show(function(){
$(this).fadeOut(2000);
});
}
//Lets write the code to make the snake eat the food
//The logic is simple
//If the new head position matches with that of the food
//Create a new head instead of moving the tail
if(nx == food.x && ny == food.y)
{
var tail = {x:nx, y:ny};
score++;
if (score % 2 == 0) {
next_level();
}
create_food();
create_obstacle();
create_obstacle3();
create_obstacle4();
snd.play();
$("#bonus").empty();
}
else
{
var tail = snake_array.pop();//pops out the last cell
tail.x = nx;tail.y = ny;
}
//The snake can now eat the food
snake_array.unshift(tail);//puts the tail as the first cell
for(var i= 0;i<snake_array.length; i++)
{
var c = snake_array[i];
//Lets paint 10px wide cells
paint_cell(c.x, c.y);
}
//Lets paint the food
paint_cell(food.x, food.y);
//Lets paint the obstacle
paint_cell2(obstacle.x, obstacle.y);
//Lets paint the second obstacle
paint_cell3(obstacle2.x, obstacle2.y);
//Lets paint the third obstacle
paint_cell2(obstacle3.x, obstacle3.y);
//Lets paint the fourth obstacle
paint_cell2(obstacle4.x, obstacle4.y);
//Lets paint the score
var score_text = "Score:" + score;
ctx.fillText(score_text, 5, h-5);
}
//Lets first create a generic function to paint cells
function paint_cell(x,y)
{
ctx.fillStyle="white";
ctx.fillRect(x*cw,y*cw, cw, cw);
ctx.strokeStyle = "black";
ctx.strokeRect(x*cw,y*cw, cw, cw);
}
function paint_cell2(x,y)
{
ctx.fillStyle="orange";
ctx.fillRect(x*cw,y*cw, cw, cw);
ctx.strokeStyle = "black";
ctx.strokeRect(x*cw,y*cw, cw, cw);
}
function paint_cell3(x,y)
{
ctx.fillStyle="red";
ctx.fillRect(x*cw,y*cw, cw, cw);
ctx.strokeStyle = "black";
ctx.strokeRect(x*cw,y*cw, cw, cw);
}
function check_collision(x, y, array)
{
//This function will check the provided x/y
//coordinates exist in an array of cells or not
for(var i = 0; i<array.length; i++)
{
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
}
//Lets addd the keyboard controls now
$(document).keydown(function(e){
var key = e.which;
//We will add another clause to prevent reverse gear
if(key == "37" && d!= "right") d = "left";
else if(key == "38" && d!= "down") d="up";
else if(key == "39" && d!= "left") d="right";
else if(key == "40" && d!= "up") d="down";
//The snake is now keyboard controllable
})
})
You can use the % operator to solve this. MSDN: http://msdn.microsoft.com/en-us/library/ie/9f59bza0(v=vs.94).aspx
Code
if (score % 5 == 0) {
//Score is a divisor of 5, new level!
var img = document.getElementById("anid");
//do what you want
}
Here's a fiddle demonstrating the concept: http://jsfiddle.net/vCHCG/
Related
I am using CodeHs which uses very basic JavaScript. No HTML or Design modes yet and it's only JS Script. My teacher game me this collision code:
function checkCircleCollision (circle1, circle2) {
var dx = circle1.x - circle2.x;
var dy = circle1.y - circle2.y;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < circle1.radius + circle2.radius) {
return true;
}
return false;
}
Example of how to use collision functions:
The above functions will give back a value of either true or false, so you can use them with an If Statement.
Immediately after moving objects, you can check if two objects are touching:
if (checkCollision(player,enemy))
player.setColor(Color.red);
else
player.setColor(Color.black);.
But when I put it in my program it is saying that x and y that is being used for dx and dy is not defined. Without this, my game can't run. Here is all of my code:
//Variables
var brown = new Color(139 ,69 ,19);
var START_RADIUS = 1;
var DELAY = 100;
var INCREMENT = 1;
var CHANGE_COLORS_AT = 10;
var MAX_RADIUS = 100;
var counter = 0;
var player;
var finishLine;
var RADIUS = 20;
var obstacle;
var obstacle2;
var obstacle3;
var dx = 0;
var dy = 4;
var dx2 = 0;
var dy2 = -4;
var dx3 = 0;
var dy3 = 7;
var x;
var y;
//Start Function
function start(){
var wannaStart = readLine("Do you wanna start playing Impossible Dodgeball? ")
if(wannaStart == "Yes" || wannaStart == "yes" || wannaStart == "Absolutely!"){
startGame();
println("Get to the finish line without getting hit. Enjoy! ");
} else {
println("Enjoy this blank canvas then!");
}
}
//Starts the game if the user responded to correctly to the if statement above
function startGame(){
// checkForCollisions();
drawBackground();
player = drawCircle(20, Color.red, 25, getHeight()/2);
keyDownMethod(move);
drawObstacles();
}
//Draws the background
function drawBackground(){
drawRectangle(getWidth(), 250, 0, 0, Color.blue);
drawSun();
drawRectangle(getWidth(), getHeight()/2, 0, 300, brown);
drawRectangle(getWidth(), 50, 0, 250, Color.green);
finishLine = new Rectangle(10, getHeight());
finishLine.setPosition(350, 0);
finishLine.setColor(Color.white);
add(finishLine);
drawRectangle(10, getHeight(), 360, 0, Color.black);
drawRectangle(10, getHeight(), 370, 0, Color.white);
drawRectangle(10, getHeight(), 380, 0, Color.black);
drawRectangle(10, getHeight(), 390, 0, Color.white);
}
//Draws the rising sun in the background
function drawSun(){
circle = new Circle(START_RADIUS);
circle.setPosition(getWidth()/2, getHeight()/2+10);
add(circle);
setTimer(draw, 50);
}
//Draws all the moving obstacles
function drawObstacles(){
drawObstacle1();
drawObstacle2();
drawObstacle3();
}
//I was unable to get the collision code for the player and the obstacles to work :(
/*function checkForCollisions(){
if(checkCircleCollision(player, obstacle) == true){
println("You lose");
}
}
function checkCircleCollision (circle1, circle2) {
var dx4 = circle1.x - circle2.x;
var dy4 = circle1.y - circle2.y;
var distance = Math.sqrt(dx4 * dx4 + dy4 * dy4);
if (distance < circle1.radius + circle2.radius) {
return true;
}
return false;
}*/
//Draws the first obstacle
function drawObstacle1(){
obstacle = new Circle(RADIUS);
obstacle.setPosition(100, 100);
obstacle.setColor(Randomizer.nextColor());
add(obstacle);
setTimer(draw2, 20);
}
//Draws the second obstacle
function drawObstacle2(){
obstacle2 = new Circle(30);
obstacle2.setPosition(175, 300);
obstacle2.setColor(Randomizer.nextColor());
add(obstacle2);
setTimer(draw3, 20);
}
//Draws the third obstacle
function drawObstacle3(){
obstacle3 = new Circle(10);
obstacle3.setPosition(240, 50);
obstacle3.setColor(Randomizer.nextColor());
add(obstacle3);
setTimer(draw4, 20);
}
//Moves the obstacle
function draw2(){
checkForWalls();
obstacle.move(dx, dy);
}
//Same as above but for obstacle 2
function draw3(){
checkForWalls2();
obstacle2.move(dx2, dy2);
}
//Same as above but for obstacle 3
function draw4(){
checkForWalls3();
obstacle3.move(dx3, dy3);
}
//Bounces obstacle 1 off of the walls
function checkForWalls(){
//bottom wall
if(obstacle.getY() + obstacle.getRadius() > getHeight()){
dy = -dy;
}
//top wall
if(obstacle.getY() - obstacle.getRadius() < 0){
dy = -dy;
}
}
//Bounces obstacle 2 off of the walls
function checkForWalls2(){
//bottom wall
if(obstacle2.getY() + obstacle2.getRadius() > getHeight()){
dy2 = -dy2;
}
//top wall
if(obstacle2.getY() - obstacle2.getRadius() < 0){
dy2 = -dy2;
}
}
//Bounces obstacle 3 off of the walls
function checkForWalls3(){
//bottom wall
if(obstacle3.getY() + obstacle3.getRadius() > getHeight()){
dy3 = -dy3;
}
//top wall
if(obstacle3.getY() - obstacle3.getRadius() < 0){
dy3 = -dy3;
}
}
//Provided by CodeHS
function drawRectangle(width, height, x, y, Color){
var rect = new Rectangle(width, height);
rect.setPosition(x, y);
rect.setColor(Color);
add(rect);
}
//Provided by CodeHS
function drawCircle(radius, Color, x, y){
var circle = new Circle(radius);
circle.setColor(Color);
circle.setPosition(x, y);
add(circle);
return(circle);
}
//Provided by CodeHs
function draw(){
START_RADIUS = START_RADIUS + INCREMENT;
circle.setRadius(START_RADIUS);
circle.setColor(Color.yellow);
counter++;
if(counter == MAX_RADIUS){
counter = 0;
START_RADIUS = 1;
}
}
//Moves the player and if it hits the finish line, spams the message "You win!"
function move(e){
if(e.keyCode == Keyboard.LEFT){
player.move(-5, 0);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.UP){
player.move(0, -5);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.DOWN){
player.move(0, 5);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.RIGHT){
player.move(5, 0);
setTimer(printWin, DELAY);
}
}
//Prints the win message once player wins
function printWin(){
if(player.getX() >= finishLine.getX()) {
var won = true;
}
if(won == true){
println("You win!");
}
}
Please remember that it is very basic code (no HTML or design) and I'm new.
The way to get an object position is to use object.getX() and object.getY(). Anyways, I made it spam you lose when you touch a ball with your collision code. Here is the fixed game:
//Variables
var brown = new Color(139 ,69 ,19);
var START_RADIUS = 1;
var DELAY = 100;
var INCREMENT = 1;
var CHANGE_COLORS_AT = 10;
var MAX_RADIUS = 100;
var counter = 0;
var player;
var circle;
var finishLine;
var RADIUS = 20;
var obstacle;
var obstacle2;
var obstacle3;
var dx = 0;
var dy = 4;
var dx2 = 0;
var dy2 = -4;
var dx3 = 0;
var dy3 = 7;
var x;
var y;
//Start Function
function start(){
var wannaStart = readLine("Do you wanna start playing Impossible Dodgeball? ")
if(wannaStart == "Yes" || wannaStart == "yes" || wannaStart == "Absolutely!"){
startGame();
println("Get to the finish line without getting hit. Enjoy! ");
} else {
println("Enjoy this blank canvas then!");
}
}
//Starts the game if the user responded to correctly to the if statement above
function startGame(){
// checkForCollisions();
drawBackground();
player = drawCircle(20, Color.red, 25, getHeight()/2);
keyDownMethod(move);
drawObstacles();
}
//Draws the background
function drawBackground(){
drawRectangle(getWidth(), 250, 0, 0, Color.blue);
drawSun();
drawRectangle(getWidth(), getHeight()/2, 0, 300, brown);
drawRectangle(getWidth(), 50, 0, 250, Color.green);
finishLine = new Rectangle(10, getHeight());
finishLine.setPosition(350, 0);
finishLine.setColor(Color.white);
add(finishLine);
drawRectangle(10, getHeight(), 360, 0, Color.black);
drawRectangle(10, getHeight(), 370, 0, Color.white);
drawRectangle(10, getHeight(), 380, 0, Color.black);
drawRectangle(10, getHeight(), 390, 0, Color.white);
}
//Draws the rising sun in the background
function drawSun(){
circle = new Circle(START_RADIUS);
circle.setPosition(getWidth()/2, getHeight()/2+10);
add(circle);
setTimer(draw, 50);
}
//Draws all the moving obstacles
function drawObstacles(){
drawObstacle1();
drawObstacle2();
drawObstacle3();
}
//I was unable to get the collision code for the player and the obstacles to work :(
//I fixed it :)
//the fixed code is on line 231
function checkCircleCollision (circle1, circle2) {
var dx4 = circle1.getX() - circle2.getX();
var dy4 = circle1.getY() - circle2.getY();
var distance = Math.sqrt(dx4 * dx4 + dy4 * dy4);
if (distance < circle1.radius + circle2.radius) {
return true;
}
return false;
}
//Draws the first obstacle
function drawObstacle1(){
obstacle = new Circle(RADIUS);
obstacle.setPosition(100, 100);
obstacle.setColor(Randomizer.nextColor());
add(obstacle);
setTimer(draw2, 20);
}
//Draws the second obstacle
function drawObstacle2(){
obstacle2 = new Circle(30);
obstacle2.setPosition(175, 300);
obstacle2.setColor(Randomizer.nextColor());
add(obstacle2);
setTimer(draw3, 20);
}
//Draws the third obstacle
function drawObstacle3(){
obstacle3 = new Circle(10);
obstacle3.setPosition(240, 50);
obstacle3.setColor(Randomizer.nextColor());
add(obstacle3);
setTimer(draw4, 20);
}
//Moves the obstacle
function draw2(){
checkForWalls();
obstacle.move(dx, dy);
}
//Same as above but for obstacle 2
function draw3(){
checkForWalls2();
obstacle2.move(dx2, dy2);
}
//Same as above but for obstacle 3
function draw4(){
checkForWalls3();
obstacle3.move(dx3, dy3);
}
//Bounces obstacle 1 off of the walls
function checkForWalls(){
//bottom wall
if(obstacle.getY() + obstacle.getRadius() > getHeight()){
dy = -dy;
}
//top wall
if(obstacle.getY() - obstacle.getRadius() < 0){
dy = -dy;
}
}
//Bounces obstacle 2 off of the walls
function checkForWalls2(){
//bottom wall
if(obstacle2.getY() + obstacle2.getRadius() > getHeight()){
dy2 = -dy2;
}
//top wall
if(obstacle2.getY() - obstacle2.getRadius() < 0){
dy2 = -dy2;
}
}
//Bounces obstacle 3 off of the walls
function checkForWalls3(){
//bottom wall
if(obstacle3.getY() + obstacle3.getRadius() > getHeight()){
dy3 = -dy3;
}
//top wall
if(obstacle3.getY() - obstacle3.getRadius() < 0){
dy3 = -dy3;
}
}
//Provided by CodeHS
function drawRectangle(width, height, x, y, Color){
var rect = new Rectangle(width, height);
rect.setPosition(x, y);
rect.setColor(Color);
add(rect);
}
//Provided by CodeHS
function drawCircle(radius, Color, x, y){
var circle = new Circle(radius);
circle.setColor(Color);
circle.setPosition(x, y);
add(circle);
return(circle);
}
//Provided by CodeHs
function draw(){
START_RADIUS = START_RADIUS + INCREMENT;
circle.setRadius(START_RADIUS);
circle.setColor(Color.yellow);
counter++;
if(counter == MAX_RADIUS){
counter = 0;
START_RADIUS = 1;
}
}
//Moves the player and if it hits the finish line, spams the message "You win!"
function move(e){
if(e.keyCode == Keyboard.LEFT){
player.move(-5, 0);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.UP){
player.move(0, -5);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.DOWN){
player.move(0, 5);
setTimer(printWin, DELAY);
}
if(e.keyCode == Keyboard.RIGHT){
player.move(5, 0);
setTimer(printWin, DELAY);
}
//lose code implements your collision code to detect if player is touching ball
if(checkCircleCollision(player, obstacle) == true || checkCircleCollision(player, obstacle2) == true || checkCircleCollision(player, obstacle3) == true){
setTimer(Fail, DELAY);
}
}
//Prints the win message once player wins
function printWin(){
if(player.getX() >= finishLine.getX()) {
var won = true;
}
if(won == true){
println("You win!");
}
}
function Fail(){
println("You lost!!!");
}
Catbus game
I'm trying to make my cat only jump once until it lands back on the ground. I've tried to add a statement that makes it only go to a certain point, but the velocity keeps working against it. It begins to act like a basketball that has been bounced to much. I wouldn't want to add a collider (even though I have debated it). It would just make it worse...
The code is as follows:
let img; //background
var bgImg; //also the background
var x1 = 0;
var x2;
var scrollSpeed = 4; //how fast background is
let bing; //for music
let cat;
var mode; //determines whether the game has started
let gravity = 0.2; //jumping forces
let velocity = 0.1;
let upForce = 6;
let startY = 730; //where cat bus jumps from
let startX = 70;
var font1; //custom fonts
var font2;
p5.disableFriendlyErrors = true; //avoids errors
function preload() {
bgImg = loadImage("backgwound.png"); //importing background
bing = loadSound("catbus theme song.mp3"); //importing music
font1 = loadFont("Big Font.TTF");
font2 = loadFont("Smaller Font.ttf");
}
function setup() {
createCanvas(1000, 1000); //canvas size
img = loadImage("backgwound.png"); //background in
x2 = width;
bing.loop(); //loops the music
cat = {
//coordinates for catbus
x: startX,
y: startY,
};
catGif = createImg("catgif.gif"); //creates catbus
catGif.position(cat.x, cat.y); //creates position
catGif.size(270, 100); //creates how big
mode = 0; //game start
textSize(50); //text size
}
function draw() {
let time = frameCount; //start background loop
image(img, 0 - time, 0);
image(bgImg, x1, 2, width, height);
image(bgImg, x2, 2, width, height);
x1 -= scrollSpeed;
x2 -= scrollSpeed;
if (x1 <= -width) {
x1 = width;
}
if (x2 <= -width) {
x2 = width;
} //end background loop
fill("white"); //text colour
if (mode == 0) {
textSize(20);
textFont(font1);
text("press SPACE to start the game!", 240, 500); //what text to type
}
if (mode == 0) {
textSize(35);
textFont(font2);
text("CATBUS BIZZARE ADVENTURE", 90, 450); //what text to type
}
cat.y = cat.y + velocity; //code for jumping
velocity = velocity + gravity;
if (cat.y > startY) {
velocity = 0;
// cat.y = startY;
}
catGif.position(cat.x, cat.y);
}
function keyPressed() {
if (keyCode === 32) { //spacebar code
// if ((cat.y = 730)) {
// cat.y > 730;
mode = 1;
velocity += -upForce;
}
// }
}
You can simply do this to the keyPressed function
function keyPressed() {
if (keyCode === 32 && velocity == 0) { //spacebar code
// if ((cat.y = 730)) {
// cat.y > 730;
mode = 1;
velocity += -upForce;
}
}
I'm relatively new to canvas and I'm trying to make a space ship type game. I have everything else I'd like down, except for the ship turning itself. I want to make the image of the ship rotate when the arrow keys are clicked.
So if the left arrow key is clicked, it will turn to face the left, and the right arrow key is clicked it will turn to face the right, and so on. I really can't figure this out, if anyone can show me how to do this I would really appreciate it.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
/*Variable to store score*/
var score = 0;
/*Variable that stores the players object properties*/
var x = 50;
var y = 100;
var speed = 6;
var sideLength = 50;
/*Flags to track when keypress is active*/
var down = false;
var up = false;
var left = false;
var right = false;
/*Variables that store target position and size*/
var targetX = 0;
var targetY = 0;
var targetLength = 25;
/*If a number is within range b to c*/
function isWithin(a, b, c) {
return (a > b && a < c)
}
var countDown = 30;
/*Id to track set time*/
var id = null;
/*Listening for if one of the keys is pressed*/
canvas.addEventListener('keydown', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = true;
}
if (event.keyCode === 38) {
up = true;
}
if (event.keyCode === 37) {
left = true;
}
if (event.keyCode === 39) {
right = true;
}
});
/*Listening for if one of the keys is released*/
canvas.addEventListener('keyup', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = false;
}
if (event.keyCode === 38) {
up = false;
}
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 39) {
right = false;
}
});
/*Function to show menu*/
function menu() {
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Collect The Thing', canvas.width / 2, canvas.height / 4);
context.font = '30px Arial';
context.fillText('Press to Start', canvas.width / 2, canvas.height / 2);
/*Listen for click to start game*/
canvas.addEventListener('click', startGame);
}
/*Function to start the game*/
function startGame() {
/*reduce the countdown timer every 1 second*/
id = setInterval(function () {
countDown--;
}, 1000)
/*remove click events*/
canvas.removeEventListener('click', startGame);
moveTarget();
draw();
}
/*Show game over screen*/
function endGame() {
/*stop the countdown*/
clearInterval(id);
/*clear game board*/
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Finale Score: ' + score, canvas.width / 2, canvas.height / 4);
}
/*Move target to random location in canvas*/
function moveTarget() {
targetX = Math.round(Math.random() * canvas.width - targetLength);
targetY = Math.round(Math.random() * canvas.height - targetLength);
}
/*Clear the Canvas*/
function erase() {
context.fillStyle = '#FFFFFF';
context.fillRect(0, 0, 600, 500);
}
/*Main animation drawing loop with game logic*/
function draw() {
erase();
/*Move the player sqaure*/
if (down) {
y += speed;
}
if (up) {
y -= speed;
}
if (right) {
x += speed;
}
if (left) {
x -= speed;
}
if (y + sideLength > canvas.height) {
y = canvas.height - sideLength;
}
if (y < 0) {
y = 0;
}
if (x < 0) {
x = 0;
}
if (x + sideLength > canvas.width) {
x = canvas.width - sideLength;
}
/*Collide with target*/
if (isWithin(targetX, x, x + sideLength) || isWithin(targetX + targetLength, x, x + sideLength)) {
if (isWithin(targetY, y, y + sideLength) || isWithin(targetY + targetLength, y, y + sideLength)) {
/*respawn target in a random location*/
moveTarget();
/*Increase score by 1*/
score++;
}
}
//Draw player object
context.fillRect(x, y, sideLength, sideLength);
context.drawImage(baseImage, x, y, sideLength, sideLength);
/*Draw target sqaure*/
context.fillStyle = '#00FF00';
context.fillRect(targetX, targetY, targetLength, targetLength);
//Timer and Score
context.fillStyle = '#000000';
context.font = '24px Arial';
context.textAlign = 'left';
context.fillText('Score: ' + score, 10, 24);
context.fillText('Time Remaining: ' + countDown, 10, 50);
if (countDown <= 0) {
endGame();
} else {
window.requestAnimationFrame(draw);
}
}
baseImage= new Image();
baseImage.src='xwing3.png';
baseImage.onload= function() {
menu();
}
canvas.focus();
I think in this regard you have two options.
You could have a sprite for every direction that you want the ship to face, then when you draw the image, you could choose the sprite that matches.
if(left == true) {baseImage.src='xwing3left.png';}
You could use the canvas rotate() method. This would make things more complicated, but it actually rotates the canvas and could give more opportunity to experiment.
It actually applies a transformation matrix to the canvas before it draws so you could do things like:
context.rotate(45);
context.fillRect(x,y,width,height);
Just be careful, because rotate always occurs around the origin, so you might need to use translate() as well to make it work the way you expect.
Hope this helps! :)
I am trying to create a scoreboard for my game by using local storage to carry over the score variable after a game is finished by a user. However, this is not working for some reason. I am relatively new to coding so I did some research on local storage but couldn't get the code to work to no avail. Could someone help me with this code thanks.
Page 1:
<html>
<title>Level Selector</title>
<canvas id="myCanvas" width="750" height="400"></canvas>
<style type="text/css">
canvas { background: #eee; }
</style>
<script>
document.addEventListener('load', draw);
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;//Ball is moving in x direction at a constant rate
var dy = -2;//Ball is moving in y direction at a constant rate
var ballRadius = 10;//To see if ball is colliding with brick/canvas
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;//This variable is false because the 'right arrow' key is not pressed.
var leftPressed = false;//This variable is false because the 'left arrow' key is not pressed.
var brickRowCount = 5;
var brickColumnCount = 8;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;
var paused = false;
var bricks = [];//this is an array holding all the bricks
for(var c=0; c<brickColumnCount; c++) {
bricks[c] = [];
for(var r=0; r<brickRowCount; r++) {
bricks[c][r] = { x: 0, y: 0, status: 1 };//If status is '1' then draw it. However, is status is '0', fill in with background
}
}
document.addEventListener("keydown", keyDownHandler, false);//Functions only when key is pressed
document.addEventListener("keyup", keyUpHandler, false);//Functions only when key is not pressed
document.addEventListener("mousemove", mouseMoveHandler, false);//Functions only when mouse curcor moves
//keyCode(39) is the code for the 'right arrow' key and keyCode(37) is the code for the 'left arrow' key
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 mouseMoveHandler(e) {
var relativeX = e.clientX - canvas.offsetLeft;//This represents the hoizontal mouse movement.
if(relativeX > 0 && relativeX < canvas.width) {
paddleX = relativeX - paddleWidth/2;
}
}
window.addEventListener('keydown', pauseGameKeyHandler, false);
function pauseGameKeyHandler(e) {
var keyCode = e.keyCode;
switch(keyCode){
case 80: //p
togglePause();
break;
}
}
function togglePause() {
paused = !paused;
draw();
}
/*************************************************************/
// NEW
const ballPowerupHalfWidth = 30;
const paddlePowerupHalfWidth = 30;
let ballPowerups = [];
let paddlePowerups = [];
// This function adds powerup to random position
function addPowerups() {
// I check only if none exist, you could
// add more than 1 powerup if you want
if (ballPowerups.length < 1) {
// otherwise half the triangle could be outside canvas
const padding = 50;
const xMin = 0 + padding;
const xMax = canvas.width - padding;
const yMin = 0 + padding;
const yMax = canvas.height - padding;
ballPowerups.push({
x: Math.floor(Math.random()*(xMax-xMin+1)+xMin),
y: Math.floor(Math.random()*(yMax-yMin+1)+yMin),
});
}
// I check only if none exist, you could
// add more than 1 powerup if you want
if (paddlePowerups.length < 1) {
// otherwise half the triangle could be outside canvas
const padding = 50;
const xMin = 0 + padding;
const xMax = canvas.width - padding;
const yMin = 0 + padding;
const yMax = canvas.height - padding;
paddlePowerups.push({
x: Math.floor(Math.random()*(xMax-xMin+1)+xMin),
y: Math.floor(Math.random()*(yMax-yMin+1)+yMin),
});
}
}
// NEW: do all collision detections
function doCollisionDetection() {
// ball powerups
ballPowerups.forEach((powerup, i) => {
rectangleCollisionDetection(
{x: powerup.x, y: powerup.y},
{w: ballPowerupHalfWidth, h: ballPowerupHalfWidth},
() => {
console.log('BALL POWERUP COLLISION');
// remove powerup
ballPowerups.splice(i, 1);
dy = dy/2
setTimeout(() => { dy=2 }, 5000)
// to make effect last 10 seconds:
// 1. add effect
// 2. and setTimeout(() => { /* code that removes effect */ }, 10000);
});
});
// paddle powerups
paddlePowerups.forEach((powerup, i) => {
rectangleCollisionDetection(
{x: powerup.x, y: powerup.y},
{w: ballPowerupHalfWidth, h: ballPowerupHalfWidth},
() => {
console.log('PADDLE POWERUP COLLISION');
// remove powerup
paddlePowerups.splice(i, 1);
paddleHeight = paddleHeight*1.5
paddleWidth = paddleWidth*1.5
setTimeout(() => { paddleHeight=10; }, 10000)
});
});
// bricks
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
var b = bricks[c][r];
if(b.status == 1) {
rectangleCollisionDetection(b, {w: brickWidth, h: brickHeight}, () => {
console.log('BRICK COLLISION');
dy = -dy;
b.status = 0;
score++;
if(score == brickRowCount*brickColumnCount) {
alert("YOU WIN, CONGRATULATIONS!");
window.location = "Intro Screen.html";
}
});
}
}
}
// NEW: collision detection between ball and rectangle shaped
// collision boundary (only need center(x, y) and half width)
function rectangleCollisionDetection(center, size, callback) {
if(
x > center.x &&
x < center.x+size.w &&
y > center.y &&
y < center.y+size.h
) {
callback && callback();
}
}
function drawBallpowerup() {
ballPowerups.forEach(powerup => {
ctx.beginPath();
ctx.moveTo(powerup.x, powerup.y);
ctx.lineTo(powerup.x+ballPowerupHalfWidth, powerup.y+ballPowerupHalfWidth);
ctx.lineTo(powerup.x+ballPowerupHalfWidth*2, powerup.y);
ctx.fillStyle = "#42f445";
ctx.fill();
ctx.closePath();
});
}
function drawPaddlepowerup() {
paddlePowerups.forEach(powerup => {
ctx.beginPath();
ctx.moveTo(powerup.x, powerup.y);
ctx.lineTo(powerup.x+paddlePowerupHalfWidth, powerup.y+paddlePowerupHalfWidth);
ctx.lineTo(powerup.x+paddlePowerupHalfWidth*2, powerup.y);
ctx.fillStyle = "#ce6210";
ctx.fill();
ctx.closePath();
});
}
// my big changes end here
/*************************************************************/
//this is the score variable of the game
function drawScore() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Score: "+score, 8, 20);
}
//this is the lives variable of the game
function drawLives() {
ctx.font = "16px Arial";
ctx.fillStyle = "#0095DD";
ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}
//this creates the ball
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the paddle
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
//this creates the bricks
function drawBricks() {
for(var c=0; c<brickColumnCount; c++) {
for(var r=0; r<brickRowCount; r++) {
if(bricks[c][r].status == 1) {
var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
var brickY = (r*(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 draw() {
// clears canvas content from previous frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();//this code draws the ball onto the canvas
drawPaddle();//this code draws the paddle onto the canvas
drawBricks();//this code draws the bricks onto the canvas
addPowerups();
doCollisionDetection();
drawScore();//this code draws the score variable onto the canvas
drawLives();//this code draws the lives variable onto the canvas
drawBallpowerup();
drawPaddlepowerup();
//Reverse Ball movement when the ball collides with wall in 'x' direction (Left/Right wall)
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
//Reverse Ball movement when the ball collides with wall in 'y' direction (Top/Bottom wall)
if(y + dy < ballRadius) {
dy = -dy;
} else if(y + dy > canvas.height-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;//If the ball collides with the paddle, the ball is rebounded in the opposite direction.
}
else {
lives--;
if(!lives) {
alert("GAME OVER");
localStorage.setItem("score", score);
}
window.location = "Intro Screen.html";
}
else {
x = canvas.width/2;
y = canvas.height-30;
dx = 2;
dy = -2;
paddleX = (canvas.width-paddleWidth)/2;
}
}
}
if(rightPressed && paddleX < canvas.width-paddleWidth) {//limits paddle movement in between the canvas width
paddleX += 7;//Paddle shifts 7 pixels in the positive x direction
}
else if(leftPressed && paddleX > 0) {//limits paddle movement in between the canvas width
paddleX -= 7;//Paddle shifts 7 pixels in the negative x direction
}
x += dx;//Ball is updated by painting it over each position it moves in
y += dy;//Ball is updated by painting it over each position it moves in
if(!paused) {
requestAnimationFrame(draw);
}
}
draw();
</script>
<body onload="draw();>
</body>
</html>
Page 2:
if (typeof(Storage) !== "undefined") {
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("score"));
}
When I run it and after playing the game, the score should be added onto the scoreboard in decending order (highest to lowest). I have trouble bringing over the variable.
While there are no standard specifications about it, most browsers will consider different pages served from the file:// protocol as being different-origin.
This means your two pages will be considered as different-origin and will thus have their own Storage Area that they won't be able to share, just like you won't be able to access the Storage Area from www.xxxxx.com from www.yyyyy.com.
To overcome this limitation, the easiest is to run a local web-server on your machine. Many OSes comes with preinstalled such server, and all it requires is to activate it, and for the ones that don't do it, there are many free and easy solutions.
And if you are planning to play with web standards, it's a must have anyway.
This is my first post so I hope that I put everything correctly down below here! :-P
I have a problem. Currently I'm making a snake game with a school friend of mine. We are making a snake game by using node.js so we can create a multiplayer snake game. Nothing really extreme just the basic snake game but then with more players.
Currently I've created a code that can move the snake and also will place food randomly on the canvas (I'm using the HTML5 Canvas element in which the game is played).
Now I'm stuck because I want to create a function that allows the snake to eat the food and then grow longer. As far as I know I have the function as it should be, but for some reason it does not work. My knowledge of javascript is very basic so what I'm doing here is all new for me. I will put the entire code down below so you can see it through.
I've created 2 javascript files. one that has the snake code in it and the other has the food code in it. The function that I'm referring about is inside the Snake script under Snake.prototype.move
I really hope that someone can help me out so I can proceed with our game.
This is the main code (Snake code):
var game;
$(document).ready(function(){
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var cw = 10;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);
var GameObject = function() {
this.snakes = [];
this.foods = [];
}
game = new GameObject();
var snake = new Snake(1, 15, 'testnaam');
snake.create();
game.snakes.push(snake);
game.foods.push(new Food(w, cw));
function loop() {
window.setTimeout(loop, 60);
ctx.clearRect(0, 0, w, h);
if(game.snakes.lenght !== 0) {
for(i = 0; i < game.snakes.length; i++) {
var s = game.snakes[i];
s.paint(ctx, game);
}
} else {
}
if(game.foods.length !== 0) {
for(var i = 0; i < game.foods.length; i++) {
var f = game.foods[i];
f.paint(ctx);
}
} else {
}
}
loop();
document.addEventListener('keydown', function(e) {
e.preventDefault();
var key = e.which;
if(key == "37" && snake.direction !="right") snake.direction = "left";
else if(key == "38" && snake.direction !="down") snake.direction = "up";
else if(key == "39" && snake.direction !="left") snake.direction = "right";
else if(key == "40" && snake.direction !="up") snake.direction = "down";
}, false);
});
var Snake = function(player, length, alias){
this.length = length;
this.pieces = [];
this.player = player;
this.position = {x: 0, y: 0};
this.direction = "right";
this.color = this.color();
this.getName = alias;
}
Snake.prototype.create = function(){
for(var i = this.length -1; i >= 0; i--) {
this.pieces.push({x: i, y: 0});
}
};
Snake.prototype.paint = function(ctx, game){
this.move(game);
for(var i = 0; i < this.pieces.length; i++){
var c = this.pieces[i];
ctx.fillStyle = this.color;
ctx.fillRect(c.x*10, c.y*10, 10, 10);
}
};
Snake.prototype.color = function(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
};
Snake.prototype.getName = function() {
return this.alias;
}
Snake.prototype.getPosition = function() {
return {x: this.x, y: this.y }
}
Snake.prototype.move = function(game) {
var nx = this.pieces[0].x;
var ny = this.pieces[0].y;
if(this.direction == "right")nx++;
else if(this.direction == "left")nx--;
else if(this.direction == "up")ny--;
else if(this.direction == "down")ny++;
if(Snake == game.foods[0].position.x && Snake == game.foods[0].position.y){
console.log("raak");
var tail = {
x: nx,
y: ny
};
Food.create();
} else{
var tail = this.pieces.pop();
tail.x = nx;
tail.y = ny;
}
this.pieces.unshift(tail);
};
Snake.prototype.collision = function(x, y, array){
for(var i = 0; i < array.length; i++){
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
};
And This is the code for the food
var Food = function(w, cw){
this.w = w;
this.cw = cw;
this.position = this.create();
console.log(this.position);
};
Food.prototype.create = function(){
var min = 0;
var max = (this.w/this.cw);
return position = {
x: Math.round(min + Math.random()* (Math.abs(min)+(max)))*this.cw,
y: Math.round(min + Math.random()* (Math.abs(min)+(max)))*this.cw
}
};
Food.prototype.paint = function(ctx){
ctx.fillStyle = "#000";
ctx.fillRect(this.position.x,this.position.y,10,10)
};
Thank you very much!
Live demo
I had to fiddle with it a lot.. there is a lot of weirdness going on in the code, but this is the area I messed with primarily to get it working.
Snake.prototype.move = function (game) {
var nx = this.pieces[0].x;
var ny = this.pieces[0].y;
if (this.direction == "right") nx++;
else if (this.direction == "left") nx--;
else if (this.direction == "up") ny--;
else if (this.direction == "down") ny++;
/*
* you werent testing the front pieces x and y, also since your multiplying the snake
* pieces by 10, you need to divide the food positions by 10 for the coords to match up
*/
if (this.pieces[0].x == game.foods[0].position.x / 10 && this.pieces[0].y == game.foods[0].position.y / 10) {
console.log("raak");
var tail = {
x: nx,
y: ny
};
// push your piece
this.pieces.push(tail);
// you have an array for prob to eventually have more than one on the screen.
// for now i set food[0] to be a new piece of food. We dont have ref's to w and cw in this
// func to I passed in the values.
game.foods[0] = new Food(canvas.width, 10);
} else {
var tail = this.pieces.pop();
tail.x = nx;
tail.y = ny;
// only unshift when we havent added a piece
this.pieces.unshift(tail);
}
};
Basically you weren't testing the positions at all and you werent dividing the foods position by 10 when checking so the snake's position could never match the foods.