HTML5 Javascript game - javascript

I'm trying to make a HTML5 game in javascript. Similar to pong, but once the bubble hits the paddle or bottom screen it "bursts" or disappears. I cant seem to get the Bubble to disappear or burst in my code. Could anyone help me?
var canvasColor;
var x,y,radius,color;
var x=50, y=30
var bubbles=[];
var counter;
var lastBubble=0;
var steps=0, burst=0, escaped=0;
var batonMovement = 200;
var moveBatonRight = false;
var moveBatonLeft = false;
function startGame()
{
var r,g,b;
var canvas,color;
//Initialize
canvasColor = '#EAEDDC';
x = 10;
y = 10;
radius = 10;
clearScreen();
counter=0;
while (counter <100)
{
//make bubble appear randomly
x=Math.floor(Math.random()*450)
//Set up a random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
color='rgb('+r+','+g+','+b+')';
bubbles[counter] = new Bubble(x,y,radius,color);
counter+=1;
}
setInterval('drawForever()',50);
}
function Bubble (x,y,radius,color)
{
this.x=x;
this.y=y;
this.radius=radius;
this.color=color;
this.active=false;
}
function drawForever()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps +=1
clearScreen();
if (steps%20==0 && lastBubble < 100){
bubbles[lastBubble].active=true;
lastBubble +=1;
}
drawBaton();
counter=0;
while (counter <100)
{
if (bubbles[counter].active==true){
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2*Math.PI);
pen.fill();
bubbles[counter].y+=2;
}
if (y>=240 && y<=270 && x>=batonMovement-10 && x<=batonMovement+60)
{
bubbles[lastBubble]=false;
}
else if (y>=450)
{
bubbles[lastBubble]=false;
}
counter +=1;
}
}
function clearScreen()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = canvasColor;
pen.fillRect(0,0,450,300);
}
function drawBaton()
{
var canvas, pen;
if (moveBatonLeft == true && batonMovement > 0)
{
batonMovement -= 20;
}
else if (moveBatonRight == true && batonMovement < 400)
{
batonMovement += 20;
}
//draw Baton (rectangle)
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = '#0000FF';
pen.fillRect(batonMovement,250,50,10);
}
function moveLeft()
{
moveBatonLeft=true;
}
function moveRight()
{
moveBatonRight=true;
}
function stopMove()
{
moveBatonLeft=false;
moveBatonRight=false;
}
Below is the HTML code...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bubble Burster</title>
<script type="text/javascript" src="project.js"></script>
</head>
<body onload="startGame();">
<div style="text-align:center;">
<h2>Bubble Burster</h2>
<canvas id="myCanvas" width="450" height="300" style="border:5px solid #000000; background-color: #f1f1f1;">
Your browser does not support the canvas element.
</canvas><br>
<button onmousedown="moveLeft();" onmouseup="stopMove();">LEFT</button>
<button onmousedown="moveRight();" onmouseup="stopMove();">RIGHT</button><br><br>
<form>
<input type="radio" name="difficulty" value="easy" onclick="check(this.value);" checked> Easy
<input type="radio" name="difficulty" value="moderate" onclick="check(this.value)"> Moderate
<input type="radio" name="difficulty" value="hard" onclick="check(this.value)"> Hard <br><br>
</form>
<span id="burst">Burst:</span>
<span id="escaped">Escaped: </span>
<span id="steps">Steps elapsed:</span>
<h3 id="output"></h3>
</div>
</body>
</html>

You are referring to x, y which are not defined in the drawForever function. The global values of x and y may not refer to the right bubble. In fact y is set to 10 in the startGame function and never altered subsequently. You also probably want to refer to bubbles[counter] rather than bubbles[lastBubble]. The game seems to work if you make the changes below, referring to bubbles[counter].x and bubbles[counter].y instead of x and y.
function drawForever() {
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps += 1
clearScreen();
if (steps % 20 == 0 && lastBubble < 100) {
bubbles[lastBubble].active = true;
lastBubble += 1;
}
drawBaton();
counter = 0;
while (counter < 100) {
if (bubbles[counter].active == true) {
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2 * Math.PI);
pen.fill();
bubbles[counter].y += 2;
}
y = bubbles[counter].y; // ADDED (y was not defined in original code)
x = bubbles[counter].x; // ADDED (x was not defined in original code)
if (y >= 240 && y <= 270 && x >= batonMovement - 10 && x <= batonMovement + 60) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
} else if (y >= 450) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
}
counter += 1;
}
}
https://jsfiddle.net/acLot87q/4/
You should also make x and y local variables within each function; they are not currently serving the purpose that you seem to think.

