Last active
August 30, 2022 21:15
-
-
Save amatiasq/2f81e5dd72ba793d4f5a211cb7a87e4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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