summaryrefslogtreecommitdiff
path: root/client/src/logic/players.ts
blob: ae7dcbe92a4fd0e78dfa68a4164d478e753f3dc3 (plain)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { checkMap, decompressMap, genMap } from "../map.js"
import { GAME_MAP_COUNT, GameState, Input, Key, Rotation, Vec2 } from "../types.js"

const canPlayerJoin = (data: GameState) => {

    // lobby has already started
    if (data.started) {
        return false
    }

    // lobby full
    if (Object.keys(data.players).length >= 4) {
        return false
    }

    return true

}

const loadMaps = (maps: {[key: number]: string}): boolean => {

    for (let mapId = 0; mapId < GAME_MAP_COUNT; mapId++) {

        let {width, height, data} = decompressMap(maps[mapId])
        let map = genMap(width, height, data, mapId)
        let [success, result] = checkMap(map)

        if (!success) {
            alert(result)
            return false
        }

        map.spawns = result as Vec2[]

    }

    return true
}


export const updatePlayers = (data: GameState, input: Input) => {
   
    let startPressed = false;

    for(const added of input.added || []) {
        
        if (!canPlayerJoin(data)) {
            continue
        }

		console.log("added", added);

        data.input[added] = Key.NOTHING

		data.players[added] ||= {
			pos: {x: 1, y: 1},
            inputRotation: Rotation.EAST,
            moveRotation: Rotation.NOTHING,
            velocityRotation: Rotation.NOTHING,
            moving: false,
            thiccLeft: 0,
            dead: false,
            framesDead: 0,
            atePellets: 0
		};

	}

	for(const id in input.players) {

		if(!input.players[id]) {
			continue;
		}

		if(id in data.players && input.players[id].name !== undefined) {

			let name = input.players[id].name;
			name = name.substring(0, 16);
			
			data.players[id] = {
				...data.players[id],
				name,
			};
            
		}

        if (input.players[id].start) {
            let maps = input.players[id].maps
            if (loadMaps(maps)) {
                startPressed = true
            }
        }

        if (input.players[id].key)
		    data.input[id] = input.players[id].key

	}

    for(const removed of input.removed || []) {
		console.log("removed", removed);
		delete data.input[removed];
		delete data.players[removed];

        let element_id = 'span' + removed 
        let element = document.getElementById(element_id)
        if (element !== null && element !== undefined) element.remove()
	}

    return startPressed

}