Related

My javascript doesn't give any output and when i reload the page it crashes

This is my code and when run instead of a black box containing my game in the centre of the screen there is just a gap and no website can seem to tell me where I went wrong:
console.log("start")
//Global functions
var canvas = document.getElementById("canva");
var canvasCon;
var snakeX = 400;
var snakeY = 300;
var direction;
var snakeSpeed = 1;
var apple = false;
var appleX;
var appleY
var snakeSize = 30;
var scoreboard = document.getElementById("score");
var Score = 0;
var trailX = new Array();
var trailY = new Array();
console.log("set global variables!")
window.onload = function(){
console.log("ran on window load function")
canvasCon = canvas.getContext('2d');
//Calls "drawing" and "move" fps times per second
var fps = 30
setInterval(function(){
move()
drawing()
},1000/fps);
}
document.addEventListener('keydown', getKey);
function getKey(event){
//gets the keycode
direction = event.keyCode;
return direction;
}
//moves the objsects
function move(){
//creates a easier to read way to check the value of getKey
var left = 37;
var up = 38;
var right = 39;
var down = 40;
//changing the position of the snake
switch(direction){
case right:
snakeX = snakeX + snakeSpeed;
break;
case left:
snakeX = snakeX - snakeSpeed;
break;
case up:
snakeY = snakeY - snakeSpeed;
break;
case down:
snakeY = snakeY + snakeSpeed;
break;
}
trail()
//checks if snake has gone off the board and then moves the snake to the other end of the board if that returns True
if(snakeX > canvas.width){
snakeX = 0
}else if(snakeX < 0){
snakeX = canvas.width
}
if(snakeY > canvas.height){
snakeY = 0
}else if(snakeY < 0){
snakeY = canvas.height
}
}
//draws everything /w updated coordinates
function drawing(){
//Backround of the Game
canvasCon.fillStyle = 'black';
canvasCon.fillRect(0,0,canvas.width,canvas.height);
//The snake
canvasCon.fillStyle = 'green';
canvasCon.fillRect(snakeX,snakeY,snakeSize,snakeSize);
//apple creation
apples()
canvasCon.fillStyle = 'red';
canvasCon.fillRect(appleX,appleY,25,25);
}
//makes the apples work
function apples(){
if(collision()){
Score += 1
console.log(Score)
scoreboard.innerHTML = "<b>Score: "+Score+"<b>"
apple = false
}
if(apple == false){
apple = true
appleX = Math.floor(Math.random() * (canvas.width - 50));
appleY = Math.floor(Math.random() * (canvas.height - 50));
}
}
function collision(){
var distX = Math.abs(appleX - snakeX-snakeSize/2);
var distY = Math.abs(appleY - snakeY-snakeSize/2);
if (distX <= (snakeSize/2) && distY <= (snakeSize/2)) { return true; }
}
function trail(){
//adds X and Y coordinates to their respective lists
trailX.push(snakeX)
trailY.push(snakeY)
//makes sure the lists are the right length
while(trailX.length > Score){
var index = trailX.indexOf(0);
trailX.splice(index, 1);
}
while(trailY.length > Score){
var index = trailY.indexOf(0);
trailY.splice(index, 1);
}
if(trailY.length != trailX.length){
console.log("trailY != trailX")
}
for(i= trailX.length-1; i<=0; i--){
canvasCon.fillStyle = 'yellow';
canvasCon.fillRect(trailX[i],trailY[i],25,25);
}
}
<title>SNAKE!!</title>
<body>
<p style="text-align:center; text-color:red"><b>Hope you Enjoy Ma GREAT GAME!!</b></p>
<br/><br/><br/>
<div style="width:800px; margin:0 auto;">
<canvas id=canva width="800" height="600"></canvas>
<br/>
<p id="score">Score: </p>
</div>
</body>
whenever the page gets reloaded even on jsfiddle.net it crashes.
plz help I have no idea what i did wrong!
First rule of JS - if it is stuck, you probably have an endless loop.
And indeed You have an endless loop with your final for:
for(i= trailX.length-1; i<=0; i--){
canvasCon.fillStyle = 'yellow';
canvasCon.fillRect(trailX[i],trailY[i],25,25);
}
i<=0
If i start with 0 and goes down by 1 each iteration, it will always be less or equal to 0 so the end condition will never be met.

