Skip to content

Instantly share code, notes, and snippets.

@bashbaugh
Last active February 27, 2019 02:09
Show Gist options
  • Save bashbaugh/cf46d818246456b3c9b2013b898f3f1b to your computer and use it in GitHub Desktop.
Save bashbaugh/cf46d818246456b3c9b2013b898f3f1b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Game</title>
</head>
<body onload="init()">
<h1>JavaScript Game</h1>
<p>Here is a simple JavaScript game:</p>
<canvas id="c" width="400" height="400"></canvas>
<script>
console.log("Starting the script!");
console.log("Starting the script!");
// Get canvas:
let canvas_element = document.getElementById("c");
let canvas = canvas_element.getContext("2d");
// Set up variables:
let player_x = 200;
let player_y = 220;
let dots_x = [200];
let dots_y = [0];
let dots_color = ["#800080"];
let score = 0;
let start_time = 0;
let game_over = 0;
// Set up config "settings" variables:
let dot_color_options = ["#FF0000", "#800080"];
let player_color = "#FFFF00";
let text_color = "#FFFFFF";
let frames_per_second = 15;
let dot_pixels_per_frame = 5;
let player_move_increment = 40;
let dot_distance_apart = 10;
let game_duration = 30 * 1000;
let dot_radius = 10;
let player_radius = 20;
document.onkeydown = key_pressed;
function init()
{
draw_background();
canvas.fillStyle = "#FFFFFF";
canvas.font = "25px Arial";
canvas.fillText("Press the up arrow to start", 40, 200);
}
function draw_background()
{
canvas.clearRect(0, 0, canvas_element.width, canvas_element.height);
canvas.fillStyle = "#1EBA00";
canvas.fillRect(0, 0, canvas_element.width, canvas_element.height);
}
function key_pressed(key)
{
if (key.key == "ArrowUp")
{
// Start the game if not started:
console.log("up");
if (start_time == 0)
{
start_time = new Date().getTime();
setInterval(update, 1000 / frames_per_second);
}
}
if (key.key == "ArrowLeft")
{
console.log("left");
}
if (key.key == "ArrowRight")
{
console.log("right");
}
}
function update()
{
let time_right_now = date.getTime()
// If time right now minus start time is less than game time limit:
if (time_right_now - start_time < game_duration)
{
// Compare player coordinates to dot coordinates to see whether the player is above a dot. Increment score if so.
// Check distance from highest dot to top of screen. If greater than dot_distance_apart, create a new dot at top.
}
else // else: game is over.
{
// Set game_over to true.
}
// Clear the canvas and draw the background.
// Draw dots and move them down the screen.
// Ensure that player is within canvas
// Draw player onto screen.
// Draw score onto screen.
// IF game_over:
// Draw game over screen
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment