Keep track of score and reset game after score

Client: only set direction on change
This commit is contained in:
2022-11-04 13:00:54 +01:00
parent cd7a1f15a9
commit 2fb395a8d4
2 changed files with 49 additions and 22 deletions

View File

@ -16,15 +16,13 @@ public struct PongGameState {
BallState = PongBallState.Initial,
Paddle1 = PongPaddleState.Initial,
Paddle2 = PongPaddleState.Initial,
Status = GameStatus.WaitingForPlayers,
WinnerLeft = null
Status = GameStatus.WaitingForPlayers
};
public PongPaddleState Paddle1;
public PongPaddleState Paddle2;
public PongBallState BallState;
public GameStatus Status;
public bool? WinnerLeft;
public static void Update(ref PongGameState state) {
if (state.Status is not GameStatus.InProgress) return;
@ -32,15 +30,24 @@ public struct PongGameState {
PongPaddleState.Update(ref state.Paddle1);
PongPaddleState.Update(ref state.Paddle2);
PongBallState.Update(ref state.BallState);
var ballX = state.BallState.Pos.X;
if (ballX is < 0 or > WIDTH) {
state.WinnerLeft = ballX < 0;
state.Status = GameStatus.Finished;
return;
}
Collide(in state.Paddle1, ref state.BallState, true);
Collide(in state.Paddle2, ref state.BallState, false);
switch (state.BallState.Pos.X) {
case > WIDTH:
AnnounceScore(ref state, ref state.Paddle1);
return;
case < 0:
AnnounceScore(ref state, ref state.Paddle2);
return;
}
}
private static void AnnounceScore(ref PongGameState state, ref PongPaddleState winner) {
winner.Score++;
state.Paddle1.ResetPosition();
state.Paddle2.ResetPosition();
state.BallState.ResetPosition();
}
private static void Collide(in PongPaddleState paddle, ref PongBallState ballState, bool left) {
@ -91,6 +98,12 @@ public struct PongGameState {
}
public RectangleF GetCollider() => new(Pos.X - BALL_RADIUS, Pos.Y - BALL_RADIUS, 2 * BALL_RADIUS, 2 * BALL_RADIUS);
public void ResetPosition() {
BallAngle = 0.0f;
Pos.X = WIDTH / 2;
Pos.Y = HEIGHT / 2;
}
}
public struct PongPaddleState {
@ -98,19 +111,27 @@ public struct PongGameState {
public const float PADDLE_HALF_LENGTH = PADDLE_LENGTH / 2;
public const float PADDLE_WIDTH = PADDLE_LENGTH / 5;
public const float PADDLE_SPEED = 8;
private const float PADDLE_INITIAL_HEIGHT = HEIGHT / 2;
public static readonly PongPaddleState Initial = new() {
Score = 0,
Direction = PongPaddleDirection.Stop,
Height = HEIGHT / 2
Height = PADDLE_INITIAL_HEIGHT
};
public float Height;
public PongPaddleDirection Direction;
public int Score;
public static void Update(ref PongPaddleState state) {
state.Height = Math.Clamp(state.Height - ((int)state.Direction) * PADDLE_SPEED, PADDLE_HALF_LENGTH, HEIGHT - PADDLE_HALF_LENGTH);
state.Height = Math.Clamp(state.Height + ((int)state.Direction) * PADDLE_SPEED, PADDLE_HALF_LENGTH, HEIGHT - PADDLE_HALF_LENGTH);
}
public RectangleF GetCollider(float x) => new(x - PADDLE_WIDTH / 2, Height - PADDLE_HALF_LENGTH, PADDLE_WIDTH, PADDLE_LENGTH);
public void ResetPosition() {
Direction = PongPaddleDirection.Stop;
Height = PADDLE_INITIAL_HEIGHT;
}
}
}