File size: 1,905 Bytes
8cbe088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { v, Infer, ObjectType } from 'convex/values';
import { Game } from './game';

// Define the schema for DayNightCycle
export const dayNightCycleSchema = {
  currentTime: v.number(),
  isDay: v.boolean(),
  dayDuration: v.number(),
  nightDuration: v.number(),
};
export type SerializedDayNightCycle = ObjectType<typeof dayNightCycleSchema>;

export class DayNightCycle {
  currentTime: number;
  isDay: boolean;
  dayDuration: number;
  nightDuration: number;

  constructor(serialized: SerializedDayNightCycle) {
    const { currentTime, isDay, dayDuration, nightDuration } = serialized;
    this.currentTime = currentTime;
    this.isDay = isDay;
    this.dayDuration = dayDuration;
    this.nightDuration = nightDuration;
  }

  // Tick method to increment the counter
  tick(game: Game, tickDuration: number) {
    this.currentTime += tickDuration;

    if (this.isDay && this.currentTime >= this.dayDuration) {
      this.isDay = false;
      this.currentTime = 0;
      this.onNightStart(game);
    } else if (!this.isDay && this.currentTime >= this.nightDuration) {
      this.isDay = true;
      this.currentTime = 0;
      this.onDayStart(game);
    }
  }

  onDayStart(game: Game) {
    console.log("Day has started!");
    for (const player of game.world.players.values()) {
      // player.onDayStart(game);
    }
    for (const agent of game.world.agents.values()) {
      // agent.onDayStart(game);
    }
  }

  onNightStart(game: Game) {
    console.log("Night has started!");
    for (const player of game.world.players.values()) {
      // player.onNightStart(game);
    }
    for (const agent of game.world.agents.values()) {
      // agent.onNightStart(game);
    }
  }

  serialize(): SerializedDayNightCycle {
    const { currentTime, isDay, dayDuration, nightDuration } = this;
    return {
      currentTime,
      isDay,
      dayDuration,
      nightDuration,
    };
  }
}