Skip to content

Commit

Permalink
refactor(helpers): modularize coinflip and outsideCoordinates
Browse files Browse the repository at this point in the history
  • Loading branch information
remarkablemark committed Jan 22, 2025
1 parent aee14ab commit 53a63fe
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 18 deletions.
6 changes: 6 additions & 0 deletions src/helpers/chance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Returns true or false.
*/
export function coinflip() {
return Boolean(randi(2))
}
14 changes: 14 additions & 0 deletions src/helpers/coordinates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { coinflip } from './chance'

/**
* Generate random coordinates outside the camera view.
*/
export function outsideCoordinates(x: number, y: number) {
const halfWidth = width() / 2
const halfHeight = height() / 2
const multiplier = coinflip() ? 1 : -1
return {
x: x + halfWidth * multiplier,
y: y + halfHeight * multiplier,
}
}
2 changes: 2 additions & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './chance'
export * from './coordinates'
20 changes: 2 additions & 18 deletions src/scenes/game.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,14 @@
import { Scene } from '../constants'
import { addEnemy, addPlayer } from '../gameobjects'
import { outsideCoordinates } from '../helpers'

scene(Scene.Game, () => {
const player = addPlayer()

add([text('Press arrow keys', { width: width() / 2 }), pos(12, 12)])

loop(5, () => {
const { x, y } = coordinates(player.pos.x, player.pos.y)
const { x, y } = outsideCoordinates(player.pos.x, player.pos.y)
addEnemy(x, y, player)
})
})

/**
* Random coordinates outside the camera view.
*/
function coordinates(x: number, y: number) {
const halfWidth = width() / 2
const halfHeight = height() / 2
const multiplier = coinflip() ? 1 : -1
return {
x: x + halfWidth * multiplier,
y: y + halfHeight * multiplier,
}
}

function coinflip() {
return Boolean(randi(2))
}

0 comments on commit 53a63fe

Please sign in to comment.