Neale Pickett
·
2024-12-04
player.mjs
1import {Tank} from "./tank.mjs"
2
3const Millisecond = 1
4const Second = 1000 * Millisecond
5const FPS = 12
6
7export class Player {
8 constructor(ctx) {
9 this.ctx = ctx
10 }
11
12 load(game) {
13 this.ctx.canvas.width = game.field[0]
14 this.ctx.canvas.height = game.field[1]
15
16 this.tanks = []
17 for (let tankDef of game.tanks) {
18 let tank = new Tank(this.ctx, tankDef.color, tankDef.sensors)
19 this.tanks.push(tank)
20 }
21
22 this.rounds = game.rounds
23
24 this.start()
25 }
26
27 start(frameno = 0) {
28 if (!this.loop_id) {
29 this.loop_id = setInterval(
30 () => this.update(),
31 Second / FPS,
32 )
33 }
34 this.frameno = frameno
35 }
36
37 stop() {
38 if (this.loop_id) {
39 clearInterval(this.loop_id)
40 this.loop_id = null
41 }
42 }
43
44
45 update() {
46 let frame = this.rounds[this.frameno]
47 if (!frame) {
48 this.stop()
49 setTimeout(
50 () => {
51 this.start()
52 },
53 4 * Second,
54 )
55 return
56 }
57
58 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height)
59
60 // Update and draw craters first
61 for (let i in frame) {
62 let tank = this.tanks[i]
63 tank.set_state(...frame[i])
64 tank.draw_crater()
65 }
66 // Then sensors
67 for (let tank of this.tanks) {
68 tank.draw_wrap_sensors()
69 }
70 // Then tanks
71 for (let tank of this.tanks) {
72 tank.draw_tank()
73 }
74
75 this.frameno += 1
76 }
77}
78