summaryrefslogtreecommitdiff
path: root/client/src/logic/players.ts
blob: ebe469f0b4454407dd371291e8fcc13210434dec (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
import { GameState, Input, Key, Rotation } 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

}

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.EAST,
            moving: false,
		};

	}

	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,
			};
            
		}

		startPressed ||= input.players[id].start;
        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

}