HTML Canvas & Javascript - Hover and Click Events

Below is a script which defines two functions that draw 4 rectangular buttons and 1 circular button respectively. I am trying to implement specific Hover and Click functionality into the buttons (as described in the script alerts) but I am at a bit of a loss as to how to do this. I tried calling the makeInteractiveButton() functions on each click but this caused a lot of odd overlap and lag. I want the script to do the following:
If the circular button is hovered, I would like it's fillColour to change and if it is clicked I would like it to change again to the colours described in the code (#FFC77E for hover, #FFDDB0 for clicked). This should only happen for the duration of the hover or click.
HTML:
<html lang="en">
<body>
<canvas id="game" width = "750" height = "500"></canvas>
<script type='text/javascript' src='stack.js'></script>
</body>
</html>
JavaScript:
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d')
elements = [];
c.style.background = 'grey';
function makeInteractiveButton(x, strokeColor, fillColor) {
ctx.strokeStyle=strokeColor;
ctx.fillStyle=fillColor;
ctx.beginPath();
ctx.lineWidth=6;
ctx.arc(x, 475, 20, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
elements.push({
arcX: x,
arcY: 475,
arcRadius: 20
});
}
b1 = makeInteractiveButton(235, '#FFFCF8', '#FFB85D');
c.addEventListener('mousemove', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if cursor in rect
alert('Rectangle should undergo 5 degree rotation and 105% scale');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if cursor in circle
alert('Set b1 fillColour to #FFC77E.');
}
});
}, false);
c.addEventListener('click', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if rect clicked
alert('Move all cards to centre simultaneously.');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if circle clicked
alert('Set b1 fillColour to #FFDDB0.');
}
});
}, false);
One way is keep all element data and write a hitTest(x,y) function but when you have a lot of complex shapes its better to use a secondary canvas to render element with their ID instead of their color in it and the color of x,y in second canvas is ID of hitted element, I should mention that the second canvas is'nt visible and its just a gelper for get the hitted element.
Github Sample:
https://siamandmaroufi.github.io/CanvasElement/
Simple implementation of hitTest for Rectangles :
var Rectangle = function(id,x,y,width,height,color){
this.id = id;
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.color = color || '#7cf';
this.selected = false;
}
Rectangle.prototype.draw = function(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
if(this.selected){
ctx.strokeStyle='red';
ctx.setLineDash([5,5]);
ctx.lineWidth = 5;
ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
Rectangle.prototype.hitTest=function(x,y){
return (x >= this.x) && (x <= (this.width+this.x)) &&
(y >= this.y) && (y <= (this.height+this.y));
}
var Paint = function(el) {
this.element = el;
this.shapes = [];
}
Paint.prototype.addShape = function(shape){
this.shapes.push(shape);
}
Paint.prototype.render = function(){
//clear the canvas
this.element.width = this.element.width;
var ctx = this.element.getContext('2d');
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].draw(ctx);
}
}
Paint.prototype.setSelected = function(shape){
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].selected = this.shapes[i]==shape;
}
this.render();
}
Paint.prototype.select = function(x,y){
for(var i=this.shapes.length-1;i>=0;i--){
if(this.shapes[i].hitTest(x,y)){
return this.shapes[i];
}
}
return null;
}
var el = document.getElementById('panel');
var paint = new Paint(el);
var rectA = new Rectangle('A',10,10,150,90,'yellow');
var rectB = new Rectangle('B',150,90,140,100,'green');
var rectC = new Rectangle('C',70,85,200,70,'rgba(0,0,0,.5)');
paint.addShape(rectA);
paint.addShape(rectB);
paint.addShape(rectC);
paint.render();
function panel_mouseUp(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
if(shape){
alert(shape.id);
}
//console.log('selected shape :',shape);
}
function panel_mouseMove(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
paint.setSelected(shape);
}
el.addEventListener('mouseup',panel_mouseUp);
el.addEventListener('mousemove',panel_mouseMove);
body {background:#e6e6e6;}
#panel {
border:solid thin #ccc;
background:#fff;
margin:0 auto;
display:block;
}
<canvas id="panel" width="400px" height="200px" >
</canvas>
just click or move over the shapes

Finding Value in an Indexed array

