/ README.md
README.md
  1  # ToasterGen Spin
  2  
  3  ToasterGen Spin is a commissioned roulette game for an in-game ComputerCraft casino. It features a dynamic, animated roulette board along with supporting utilities for archiving and compression, all written in Lua.
  4  
  5  ## Features
  6  
  7  - **Dynamic Roulette Board**:
  8    Draws a complete roulette ring with animated ball movement and decorative elements (see [`src/ring.lua`](src/ring.lua)). The ring is rendered on a ComputerCraft monitor, utilizing functions to draw elements, lines, and the animated ball. The `launchBall` function animates the ball's movement, and the winning number is highlighted with a blinking effect.
  9  
 10  - **Interactive Betting Carpet**:
 11    Provides a user interface for placing bets, rendered on a separate monitor (see [`src/carpet.lua`](src/carpet.lua)). The carpet module defines the layout of betting options and handles touch events to register bets. The `findClickedNumber` function determines which betting option was selected based on the coordinates of the touch event.
 12  
 13  - **Server Communication**:
 14    Communicates with a central server to manage player balances and process payouts (see [`src/modem.lua`](src/modem.lua) and [`stator.lua`](stator.lua)). The `sendWin`, `getBallance`, and `resetBallance` functions in `modem.lua` handle communication with the server, while `stator.lua` on the server side manages player data and processes requests.
 15  
 16  - **Player Detection**:
 17    Detects players in a defined area using a player detector peripheral. The `stator.lua` script uses the `getPlayersInBorders` function to identify players within the designated zone.
 18  
 19  - **Automatic Payouts**:
 20    The system automatically attempts to payout winnings directly to the player's inventory after each spin. It checks the player's balance and transfers the winnings as emeralds.
 21  
 22  - **Configuration**:
 23    Customizable behaviour and appearance via TOML configuration files (see [`config.toml`](config.toml) and [`tools/config.lua`](tools/config.lua)). The `config.lua` script provides functions for configuring the game's settings, including peripheral devices, reward multipliers, and server parameters.
 24  
 25  - **Modular Design**:
 26    Organized into multiple modules such as [`spin.lua`](spin.lua) for the main game logic, [`carpet.lua`](src/carpet.lua) for the betting carpet, [`ring.lua`](src/ring.lua) for the roulette wheel, and [`chat.lua`](src/chat.lua) for chat integration.
 27  
 28  ## System Architecture
 29  
 30  The ToasterGen Spin system consists of three main components:
 31  
 32  1. **Client**: The roulette table itself with monitors for the betting carpet and roulette wheel
 33  2. **Server**: Manages player data, processes bets, and handles payouts
 34  3. **Player Interaction**: Through physical buttons and monitor touches
 35  4. **Inventory Manager**: A physical device that connects to the player's inventory and sends/receives payments directly to/from a client.
 36  
 37  ### Player Registration Process
 38  
 39  Players register for betting through a physical interaction process:
 40  
 41  1. Connect their inventory to an Inventory Manager (IV)
 42  2. Press a redstone button located on top of the machine
 43  3. The client detects which button was pressed by reading the redstone signal strength
 44  4. This assigns the player as the current active better, allowing them to place bets
 45  
 46  This physical registration process ensures that only players physically present at the machine can place bets and prevents remote exploitation.
 47  
 48  ### Communication Flow
 49  
 50  #### Overall System Architecture
 51  
 52  ```mermaid
 53  graph TB
 54      Player[Player] -->|Places Bets| Client
 55      Player -->|Physical Interactions| Client
 56      Client -->|Monitor Display| Player
 57      Server -->|Database Operations| DB[(Database)]
 58      Player -->|Selects self| IVManager
 59      Player -->|Assigns self's inventory| IVManager
 60      IVManager -->|Changes current better| Client
 61      IVManager -->|Redstone signal for player ID| Client
 62      Client -->|Updates Player| IVManager
 63      Client -->|Check player's offhand| Server
 64  
 65      subgraph Client
 66          Carpet[Carpet Monitor]
 67          Ring[Ring Monitor]
 68          Mod[Modem]
 69      end
 70  
 71      subgraph Server
 72          SModem[Modem]
 73          DBMgr[Database Manager]
 74      end
 75  
 76      subgraph IVManager
 77          IV[Inventory Manager]
 78          IVButton[Button]
 79          IModem[Modem]
 80      end
 81  ```
 82  
 83  #### Betting and Payout Sequence
 84  
 85  ```mermaid
 86  sequenceDiagram
 87      participant Player
 88      participant Client
 89      participant Server
 90      participant IVManager
 91      participant Database
 92  
 93      Player->>Client: Press button (register)
 94      Client-->>Player: Confirm registration
 95      Player->>Client: Place emerald
 96      Client->>IVManager: Check for emeralds in offhand
 97      IVManager-->>Client: Number of emeralds in offhand
 98      alt Enough Emeralds
 99          Player->>Client: Touch carpet (bet)
100          Client->>IVManager: Take one emerald
101          IVManager-->>Client: Removed one emerald
102          Client->>Client: Registers bet
103          Client->>Player: Displays bet
104          Player->>Client: Touch ring (spin)
105          Client->>Client: Animates ball, calculates winner
106  
107          alt Winning Bet
108              Client->>Server: sendWin(player, bet, payout)
109              Server->>Database: updateBalance
110              Server-->>Client: confirmWin
111                  Client->>IVManager: Transfer payout
112              alt Payout Successful
113                  Client->>Server: resetBalance(player)
114                  Server-->>Client: confirmReset
115              else Payout Failed
116                  Client-->>Player: not enough emeralds, contact admin
117              end
118          else Losing Bet
119              Client->>Player: no payout
120          end
121      else Not Enough Emeralds
122          Client ->> Player: Not enough emeralds, ignore
123      end
124  ```
125  
126  #### Player Detection Flow
127  
128  ```mermaid
129  flowchart LR
130      A[Player Approaches Table] --> B{In Range?}
131      B -- No --> C[Cannot Bet]
132      B -- Yes --> D{Pressed Button?}
133      D -- No --> E[Tell Player to Press Button]
134      D -- Yes --> F[Identify Player]
135      F --> G{Has Emeralds?}
136      G -- No --> H[Prompt to add Emeralds]
137      G -- Yes --> I[Allowed to Bet]
138      I --> J[Spin Wheel]
139      J --> K{Win or Lose?}
140      K -- Win --> L[Calculate Payout]
141      K -- Lose --> M[End Round]
142      L --> N[Update Player Balance]
143      N --> M
144  ```
145  
146  ## Event Handling
147  
148  The game uses ComputerCraft's event system to handle user input and peripheral events. The main loop in `spin.lua` listens for `redstone` and `monitor_touch` events.
149  
150  - **Redstone Events**: Triggered when a player presses a button to register for betting.
151  - **Monitor Touch Events**: Triggered when a player touches the betting carpet or the roulette wheel.
152  
153  ### Event Flow
154  
155  ```mermaid
156  stateDiagram-v2
157      [*] --> Idle
158      Idle --> PlayerRegistration: Redstone Event
159      PlayerRegistration --> BettingPhase
160      BettingPhase --> SpinningPhase: Ring Touch
161      SpinningPhase --> ResultCalculation: Ball Stops
162      ResultCalculation --> PayoutPhase
163      PayoutPhase --> Idle: Round Complete
164  ```
165  
166  ## Technical Implementation
167  
168  ### Redstone Signal Detection
169  
170  The system identifies which player is interacting with the machine through redstone signal strength:
171  
172  1. Each inventory manager is mapped to a specific signal strength
173  2. When a player presses the button, it produces a specific signal strength
174  3. The client reads this signal via `redstone.getAnalogInput(config.devices.redstone)`
175  4. The `currentBetter` variable is set to the corresponding player index
176  5. Formula: `id = redStreingth - config.devices.ivmanBigger` (base signal strength subtracted from signal)
177  
178  This approach allows multiple IV managers to be connected to the same system but still uniquely identify each player.
179  
180  ### Modem Communication Protocol
181  
182  The client and server communicate using the ComputerCraft modem peripheral on channel 1.
183  
184  **Message Format:**
185  
186  ```txt
187  Message {
188    type: string        // Request type (e.g., "win", "balance", "resetBalance")
189    player?: string     // Player name
190    bet?: Bet           // Bet information
191    payout?: number     // Payout amount
192    startPos?: Position // For player detection
193    endPos?: Position   // For player detection
194  }
195  
196  Response {
197    type: string        // Response type (e.g., "winRes", "balanceRes")
198    code: number        // HTTP-like status code
199    message: string     // Status message
200    balance?: number    // For balance responses
201    players?: string[]  // For player detection responses
202    numberOfPlayers?: number // Count of players detected
203  }
204  ```
205  
206  ## Usage
207  
208  - Run the game by executing `spin.lua` on your ComputerCraft setup.
209  - Customize behaviour and appearance via the configuration file.
210  - Explore and test individual components in the [`tests`](tests/) directory.
211  
212  **When reporting issues, please include the following environment details:**
213  
214  - Minecraft Version
215  - Loader (Forge/Fabric)
216  - CC Tweaked Version
217  
218  ## Licence
219  
220  Distributed under the GNU Lesser General Public Licence. See [LICENCE](LICENCE) for details.
221  Enjoy your spin and happy coding!
222  
223  'lua-toml' is licensed under [MIT](https://opensource.org/licenses/MIT).
224  
225  ```txt
226  Copyright (c) 2017 Jonathan Stoler
227  
228  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
229  
230  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
231  
232  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
233  ```