Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLeo Effert
3,704 PointsTrying to compare to variables in javascript
I'm building a game with a canvas and four buttons. I have a enemy bouncing of the walls. Now I'm trying to make it so that the game ends if he catches me. But in the function gameOver() the (xe === x) never becomes true.
var canvas = document.querySelector('canvas'); var c = canvas.getContext('2d');
var x = 100; var y = 75;
c.fillStyle = "green"; c.fillRect(x, y, 10, 10);
c.fillStyle = "red"; c.fillRect(50, 20, 200, 10);
c.fillStyle = "red"; c.fillRect(50, 120, 200, 10);
c.fillStyle = "red"; c.fillRect(50, 20, 10, 100);
c.fillStyle = "red"; c.fillRect(240, 20, 10, 100);
$("img").hide();
var xe = 150; var xeplus = 10;
function gameOver() {
if (y < 30 || y > 110 || x < 60 || x > 230 || xe === x) { $("#field").hide(); $("button").hide(); $("#title").text("HAHAHAHAHAHAHAHA!"); $("img").show(); }}
$("button").click(function() { c.fillStyle = "white"; c.fillRect(xe, 75, 10, 10); xe = xe + xeplus; c.fillStyle = "red"; c.fillRect(xe, 75, 10, 10);
if (xe > 220 || xe < 70) { xeplus = -xeplus; } });
$("#moveUp").click(function() { c.fillStyle = "white"; c.fillRect(x, y, 10, 10); y = y - 5; c.fillStyle = "green"; c.fillRect(x, y, 10, 10); gameOver(); });
$("#moveLeft").click(function() { c.fillStyle = "white"; c.fillRect(x, y, 10, 10); x = x - 5; c.fillStyle = "green"; c.fillRect(x, y, 10, 10); gameOver(); });
$("#moveDown").click(function() { c.fillStyle = "white"; c.fillRect(x, y, 10, 10); y = y + 5; c.fillStyle = "green"; c.fillRect(x, y, 10, 10); gameOver(); });
$("#moveRight").click(function() { c.fillStyle = "white"; c.fillRect(x, y, 10, 10); x = x + 5; c.fillStyle = "green"; c.fillRect(x, y, 10, 10); gameOver(); });
1 Answer
Steven Parker
231,269 PointsThis code doesn't seem to be complete, but I notice that all of the click handlers call "gameOver" except the one for "button".
But if you match the coordinates using one of the other handlers, it does become true.
Steven Parker
231,269 PointsSteven Parker
231,269 PointsUse the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. Or watch this video on code formatting.