JS Racer
Application Overview¶
It's time to dip a toe into the world of games. Albeit a very tiny toe.
You are going to build a simple racing game that moves some "cars" (colored divs) across the screen. It'll even be a multi-player game as each player will be able to hit their own key to make their div move.
Release 1 - Listen for keydown¶
- Create an HTML file with two
divelements. Give themids of 'car1', 'car2' respectively. - Use CSS to make one of them blue and the other red, and both of them
50pxby50px. You can use a style sheet for this as opposed to using JavaScript. - Add a
keydownevent listener. -
For now just print a message to the console when a key is pressed.
-
Create a function which checks which key was pressed. If the
pkey was pressed move the blue car, and if theqkey was pressed move the red car. - For the time being, just print "blue" or "red" depending on which key was pressed.
Release 2 - Move the cars¶
- Create a function named
moveCar. Pass this function theHTMLElementof thedivthat corresponds to the key that was pressed and the event from the key press. - Use the marginLeft style property to "move" the corresponding
divacross the screen when its key is pressed. If the left-margin is increasing it will appear that that div is gliding across the screen. - Inside of your
moveCarfunction each time the marginLeft property is increased check to see if it is equivalent to the browser window's width.window.innerWidthreturns the current width of the screen inpx. When one of the divs reaches this value, it is the winner. Print out a message to the console notifying you which div won.
Release 3 - Make it better¶
- Replace the colored
divs with actual images of cars (or horses, dragons, what have you). - Add additional logic to the keydown so that the red car moves on alternating
qandwkeys, and the blue car moves on alternatingoandpkeys. If the user does not alternate, the car should not move (remove the event listeners). - When a user wins the race, clear the screen and display a message or image notifying the players who won the race.
- Do anything else you can think of to spruce up this relatively simple game. Maybe add some more players/key events, a finish line, background image, etc.