Skip to content

Instantly share code, notes, and snippets.

@kentbrew

kentbrew/game.js

Created Jun 29, 2020
Embed
What would you like to do?
/* use strict */
const me = {
// we could potentially set this in game.create from game["_gridWidth"]
// instead of hard-coding the number 24
board: {
height: 24,
width: 24
},
// starting score should be 0
score: 0,
// our game will last this many seconds
secondsRemaining: 45,
// 1 = 100% chance
chanceOfDot: 0.05,
// x and y modifiers for up, down, right, and left
move: {
[Direction.Up]: { x: 0, y: -1 },
[Direction.Down]: { x: 0, y: 1 },
[Direction.Right]: { x: 1, y: 0 },
[Direction.Left]: { x: -1, y: 0 }
},
items: []
},
// initialze the game
create = () => {
// start our score at zero
me.score = 0;
// randomly set our player
me.player = {
x: Math.floor(Math.random() * me.board.width),
y: Math.floor(Math.random() * me.board.height),
c: Color.Blue
};
},
// every few frames we'll run this
update = () => {
// should we make a new dot?
if (Math.random() < me.chanceOfDot) {
const newDot = {
x: Math.floor(Math.random() * me.board.width),
y: Math.floor(Math.random() * me.board.height),
c: Color.Black
};
// don't set a new dot under player
if (newDot.x !== me.player.x || newDot.y !== me.player.y) {
me.items.push(newDot);
}
}
// draw all dots and check if player is on one
me.items.filter((it, index) => {
game.setDot(it.x, it.y, it.c);
if (it.x === me.player.x && it.y === me.player.y) {
me.score = me.score + 1;
me.items.splice(index, 1);
}
// important: since we are not checking whether the prospective place
// for a new dot already has a dot on it before we create it, don't break
// if you find one
});
// draw player
game.setDot(me.player.x, me.player.y, me.player.c);
},
// if someone presses a key, do this:
onKeyPress = (direction) => {
const tx = me.player.x + me.move[direction].x;
const ty = me.player.y + me.move[direction].y;
if (tx > -1 && ty > -1 && tx < me.board.width && ty < me.board.height) {
me.player.x = tx;
me.player.y = ty;
}
},
// if someone clicks a dot, do this:
onDotClicked = (dot) => {
// this is ... not super useful?
console.log(dot);
},
// run me once per second until we're out of time
tick = () => {
me.secondsRemaining = me.secondsRemaining - 1;
if (me.secondsRemaining) {
game.setText(`Time left: ${me.secondsRemaining}s. Score: ${me.score}`);
window.setTimeout(tick, 1000);
} else {
game.setText(`Game over! Final score: ${me.score}`);
// wait at least 100ms for things to die down before calling game.end or it won't work?
window.setTimeout(()=> {
game.end();
},100);
}
return;
},
// create an instance of Game to run
game = new Game({create, update, onKeyPress, onDotClicked});
// start the game
game.run();
// start ticking
tick();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment