-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoomController.sol
80 lines (62 loc) · 2.29 KB
/
RoomController.sol
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract RoomController {
struct Room {
address[] players;
uint256 currentPlayerIndex;
uint256 randomParameter;
}
mapping(uint256 => Room) public rooms;
mapping(address => uint256) public playerInRoom;
uint256 public numberOfRooms;
constructor() {
numberOfRooms = 0;
}
function playersNotInGame(address[] calldata players) public view returns (bool) {
for (uint256 i = 0; i < players.length; i++) {
if (playerInRoom[players[i]] != 0) {
return false;
}
}
return true;
}
function getCurrentPlayerIndex(uint256 roomId) public view returns(uint256) {
Room storage room = rooms[roomId];
return room.currentPlayerIndex;
}
function getCurrentPlayerAddress(uint256 roomId) public view returns(address) {
Room storage room = rooms[roomId];
uint256 currentPlayerIndex = getCurrentPlayerIndex(roomId);
return room.players[currentPlayerIndex];
}
function getNumberOfPlayersInRoom(uint256 roomId) public view returns(uint256) {
Room storage room = rooms[roomId];
return room.players.length;
}
function switchPlayer(uint256 roomId) internal {
Room storage room = rooms[roomId];
uint256 numberOfPlayers = room.players.length;
room.currentPlayerIndex++;
room.currentPlayerIndex %= numberOfPlayers;
}
function createRoom(address[] calldata players) internal returns (uint256) {
require(
playersNotInGame(players),
"Players have some game unfinished"
);
numberOfRooms++;
Room storage room = rooms[numberOfRooms];
room.players = players;
return numberOfRooms;
}
function assignPlayersToRoom(uint256 roomId, address[] calldata players) internal {
for (uint256 i = 0; i < players.length; i++) {
playerInRoom[players[i]] = roomId;
}
}
function deletePlayersFromRoom(address[] calldata players) internal {
for (uint256 i = 0; i < players.length; i++) {
playerInRoom[players[i]] = 0;
}
}
}