Skip to content

Commit

Permalink
refactor(events): modularize player attack logic
Browse files Browse the repository at this point in the history
  • Loading branch information
remarkablemark committed Jan 22, 2025
1 parent 0f00bee commit aee14ab
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 32 deletions.
33 changes: 33 additions & 0 deletions src/events/attack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { addBullet } from '../gameobjects'
import type { Player } from '../types'

export function addAttack(player: Player) {
const attack = new Attack(player)

onClick(() => {
if (attack.canAttack()) {
attack.update()
addBullet(player)
}
})
}

class Attack {
private attackDelay = 1
private lastAttacked = 0
private player

constructor(player: Player) {
this.player = player
}

update() {
this.lastAttacked = time()
}

canAttack() {
return !this.lastAttacked
? true
: this.lastAttacked + this.attackDelay < time()
}
}
1 change: 1 addition & 0 deletions src/events/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './attack'
export * from './cursors'
34 changes: 2 additions & 32 deletions src/gameobjects/player.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Sprite, Tag } from '../constants'
import { addCursorKeys } from '../events'
import type { Player } from '../types'
import { addBullet } from './bullet'
import { addAttack, addCursorKeys } from '../events'

export function addPlayer(x = center().x, y = center().y) {
const player = add([
Expand All @@ -14,35 +12,7 @@ export function addPlayer(x = center().x, y = center().y) {
])

addCursorKeys(player)

const attack = new Attack(player)

onClick(() => {
if (attack.canAttack()) {
attack.update()
addBullet(player)
}
})
addAttack(player)

return player
}

class Attack {
private attackDelay = 1
private lastAttacked = 0
private player

constructor(player: Player) {
this.player = player
}

update() {
this.lastAttacked = time()
}

canAttack() {
return !this.lastAttacked
? true
: this.lastAttacked + this.attackDelay < time()
}
}

0 comments on commit aee14ab

Please sign in to comment.