Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Leo Effert
Leo Effert
3,704 Points

Trying 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(); });

Steven Parker
Steven Parker
220,501 Points

Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

1 Answer

Steven Parker
Steven Parker
220,501 Points

This 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.