I have created a function that checks a nested array to see whether an input is valid. For the input to be valid it cannot have the same name twice in the array. Arr[i][0] contains the name of the crop.
function checkList(arr,cropName) {
for (i = 0; i < 32; i++) {
if (arr[i][0] == cropName){
console.log("Name in Array")
return true;
} else {
console.log("Name not in Array")
return false;
}
}
}
for some reason this algorithm doesn't work, but i'm sure it should, any help is appreciated. I have set up a JS fiddle so you can look at it if needed.
https://jsfiddle.net/qdzvr6z1/
You're returning on the first iteration so you're only checking index 0.
Try
function checkList(arr,cropName) {
for (i = 0; i < 32; i++) {
if (arr[i][0] == cropName){
console.log("Name in Array")
return true;
}
}
console.log("Name not in Array")
return false;
}
=== UPDATED ANSWER ===
If this is useful, please vote up my answer. :)
To share some ideas on how you can clean up some code (there would be more to do, but I need to stop to get back to my work), I refactored and enhanced your solution.
Give it a try here Fiddle
html:
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;"></canvas><br>
<input type="color" id="currentColour" value="#ff0000">
<input type="text" id="cropName" placeholder="Please enter a color name"><br>
Mode:<br>
<div style="margin-left: 20px;">
<input type="radio" id="modeAdd" name="mode" value="add" checked>Add</input><br>
<input type="radio" id="modeClear" name="mode" value="clear">Clear</input>
</div>
<div>
<p>Hover over a cell to see the values here:</p>
<div style="margin-left: 20px;">
Name: <input type="text" id="hoverName" /><br>
Colour: <input type="text" id="hoverColour" />
</div>
</div>
script:
const defaultColour = "#ffffff";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var numColours = 32;
var colours = initialiseArray(numColours, defaultColour);
function initialiseArray(qty, defaultColour) {
var arr = [];
for (i = 0; i < qty; i++) {
arr.push({
name: "",
colour: defaultColour
});
};
return arr
};
//DRAW GRID
function drawGrid() {
var step;
ctx.setTransform(1, 0, 0, 1, 0.5, 0.5);
ctx.beginPath();
//Draw Vertical Lines
for (step = 50; step < 400; step += 50) {
ctx.moveTo(step, 0);
ctx.lineTo(step, 200);
}
//Draw Horizontal Lines
for (step = 50; step < 200; step += 50) {
ctx.moveTo(0, step);
ctx.lineTo(400, step);
//Draw Dividers
ctx.moveTo(200.5, 0);
ctx.lineTo(200.5, 200);
ctx.moveTo(0, 100.5);
ctx.lineTo(400, 100.5);
}
ctx.stroke();
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
//GET MOUSE COORDINATES ON CANVAS
function getMousePos(canvas, evt) {
var rect = c.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function isColourNameProvided(name) {
if (name) return true
else return false;
}
// looks through an array of colour objects and returns true if the same name AND colour value combo exists
function isDuplicateNameAndColourValue(newColourName, newColourValue) {
return colours.some( c => c.name === newColourName && c.colour === newColourValue);
}
function isUserInputValid(arr, cropName, cropColour) {
if (!isColourNameProvided(cropName)) {
alert("Please set a name for the colour.");
return false;
}
// Check to see if the combination of name and colour value already exists in the palette
if (isDuplicateNameAndColourValue(cropName, cropColour)) {
alert("That combination of NAME and COLOUR VALUE already exists in the palette.");
return false;
}
return true;
}
function getMode() {
var radios = document.getElementsByName("mode");
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) return radios[i].value;
}
return null;
}
function updatePalette(event) {
var cropName;
var cropColour;
var mousePos = getMousePos(c, event);
var xPos = Math.floor(mousePos.x / 50) * 50 + 1;
var yPos = Math.floor(mousePos.y / 50) * 50 + 1;
var width = 49;
var height = 49;
var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)
switch (getMode().toUpperCase()) {
case "ADD":
cropName = document.getElementById("cropName").value;
cropColour = document.getElementById("currentColour").value;
if (isUserInputValid(colours, cropName, cropColour)) {
updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
}
break;
case "CLEAR":
cropName = "";
cropColour = defaultColour;
updatePaletteCell(cellNum, cropName, cropColour, xPos, yPos, width, height);
break;
default:
alert("Unable to determine the mode.");
break;
}
}
function updatePaletteCell(cellNum, colourName, colourValue, xPos, yPos, width, height) {
// paint the cell
ctx.fillStyle = colourValue;
ctx.fillRect(xPos, yPos, width, height);
// store values for the cell
colours[cellNum].name = colourName;
colours[cellNum].colour = colourValue;
}
function showColourInfo(event) {
var mousePos = getMousePos(c, event);
var cellNum = Math.floor(mousePos.y / 50) * 8 + Math.floor(mousePos.x / 50)
crop = colours[cellNum];
if (crop) {
document.getElementById("hoverName").value = crop.name;
document.getElementById("hoverColour").value = crop.colour;
}
}
c.addEventListener('mousemove', showColourInfo, false);
c.addEventListener('click', updatePalette, false);
drawGrid();
=== ORIGINAL ANSWER ===
The answer Daniel gave is correct, but I think it's better refactored to be like this:
function checkList(arr,cropName) {
var result = arr.some(x => {
return (x[0] === cropName);
});
console.log("Duplicate found = ", result);
return result;
}
Note: This (and the one you posted) will return true in your fiddle right now because you aren't checking before you update the cell, so it will always be found.
Another quick tip:
if (checkInput != false) is commonly done like this: if (checkInput), as this returns true for all values except: false, 0, "", null, undefined, and NaN

