Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active Aug 30, 2022
Embed
What would you like to do?
import { equal } from 'assert';
import { FIRST_FRAME } from './Netcode';
import { NetcodeClient } from './NetcodeClient';
import { NetcodeServer } from './NetcodeServer';
type UserId = 'a' | 'b';
type Input = 'RUN' | null;
interface Entity {
x: number;
v: number;
i: Input;
}
type State = Record<UserId, Entity>;
const initialState: State = {
a: { x: -10, v: 3, i: null },
b: { x: 10, v: -3, i: null },
};
function simulate(state: State): State {
const entries = Object.entries(state).map(([id, entity]) => [
id,
{
x: entity.x + entity.v,
v: entity.v + (entity.i === 'RUN' ? 1 : 0),
},
]);
return Object.fromEntries(entries);
}
describe('Netcode state management', () => {
it('should be identical after one frame', () => {
const client = new NetcodeClient(simulate, initialState);
const server = new NetcodeServer(simulate, initialState);
client.runFrame();
server.runFrame();
equal(client.serialize(), server.serialize());
});
it('client should respect incoming state over its own', () => {
const client = new NetcodeClient(simulate, {
a: { x: 0, v: 0, i: null },
b: { x: 0, v: 0, i: null },
});
const server = new NetcodeServer(simulate, initialState);
client.reciveState(server.serialize());
client.runFrame();
server.runFrame();
equal(client.serialize(), server.serialize());
});
it('client should rewrite history if server says it was different', () => {
const client = new NetcodeClient(simulate, initialState);
const server = new NetcodeServer(simulate, {
...initialState,
a: { ...initialState.a, v: 0 },
});
client.runFrame();
client.runFrame();
client.reciveState(server.serialize());
server.runFrame();
server.runFrame();
equal(client.serialize(), server.serialize());
});
it('client should rewrite history if a frame is altered', () => {
const client = new NetcodeClient(simulate, initialState);
const server = new NetcodeServer(simulate, {
...initialState,
a: { ...initialState.a, i: 'RUN' },
});
client.runFrame();
client.runFrame();
client.alterFrame(FIRST_FRAME, (state) => ({
...state,
a: { ...state.a, i: 'RUN' },
}));
server.runFrame();
server.runFrame();
equal(client.serialize(), server.serialize());
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment