# Gameplay in C#

You can write your game's scripts in C# instead of Luau, or beside it. A script whose
name ends in `.cs` gets the same engine calls a Luau script has, live reload while you
work, and a desktop export your players can run without installing .NET. This page is
how to write a game with it; the [C# reference](../reference/csharp.md) has every
call, side by side with Luau's.

> **Note.** C# runs on the desktop today. On the web it runs through
> [Fusion](fifth.md), a subset; on phones it is in progress; and multiplayer refuses a
> game in C#. See [what C# cannot do yet](csharp.md#what-c-cannot-do-yet).

## What you need

- The .NET SDK, version 10 or later.
- `frost` with C#: the download whose name ends in `-csharp`.

Without it, a game with a `.cs` script is refused (`E0482`).

## A script

```csharp
using Ven;

[State]                                  // the one struct the script keeps between steps
public struct Game
{
    public int Score;
    public Thing Hero;                   // a thing of the game, or Thing.None
}

public static class Main
{
    public static void OnScene(string scene, ref Game game)
    {
        game.Hero = World.Spawn("Transform", "Sprite", name: "hero");
        World.Set(game.Hero, "Sprite", "image", "art/hero.png");
    }

    public static void Step(float dt, TransformColumns transform, ref Game game)
    {
        int row = transform.Row(game.Hero);
        if (row >= 0) transform.X[row] += Input.Get(0, "move_x") * 90 * dt;
        if (Input.Held(0, "fire")) Sound.Play("sounds/pew.wav", vary: 0.1);
    }
}
```

`Step` runs once a step, sixty times a second, as Luau's `step(dt)` does, and `OnScene`
when a scene has started.

- **Components come as columns.** `Step` names the components it walks, and each is
  lent to it as the world's own memory for the length of the step: one span for each
  number or true-or-false field (`transform.X[row]`), with `Rows`, `Thing(row)` (the
  thing at a row) and `Row(thing)` (a thing's row, or -1). This is the fast path, and
  what Luau's `each`, `get` and `set` are in C#.
- **Everything else is a call**: `World.Find`, `World.Spawn`, `Input.Get`, `Sound.Play`,
  `Scene.Load` and the rest. The [reference](../reference/csharp.md) lists the C#
  call for every Luau one.

## What your script keeps

The struct you mark `[State]` is your script's memory between steps, as Luau's `state`
is. It is saved with the game, covered by the checksum and put back by a seek, a test or
a rollback. It holds `bool`, `int`, `uint`, `float`, `double` and `Thing` fields; keep
anything else in components.

A `static` field is not saved, exactly as a Luau `local` is not. Use one only for a
cache you can build again, and empty it in `OnRestore()`. `frost test --restore` finds a
static that changes how the game plays.

## Changes happen when the step returns

While your `Step` runs, it holds the world's memory, so the world's shape does not
change under it. A call reads the world as it is; what a call changes (`Set`, `Spawn`,
`Despawn`, `Send`, `Tween`, `Place`, `Ui.Focus`, `Scene.Load`) is done when your `Step`
or `OnScene` returns, in the order you asked, before the next script runs. In practice:

- A thing you `World.Spawn` exists from the next step. You can `Set`, `Despawn`, `Tween`
  and `Send` it at once, and keep it in your `[State]` struct, but columns do not have
  it yet (`Row` gives -1) and `Get` and `Has` refuse it.
- `World.Get` reads the world as the step found it, plus what you wrote through spans. A
  `World.Set` you made earlier in the same step is not seen yet.
- So make things after walking the ones that are there. (A Luau loop over `each` after a
  `spawn` finds the new thing; a C# loop over a column does not.)

## Differences from Luau worth knowing

- **Time and chance come from the game.** `DateTime.Now`, a `Stopwatch`, `new Random()`
  with no seed, `Random.Shared` and `Guid.NewGuid()` are refused when the script
  compiles (`VEN105`, in `E0309`), because a replay must play the same on every
  machine. Time is `dt`; chance is `World.Random`. A `Random` with a seed is yours to
  use.
- **Maths that is the same everywhere.** Use `Maths` for sine and its kin, `pow` and
  `log`: it gives the same bits on every machine. `System.Math.Sin` and its kin are
  refused (`VEN104`).
- **`%` keeps the sign in C#.** `-30 % 360` is 330 in Luau and -30 in C#. For an angle
  kept from 0 to 360, write `a - Math.Floor(a / 360) * 360`.
- **Luau scripts run first**, then C# scripts, each in the project's order. A game can
  mix the two.
- **Tables.** `Data.Get("levels/one.toml")` and `Save.Get` give a `Table`: flat, each
  value under its path, so Luau's `level.waves[1].count` is
  `.Number("waves.1.count")`.

## While you work

- Save a `.cs` file under `frost dev` and the new code is swapped in, keeping the world
  and your `[State]` struct. Code that does not compile is refused (`E0309`, with its
  line) and the old code runs on.
- A call that cannot be done stops the step with `E0302`, on your script's own line and
  column.
- `World.Print` lines carry the file and line of the call, as Luau's `print` does.
- `frost check` writes a project you can start a C# language server on.
- `frost dap` debugs a C# game from your editor with your own netcoredbg (on your `PATH`,
  or named by `FROST_NETCOREDBG`): breakpoints go in your `.cs` files, and a stop shows
  .NET's threads, stack, locals and expressions. A game in both Luau and C# cannot be
  debugged this way yet.

## Shipping a C# game

```sh
frost export desktop game.toml --out mygame-desktop
```

compiles your C# scripts ahead of time, with .NET's Native AOT, into one native library
beside the game. The person who plays your game needs no .NET. After you change a
script, export again: a player refuses a library that was not compiled from its game's
scripts.

Native AOT needs .NET's ILCompiler package for your machine. If your .NET SDK has it
beside itself (Homebrew's does), nothing is downloaded. If not, the export stops with
`E0311`, names the package, and tells you that `--fetch` lets it be fetched once from
nuget.org and kept in frost's cache.

For the web, see [Fusion](fifth.md). A web export of a C# script that is not marked
`[Fifth]` is refused.

## Whole games to read

Two of the templates have been written in C# as well: Vigil (the arena game; played on
its recording it matches the Luau one at every step, apart from what each script keeps)
and Embers (the 3D game, with a character on 3D physics, sensors, chasers, the interface
and the following camera).
[Caravan](../showcase.md), an open-world game, is written in C# too.

## What C# cannot do yet

- **Phones.** C# runs on the desktop only; phones are in progress. Keep a phone game in
  Luau.
- **The web**, except through [Fusion](fifth.md), which cannot spawn things, read input,
  play sounds or load scenes.
- **Multiplayer.** A game in C# is refused (`E0543`).
- **Libraries** are compiled into each script, so in practice one script is the root
  that composes the rest, and a library's compile errors are reported at the script.
- **A script cannot read an event it sent**, and a spawned thing is seen the next step.
- `World.Spawn` takes at most 8 component names.
- `HashCode` and `GetHashCode` differ from run to run: never let them decide anything
  in your game.