Snake Game with Controller Buttons for Mobile Use **UPDATED**

** NOTE: I've Edited the javascript below and linked to a new JSFiddle but still not getting the buttons to control the snake's movement like the arrow keys on the keyboard **
I’m trying to create a real easy snake game for project but need it to have buttons so the game will work on mobile. This is almost there except i need to have the buttons control the movement of the snake on screen:
HTML:
<div class="game-container">
<div class="container">
<div class="SplashScreen">
<h1>
Snake
</h1>
<h2>
Click To Start.
</h2>
<input class="StartButton" type="button" value="Start" />
</div>
<div class="FinishScreen" style="display:none">
<h1>
Game Over
</h1>
<p>
Your score was: <span id="score"></span>
</p>
<input class="StartButton" type="button" value="Restart" />
</div>
<canvas id="canvasArea" width="450" height="450" style="display:none;"></canvas>
</div>
<div class="button-pad">
<div class="btn-up">
<button type="submit" class="up">
<img src="http://aaronblomberg.com/sites/ez/images/btn-up.png" />
</button>
</div>
<div class="btn-right">
<button type="submit" class="right">
<img src="http://aaronblomberg.com/sites/ez/images/btn-right.png" />
</button>
</div>
<div class="btn-down">
<button type="submit" class="down">
<img src="http://aaronblomberg.com/sites/ez/images/btn-down.png" />
</button>
</div>
<div class="btn-left">
<button type="submit" class="left">
<img src="http://aaronblomberg.com/sites/ez/images/btn-left.png" />
</button>
</div>
</div>
jQuery:
( function( $ ) {
$( function() {
$(document).ready(function () {
$(".StartButton").click(function () {
$(".SplashScreen").hide();
$(".FinishScreen").hide();
$("#canvasArea").show();
init();
});
//Canvas stuff
var canvas = $("#canvasArea")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvasArea").width();
var h = $("#canvasArea").height();
//Lets save the cell width in a variable for easy control
var sw = 10;
var direction;
var nd;
var food;
var score;
//Lets create the snake now
var snake_array; //an array of cells to make up the snake
function endGame() {
$("#canvasArea").hide();
$("#score").text(score);
$(".FinishScreen").show();
}
function init() {
direction = "right"; //default direction
nd = [];
create_snake();
create_food(); //Now we can see the food particle
//finally lets display the score
score = 0;
//Lets move the snake now using a timer which will trigger the paint function
//every 60ms
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
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 - sw) / sw),
y: Math.round(Math.random() * (h - sw) / sw),
};
//This will create a cell with x/y between 0-44
//Because there are 45(450/10) positions accross the rows and columns
}
//Lets paint the snake now
function paint() {
if (nd.length) {
direction = nd.shift();
}
//To avoid the snake trail we need to paint the BG on every frame
//Lets paint the canvas now
ctx.fillStyle = "#0056a0";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "#ffffff";
ctx.strokeRect(0, 0, w, h);
//The movement code for the snake to come here.
//The logic is simple
//Pop out the tail cell and place it infront of the head cell
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//These were the position of the head cell.
//We will increment it to get the new head position
//Lets add proper direction based movement now
if (direction == "right") nx++;
else if (direction == "left") nx--;
else if (direction == "up") ny--;
else if (direction == "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 body collision
//Now if the head of the snake bumps into its body, the game will restart
if (nx == -1 || nx == w / sw || ny == -1 || ny == h / sw || check_collision(nx, ny, snake_array)) {
//end game
return endGame();
}
//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++;
//Create new food
create_food();
} 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 back 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 score
var score_text = "Score: " + score;
ctx.fillStyle = "#ffffff";
ctx.fillText(score_text, 5, h - 5);
//Set the font and font size
ctx.font = '12px Arial';
//position of the fill text counter
ctx.fillText(itemCounter, 10, 10);
}
//Lets first create a generic function to paint cells
function paint_cell(x, y) {
ctx.fillStyle = "#d8d8d8";
ctx.fillRect(x * sw, y * sw, sw, sw);
}
function check_collision(x, y, array) {
//This function will check if 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 prevent the default browser action with arrow key usage
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.keyCode] = true;
switch(e.keyCode){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.keyCode] = false;
},
false);
//Lets add the keyboard controls now
$(document).keydown(function (e) {
var key = e.which;
var td;
if (nd.length) {
var td = nd[nd.length - 1];
} else {
td = direction;
}
//We will add another clause to prevent reverse gear
if (key == "37" && td != "right") nd.push("left");
else if (key == "38" && td != "down") nd.push("up");
else if (key == "39" && td != "left") nd.push("right");
else if (key == "40" && td != "up") nd.push("down");
//The snake is now keyboard controllable
});
});
$(document).on('click', '.button-pad > button', function(e) {
if ($(this).hasClass('left-btn')) {
e = 37;
}
else if ($(this).hasClass('up-btn')) {
e = 38;
}
else if ($(this).hasClass('right-btn')) {
e = 39;
}
else if ($(this).hasClass('down-btn')) {
e = 40;
}
$.Event("keydown", {keyCode: e});
});
});
})( jQuery );
JSFiddle
http://jsfiddle.net/aaronblomberg/9w3gk3ma/3/
This is ALMOST where i need it but i need the up, down, left, and right arrow buttons to control the snake...
any help with would be greatly greatly appreciated.
You cold make something like this:
var isMobile;
checkMobile = function() {
if ($(window).width() <= 766) {
isMobile = true;
}
else {
isMobile = false;
}
}
$(window).resize(checkMobile());
$(document).ready(checkMobile());
if (isMobile) {
$('.button-pad').show();
}
else {
$('.button-pad').hide();
}
.button-pad:
$(document).on('click', '.button-pad > button', function(e) {
if ($(this).hasClass('left')) {
e = 37;
}
else if ($(this).hasClass('up')) {
e = 38;
}
else if ($(this).hasClass('right')) {
e = 39;
}
else if ($(this).hasClass('down')) {
e = 40;
}
$.Event("keydown", {keyCode: e});
}
Here is the code to add moile control to the snake game;
(If you want the whole code for the snake game please comment);
//Here is javascript;
// left key
function l() {
if(snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
}
}
// up key
function u() {
if(snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
}
}
// right key
function r() {
if(snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
}
}
// down key
function d() {
if(snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
}
Here is HTML;
<div>
<button onclick="u()" type="button" id="U">U</button>
<button onclick="l()" type="button" id="L">L</button>
<button onclick="r()" type="button" id="R">R</button>
<button onclick="d()" type="button" id="D">D</button>
</div>
Description: I simply added four buttons in the html page, created four functions in the js which will move snake as it should move in different directions and simply added them to the 'onclick' attribute of the different buttons respectively.

How to move an image depending on mouse location using JS?

I would like an image to move to the left if the mouse is to the left of the screen and to the right if the mouse to the right of the screen, using javascript, here is the code I have so far:
var dirx = 0;
var spdx = 35;
var imgLeftInt;
var imgTopInt;
var imgHeight;
var imgWidth;
var divWidth;
var divHeight;
var t;
var tempX;
var tempY;
So I'm pretty sure I'm not missing any variables...
function animBall(on) {
imgLeftInt = parseInt(document.images['logo'].style.left);
imgTopInt = parseInt(document.images['logo'].style.top);
imgHeight = parseInt(document.images['logo'].height);
imgWidth = parseInt(document.images['logo'].width);
divWidth = parseInt(document.images['container'].width);
if (tempX > 779){
dirx = 1;
}
else if(tempX < 767){
dirx = 2;
}
else {
spdx = 0;
}
So if tempX, which should be the x coordinate of the mouse location, is bigger than 779, which is the halfway point of the div tag, the image should go right. If it's less than that, it should go left, and otherwise, the speed should be zero, as in it should stay still.
if(dirx == 1){
goRight();
} else if(dirx == 2) {
goLeft();
}
}
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
I found hundreds of different ways to get the mouse location, but this was off W3C so I assume it works.
function goRight() {
document.images['logo'].style.left = imgLeftInt+spdx +"px";
if (imgLeftInt > (divWidth-imgWidth)){
dirx = 2;
spdx= 20;
}
}
function goLeft() {
document.images['logo'].style.left = (imgLeftInt-spdx) +"px";
if (imgLeftInt < 5){
dirx = 1;
spdx= 20;
}
}
</script>
So that's my whole script.
<div id="container" onmousemove="getMouseXY(event);" width="1546" height="423">
Start Animation Stop Animation <br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
I left the dependency on the mouse location to the very end so the animation script works fine (or at least worked, unless I broke something trying to get it to read the mouse location).
Any ideas what I'm doing wrong??
If it's any help, I've hosted the code here.
I went to your link and tried debugging your code. I get an error on line 21 because your document has no "container" image ("container" is a div).
At the start of your question, you said you wanted to know mouse position relative to center of "screen". For that, you'd probably want to use window.innerWidth instead of the width attribute that you set on your div.
Well that needed a whole load of work, anyway, I have done some of it for you and you can now see things partially working, but you will need to play with it on jsfiddle. Perhaps you can now open some specific questions regarding getting this to work.
<div id="container" width="1546" height="423"> <a id="start" href="#">Start Animation</a> <a id="stop" href="#">Stop Animation</a>
<br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */
(function () {
"use strict";
var start = document.getElementById("start"),
stop = document.getElementById("stop"),
container = document.getElementById("container"),
logo = document.getElementById("logo"),
dirx = 0,
spdx = 35,
imgLeftInt,
imgTopInt,
imgHeight,
imgWidth,
divWidth,
divHeight,
t,
tempX,
tempY;
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
function goRight() {
logo.style.left = imgLeftInt + spdx + "px";
if (imgLeftInt > (divWidth - imgWidth)) {
dirx = 2;
spdx = 20;
}
}
function goLeft() {
logo.style.left = (imgLeftInt - spdx) + "px";
if (imgLeftInt < 5) {
dirx = 1;
spdx = 20;
}
}
// attribute on unused
function animBall(on) {
imgLeftInt = parseInt(logo.style.left, 10);
imgTopInt = parseInt(logo.style.top, 10);
imgHeight = parseInt(logo.height, 10);
imgWidth = parseInt(logo.width, 10);
divWidth = parseInt(container.width, 10);
if (tempX > 779) {
dirx = 1;
} else if (tempX < 767) {
dirx = 2;
} else {
spdx = 0;
}
if (dirx === 1) {
goRight();
} else if (dirx === 2) {
goLeft();
}
}
function startAnim() {
t = setInterval(animBall, 80);
}
start.addEventListener("click", startAnim, false);
function stopAnim() {
clearInterval(t);
}
stop.addEventListener("click", stopAnim, false);
container.addEventListener("mousemove", getMouseXY, false);
}());
Why don't you usee the html5 canvas and gee.js
Here's the js fiddle result (it may take a while to load, but that's fault of jsfiddle, the script will load much faster once on your website): http://jsfiddle.net/wLCeE/7/embedded/result/
and here's the much simpler code to make it work:
var g = new GEE({
width: 500,
height: 423,
container: document.getElementById('canvas')
});
var img = new Image(); // Create new img element
img.onload = function () {
demo(g)
};
img.src = 'http://qabila.tv/images/logo_old.png'; // Set source path
function demo(g) {
var style = "left"
g.draw = function () {
if (g.mouseX > g.width / 2 && style == "left") styleRight()
else if (g.mouseX < g.width / 2 && style == "right") styleLeft()
}
function styleLeft() {
style = "left"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, 0, 0)
}
function styleRight() {
style = "right"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, g.width - img.width, 0)
}
}

Categories