# Arm Wrestling — documentation

> Arm wrestle any player at a table or a barrel, with stamina, bets, a rated ranking and tournaments.

- URL: https://xexstudio.com/docs/arm-wrestling
- Version: 1.0.0
- Product page: https://xexstudio.com/scripts/arm-wrestling
Arm wrestling for FiveM. Two players meet at a table or a barrel, one challenges the other, and they push against
each other with the game's own arm wrestling animations. Stamina makes it a match of timing instead of a tapping
contest, players can bet in-game money, and every ranked match moves a rating that feeds a server ranking.
ESX, QBCore and Qbox.

The server runs the match: it counts and rate-limits the pushes, applies stamina, moves the arm, picks the winner,
pays the bet and saves the result. A modified client can't win a match it didn't play.

Made by [XeX](https://xexstudio.com). Screenshots and the rest of the XeX scripts are on
[xexstudio.com](https://xexstudio.com/scripts).

## Features

- **Tables anywhere:** props that already exist on the map (the arm wrestling table and wooden barrels by default)
  through ox_target or qb-target, plus tables you place in the config with a map blip. Without a target resource,
  `[E]` at the placed tables.
- **Challenge and accept:** pick a player standing at the table, name a bet or play a friendly match, and the rival
  accepts or declines.
- **Stamina:** every push costs stamina and tired pushes are weaker. A steady rhythm keeps full power; a burst wins
  ground for a few seconds and leaves you weak. Both stamina bars are on screen, so you can strike when the rival
  is tired.
- **Bets with in-game money:** both stakes are taken when the challenge is accepted and the winner takes the pot.
  Draws and cancelled matches are refunded. Giving up, walking away or disconnecting during a match loses it.
- **Rated ranking with divisions:** each player has a rating and a division (bronze, silver, gold, diamond), and
  the number one is the champion. Beating a stronger player gives more points than beating a weaker one, and the
  result card celebrates a promotion. The ranking shows rating, wins and losses, best win streak and fastest win.
- **Monthly seasons and hall of fame:** on the first day of each month the top 3 go to the hall of fame and a new
  season starts. Best streak and fastest win stay as all-time records.
- **Ranking on the wall:** the season's top 5 and the last champion painted on a wall next to the table (no props).
- **Spectators:** players around the table see the match live: both names, the arm, the stamina bars and the pot.
- **Tournaments:** single elimination at a table for 4, 8 or 16 players, seeded by rating, with byes, an entry fee
  that makes the pot, live bracket, matches called by the server and walkovers for whoever does not show up. Past
  winners go to the hall of fame.
- **Match HUD and result card:** arm position, time left, both stamina bars, pot, and the rating change at the end.
- **Hooks and events** for skills, battle passes, analytics or permissions, without editing the resource.
- **Optimized:** no threads while nobody plays and one database write per ranked match. Placed tables only exist
  while a player is close to them.
- English and Spanish.

## Requirements

- [ox_lib](https://github.com/overextended/ox_lib) and [oxmysql](https://github.com/overextended/oxmysql)
- One framework: **ESX**, **QBCore** or **Qbox**
- OneSync (on by default on current servers)
- Optional: ox_target or qb-target (needed to use props that are already on the map)

## Install

1. Put `xex_armwrestling` in your resources folder.
2. Add it to `server.cfg` after your framework, ox_lib and oxmysql:
   ```cfg
   ensure xex_armwrestling
   ```
3. Set the language with `setr ox:locale en` (or `es`).

The `xex_armwrestling` table is created on start. If your database user can't create tables, run
`install/armwrestling.sql`.

## How it works

1. **At the table** a player picks "Arm wrestle" and chooses one of the players standing next to it.
2. **Bet.** The challenger names an amount (0 for a friendly match). The rival sees it and accepts or declines.
3. **Both stakes are taken**, both players are placed at the table and a countdown runs.
4. **Push.** Tap the push key. The arm moves towards whoever pushes harder; the match ends when it reaches one
   side, or after 45 seconds in favour of whoever is ahead.
5. **Result.** The winner takes the pot, and a ranked match updates both ratings.

Hold the give-up key for a second to forfeit. During the countdown that cancels the match and refunds the bets;
once the match has started it counts as a loss. A player who is downed cancels the match and both get their money back.

### Stamina

With the default numbers a player keeps full power at about 5 to 6 pushes per second. Faster than that empties the
bar in three to four seconds, and pushes with an empty bar are worth 30 %. Tapping as fast as possible therefore
loses against a steady player over a full match; the skill is in when to spend the burst.

### Ranking

Ratings start at 1000 and work like chess ratings: the points one player wins are the points the other loses, and
the amount depends on the difference between them (16 between equals, up to 32). To keep it honest:

- matches shorter than `Config.Ranking.minDuration` seconds are not ranked;
- the same two players only get `Config.Ranking.pairLimit` ranked matches per hour (more can be played, unranked);
- a player appears in the ranking after `Config.Ranking.minMatches` matches.

The HUD shows whether the match is ranked before it starts.

## Configure

| File | What it contains |
| --- | --- |
| `config.lua` | All settings (table below) |
| `locales/<locale>.json` | Every text: notifications, menus, HUD and ranking |
| `bridge/server.lua` | Framework, money, character names, downed check |
| `bridge/client.lua` | Notifications, target resource, downed check |

| Setting | What it does |
| --- | --- |
| `Config.Framework` | `auto`, or force `esx` / `qb` / `qbox` |
| `Config.Target` | `auto`, `ox_target`, `qb-target` or `none` (`[E]` at placed tables) |
| `Config.Controls` | Push and give-up keys with the label shown in the HUD |
| `Config.Models` | Props players can use, whether every one on the map counts, and how players stand at them |
| `Config.Tables` | Tables placed by the script: position, model, blip and an optional ranking board on a wall |
| `Config.Match` | Distances, invitation time, countdown, match length, push size, win point and the push rate limit |
| `Config.Stamina` | On or off, cost per push, recovery per second and power with no stamina |
| `Config.Bets` | On or off, account and maximum bet |
| `Config.Ranking` | On or off, size, starting rating, points per match, the rules above, divisions and seasons |
| `Config.Spectators` | On or off and how close players must be to watch a match |
| `Config.Tournaments` | On or off, who can host, sizes, sign-up time, entry limit, pot cut, call time and distances |
| `Config.WallBoard` | Distance at which wall ranking boards are drawn and how often they refresh |
| `Config.UI` | Brand name and accent color |
| `Config.Admin` | Ace and name of the reset command |
| `Config.Hooks` | Functions called by the server (see For developers) |

### Props and tables

```lua
Config.Models = {
    prop_arm_wrestle_01 = { world = true, aligned = true, axis = 0.0, offset = vec3(0.0, 0.0, 0.0) },
    prop_wooden_barrel = { world = true, aligned = false, offset = vec3(0.0, 0.0, 0.0) },
}

Config.Tables = {
    { coords = vec4(-1226.8, -1557.87, 3.19, 303.77), model = 'prop_arm_wrestle_01', blip = true },
}
```

- `world = true` lets players use every prop of that model on the map. Set it to `false` to allow only the tables
  you place.
- `aligned = true` is for props with two sides: players stand along the prop's own axis. If they end up across the
  table instead of along it, set `axis = 90.0`.
- `offset` moves the centre of the scene if the hands don't meet over the prop (x to the challenger's right,
  y towards the rival, z up).

To add any other prop (a bar table, a crate), list its model and adjust `offset` in game.

### Ranking board on a wall

Each table of `Config.Tables` can show the season's ranking on a wall nearby. Stand in front of the wall, look at
it and run `/armwrestlingboard`: the line is printed in F8 and copied to the clipboard. Paste it into the table:

```lua
Config.Tables = {
    { coords = vec4(-1226.8, -1557.87, 3.19, 303.77), model = 'prop_arm_wrestle_01', blip = true,
      board = { coords = vec4(-1205.10, -1559.80, 6.20, 215.0), width = 1.6 } },
}
```

### Tournaments

1. **Host:** at the table, pick "Tournament" and fill in a name, the size (4, 8 or 16) and the entry fee (0 for a free
   one). By default only admins host; set `Config.Tournaments.host = 'everyone'` to let any player do it.
2. **Sign-up:** players around the table are told, and sign up from the same option, paying the entry. They can
   leave and get it back until sign-up ends.
3. **Bracket:** when the tournament is full or the sign-up time ends (with at least `minPlayers`), players are
   seeded by rating. The best seeds get byes when the field is not a power of two.
4. **Matches:** the server calls each match. Both players have `callSeconds` to come to the table; whoever is not
   there loses by walkover. A draw or a cancelled match is played again. Normal challenges wait while it runs.
5. **Champion:** the winner takes the pot (minus `cut`) and is saved in the hall of fame.

Everyone can open the live bracket from the table. A player who disconnects during sign-up leaves the tournament and
their entry stays in the pot.

### Seasons and divisions

Seasons follow the calendar month. When a month ends, the top `Config.Ranking.hallSize` players of the season are
saved in the hall of fame and every rating, win and loss starts again; the ranking screen has a tab with the last
`hallSeasons` seasons. Set `Config.Ranking.seasons = false` for one endless ranking. Divisions are rating
thresholds in `Config.Ranking.divisions` (name, minimum rating and colour); add, remove or rename them freely.

### Admin commands

`/armwrestlingreset` clears the whole ranking and `/armwrestlingboard` prints the coords of a wall ranking board.
Both are restricted to `group.admin`; change it in `Config.Admin.ace`.

## For developers

```lua
exports.xex_armwrestling:IsWrestling(source)   -- server
exports.xex_armwrestling:GetStats(identifier)  -- server: { rating, wins, losses, streak, best_streak, fastest, rank, needed }
```

| Event (server, local) | Arguments |
| --- | --- |
| `xex_armwrestling:matchFinished` | `data` = `{ winner, loser, players, reason, duration, bet, ranked }` |
| `xex_armwrestling:tournamentFinished` | `data` = `{ id, name, winner, runnerUp, players, pot, prize }` |

`winner` and `loser` are server ids (`nil` on a draw), `reason` is `pin`, `time` or `forfeit` and `duration` is in
milliseconds.

```lua
AddEventHandler('xex_armwrestling:matchFinished', function(data)
    -- battle pass progress, logs, analytics...
end)
```

`Config.Hooks` does the same from the config, plus a permission check and a strength multiplier:

```lua
Config.Hooks = {
    canPlay = function(source)
        return true -- false = this player can't arm wrestle right now
    end,
    power = function(source)
        return 1.0 -- multiplier of every push, clamped between 0.5 and 1.5 (e.g. a gym skill)
    end,
    onMatchFinished = function(data) end,
    onTournamentFinished = function(data) end, -- same data as the tournamentFinished event
}
```

Keep server-specific code in your own resource and listen to the event: updates of xex_armwrestling then never
overwrite it.

## Security

Players only ask to challenge someone, answer a challenge and say how many times they tapped. The server:

- accepts only props listed in `Config.Models`, and for models that are not usable everywhere, only at a table of
  `Config.Tables`; both players must really stand at the table and the table must be free;
- takes both stakes before the match starts, or neither, and pays or refunds them exactly once;
- accepts at most `Config.Match.maxPressRate` pushes per second from each player, whatever the client sends;
- applies stamina and strength itself, moves the arm and decides the winner and the time;
- ends the match if a player leaves, walks away or disconnects, and never ranks matches that were too short or
  repeated too often between the same two players.

## FAQ

**Do I need a target resource?**
Only to use props that are already on the map. Tables from `Config.Tables` also work with `[E]`.

**Can I turn off the bets or the ranking?**
Yes: `Config.Bets.enabled = false` and `Config.Ranking.enabled = false`.

**Does a stronger character push harder?**
Not by default. Return a multiplier from `Config.Hooks.power` to connect your own skills or gym resource.

**The players stand in the wrong place at my table.**
Adjust `axis` and `offset` of that model in `Config.Models`.

**How do I reset the ranking?**
`/armwrestlingreset`, or empty the `xex_armwrestling` table. With seasons on, it also starts again every month.

**Can people watch?**
Yes. Anyone within `Config.Spectators.distance` of a match sees it live; set `enabled = false` to turn it off.

## License

MIT. Use it, change it and share it; keep the copyright notice. See LICENSE.
