feat: added web view 1v1
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideZoneChangeDetection({ eventCoalescing: true }),
|
||||
provideHttpClient(),
|
||||
provideRouter(routes)
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
<router-outlet />
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { GameComponent } from './pages/game/game.component';
|
||||
import { WelcomeComponent } from './pages/welcome/welcome.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: WelcomeComponent },
|
||||
{ path: 'game/:gameId', component: GameComponent },
|
||||
{ path: '**', redirectTo: '' }
|
||||
];
|
||||
@@ -0,0 +1,18 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { App } from './app';
|
||||
|
||||
describe('App', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideRouter([])]
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('should create the app', () => {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
const app = fixture.componentInstance;
|
||||
expect(app).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.css'
|
||||
})
|
||||
export class App {
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
.board-shell {
|
||||
width: min(100%, 82dvh, 760px);
|
||||
max-width: calc(100dvw - 2rem);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.board-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, 1fr);
|
||||
border: 2px solid #5A2C28;
|
||||
border-radius: 10px 10px 0 0;
|
||||
overflow: hidden;
|
||||
background: #5A2C28;
|
||||
}
|
||||
|
||||
.square {
|
||||
position: relative;
|
||||
aspect-ratio: 1 / 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.square.light {
|
||||
background-image: url('/arabian-chess/sprites/board/board_square_white.png');
|
||||
}
|
||||
|
||||
.square.dark {
|
||||
background-image: url('/arabian-chess/sprites/board/board_square_black.png');
|
||||
}
|
||||
|
||||
.square.highlighted::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 28%;
|
||||
height: 28%;
|
||||
border-radius: 50%;
|
||||
background: rgba(193, 158, 245, 0.75);
|
||||
border: 2px solid #5A2C28;
|
||||
}
|
||||
|
||||
.square.selected {
|
||||
outline: 3px solid #BA6D4B;
|
||||
outline-offset: -3px;
|
||||
}
|
||||
|
||||
.board-bottom {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border: 2px solid #5A2C28;
|
||||
border-top: 0;
|
||||
border-radius: 0 0 10px 10px;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<div class="board-shell">
|
||||
<div class="board-grid">
|
||||
@for (square of squares; track trackByCoordinate($index, square)) {
|
||||
<button
|
||||
type="button"
|
||||
class="square"
|
||||
[class.light]="square.isLight"
|
||||
[class.dark]="!square.isLight"
|
||||
[class.selected]="isSelected(square)"
|
||||
[class.highlighted]="isHighlighted(square)"
|
||||
[attr.data-square]="square.coordinate"
|
||||
(click)="onSquareClick(square)"
|
||||
>
|
||||
<app-chess-piece [pieceCode]="square.pieceCode" />
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<img class="board-bottom" src="/arabian-chess/sprites/board/board_bottom.png" alt="Board frame" />
|
||||
</div>
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
|
||||
import { ChessPieceComponent } from '../chess-piece/chess-piece.component';
|
||||
|
||||
interface BoardSquare {
|
||||
coordinate: string;
|
||||
isLight: boolean;
|
||||
pieceCode: string | null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-chess-board',
|
||||
standalone: true,
|
||||
imports: [ChessPieceComponent],
|
||||
templateUrl: './chess-board.component.html',
|
||||
styleUrl: './chess-board.component.css'
|
||||
})
|
||||
export class ChessBoardComponent implements OnChanges {
|
||||
@Input({ required: true }) fen = '';
|
||||
@Input() selectedSquare: string | null = null;
|
||||
@Input() highlightedSquares: string[] = [];
|
||||
@Output() squareSelected = new EventEmitter<string>();
|
||||
|
||||
squares: BoardSquare[] = [];
|
||||
private highlightedSquareSet = new Set<string>();
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['fen']) {
|
||||
this.squares = this.buildSquares(this.fen);
|
||||
}
|
||||
|
||||
if (changes['highlightedSquares']) {
|
||||
this.highlightedSquareSet = new Set(this.highlightedSquares);
|
||||
}
|
||||
}
|
||||
|
||||
trackByCoordinate(_index: number, square: BoardSquare): string {
|
||||
return square.coordinate;
|
||||
}
|
||||
|
||||
onSquareClick(square: BoardSquare): void {
|
||||
this.squareSelected.emit(square.coordinate);
|
||||
}
|
||||
|
||||
isSelected(square: BoardSquare): boolean {
|
||||
return this.selectedSquare === square.coordinate;
|
||||
}
|
||||
|
||||
isHighlighted(square: BoardSquare): boolean {
|
||||
return this.highlightedSquareSet.has(square.coordinate);
|
||||
}
|
||||
|
||||
private buildSquares(fen: string): BoardSquare[] {
|
||||
const placement = fen.split(' ')[0] ?? '';
|
||||
const rows = placement.split('/');
|
||||
if (rows.length !== 8) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const squares: BoardSquare[] = [];
|
||||
|
||||
rows.forEach((row, rowIndex) => {
|
||||
let column = 0;
|
||||
|
||||
for (const char of row) {
|
||||
if (char >= '1' && char <= '8') {
|
||||
const emptyCount = Number(char);
|
||||
for (let step = 0; step < emptyCount; step += 1) {
|
||||
squares.push(this.createSquare(rowIndex, column, null));
|
||||
column += 1;
|
||||
}
|
||||
} else {
|
||||
squares.push(this.createSquare(rowIndex, column, char));
|
||||
column += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return squares;
|
||||
}
|
||||
|
||||
private createSquare(rowIndex: number, column: number, pieceCode: string | null): BoardSquare {
|
||||
const file = String.fromCharCode(97 + column);
|
||||
const rank = String(8 - rowIndex);
|
||||
return {
|
||||
coordinate: `${file}${rank}`,
|
||||
isLight: (rowIndex + column) % 2 === 0,
|
||||
pieceCode
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
.piece {
|
||||
width: 90%;
|
||||
height: 90%;
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
@if (pieceCode) {
|
||||
<img class="piece" [src]="spriteUrl" [alt]="pieceCode" />
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-chess-piece',
|
||||
standalone: true,
|
||||
templateUrl: './chess-piece.component.html',
|
||||
styleUrl: './chess-piece.component.css'
|
||||
})
|
||||
export class ChessPieceComponent {
|
||||
@Input({ required: true }) pieceCode: string | null = null;
|
||||
|
||||
get spriteUrl(): string {
|
||||
if (!this.pieceCode) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const color = this.pieceCode === this.pieceCode.toUpperCase() ? 'white' : 'black';
|
||||
const pieceName = this.getPieceName(this.pieceCode.toLowerCase());
|
||||
return `/arabian-chess/sprites/pieces/${color}_${pieceName}.png`;
|
||||
}
|
||||
|
||||
private getPieceName(piece: string): string {
|
||||
switch (piece) {
|
||||
case 'k':
|
||||
return 'king';
|
||||
case 'q':
|
||||
return 'queen';
|
||||
case 'r':
|
||||
return 'rook';
|
||||
case 'b':
|
||||
return 'bishop';
|
||||
case 'n':
|
||||
return 'knight';
|
||||
case 'p':
|
||||
return 'pawn';
|
||||
default:
|
||||
return 'pawn';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export type GameTurn = 'white' | 'black';
|
||||
|
||||
export type GameStatus =
|
||||
| 'started'
|
||||
| 'check'
|
||||
| 'checkmate'
|
||||
| 'stalemate'
|
||||
| 'resign'
|
||||
| 'draw'
|
||||
| 'drawOffered'
|
||||
| 'fiftyMoveAvailable'
|
||||
| 'promotionPending'
|
||||
| 'insufficientMaterial';
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
fen: string;
|
||||
pgn: string;
|
||||
turn: GameTurn;
|
||||
status: GameStatus;
|
||||
winner?: GameTurn | null;
|
||||
moves: string[];
|
||||
undoAvailable: boolean;
|
||||
redoAvailable: boolean;
|
||||
}
|
||||
|
||||
export interface GameFull {
|
||||
gameId: string;
|
||||
white: PlayerInfo;
|
||||
black: PlayerInfo;
|
||||
state: GameState;
|
||||
}
|
||||
|
||||
export interface LegalMove {
|
||||
from: string;
|
||||
to: string;
|
||||
uci: string;
|
||||
moveType: string;
|
||||
promotion?: 'queen' | 'rook' | 'bishop' | 'knight' | null;
|
||||
}
|
||||
|
||||
export interface LegalMovesResponse {
|
||||
moves: LegalMove[];
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
code: string;
|
||||
message: string;
|
||||
field?: string | null;
|
||||
}
|
||||
|
||||
export interface GameFullEvent {
|
||||
type: 'gameFull';
|
||||
game: GameFull;
|
||||
}
|
||||
|
||||
export interface GameStateEvent {
|
||||
type: 'gameState';
|
||||
state: GameState;
|
||||
}
|
||||
|
||||
export interface ErrorEvent {
|
||||
type: 'error';
|
||||
error: ApiError;
|
||||
}
|
||||
|
||||
export type GameStreamEvent = GameFullEvent | GameStateEvent | ErrorEvent;
|
||||
@@ -0,0 +1,119 @@
|
||||
.game-shell {
|
||||
height: 100dvh;
|
||||
padding: clamp(0.75rem, 2vw, 1.5rem);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.game-card {
|
||||
max-width: 1100px;
|
||||
height: 100%;
|
||||
margin: 0 auto;
|
||||
background: #F3C8A0;
|
||||
border: 2px solid #5A2C28;
|
||||
border-radius: 12px;
|
||||
padding: clamp(0.75rem, 1.5vw, 1.25rem);
|
||||
box-shadow: 0 8px 24px rgba(90, 44, 40, 0.2);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
header {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2 {
|
||||
color: #5A2C28;
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
|
||||
.meta {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
display: inline-block;
|
||||
margin-bottom: 0.5rem;
|
||||
color: #5A2C28;
|
||||
}
|
||||
|
||||
.top-section {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.state-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.panel {
|
||||
background: #B9C2DA;
|
||||
border-radius: 10px;
|
||||
border: 2px solid #5A2C28;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.panel p {
|
||||
margin: 0.3rem 0;
|
||||
}
|
||||
|
||||
code {
|
||||
display: block;
|
||||
background: #E1EAA9;
|
||||
border-radius: 8px;
|
||||
padding: 0.5rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.move-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.board-section {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: clamp(0.35rem, 1vw, 0.75rem);
|
||||
border-radius: 10px;
|
||||
border: 2px solid #5A2C28;
|
||||
background: #B9DAD1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
input {
|
||||
border: 2px solid #5A2C28;
|
||||
border-radius: 10px;
|
||||
background: #B9DAD1;
|
||||
padding: 0.6rem 0.75rem;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 2px solid #5A2C28;
|
||||
border-radius: 10px;
|
||||
background: #C19EF5;
|
||||
color: #5A2C28;
|
||||
padding: 0.6rem 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #BA6D4B;
|
||||
color: #F3C8A0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-top: 0.5rem;
|
||||
color: #5A2C28;
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<main class="game-shell">
|
||||
<section class="game-card">
|
||||
<header>
|
||||
<a routerLink="/" class="back-link">Back</a>
|
||||
<h1>1 vs 1 Game</h1>
|
||||
<p class="meta">Game ID: <strong>{{ gameId }}</strong></p>
|
||||
</header>
|
||||
|
||||
@if (loading) {
|
||||
<p>Loading game state...</p>
|
||||
} @else if (state) {
|
||||
<section class="top-section">
|
||||
<div class="state-grid">
|
||||
<div class="panel">
|
||||
<h2>Status</h2>
|
||||
<p>Turn: <strong>{{ state.turn }}</strong></p>
|
||||
<p>Status: <strong>{{ state.status }}</strong></p>
|
||||
<p>FEN:</p>
|
||||
<code>{{ state.fen }}</code>
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<h2>Moves</h2>
|
||||
<p>PGN: {{ state.pgn || 'No moves yet' }}</p>
|
||||
<p>Played UCI: {{ state.moves.length ? state.moves.join(', ') : 'None' }}</p>
|
||||
<p>Legal UCI: {{ legalMoveUciList.length ? legalMoveUciList.join(', ') : 'None' }}</p>
|
||||
<p>Board: click your piece to highlight legal targets.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="move-form" (ngSubmit)="submitMove()">
|
||||
<label for="uciMove">Play move (UCI)</label>
|
||||
<input id="uciMove" name="uciMove" [(ngModel)]="moveInput" placeholder="e2e4" />
|
||||
<button type="submit">Send Move</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="board-section">
|
||||
<app-chess-board
|
||||
[fen]="state.fen"
|
||||
[selectedSquare]="selectedSquare"
|
||||
[highlightedSquares]="highlightedSquares"
|
||||
(squareSelected)="onBoardSquareSelected($event)"
|
||||
/>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (errorMessage) {
|
||||
<p class="error">{{ errorMessage }}</p>
|
||||
}
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,250 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { interval, startWith, Subscription, switchMap } from 'rxjs';
|
||||
import { ChessBoardComponent } from '../../components/chess-board/chess-board.component';
|
||||
import { GameFull, GameState, GameStreamEvent, LegalMove } from '../../models/game.models';
|
||||
import { GameApiService } from '../../services/game-api.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-game',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, RouterLink, ChessBoardComponent],
|
||||
templateUrl: './game.component.html',
|
||||
styleUrl: './game.component.css'
|
||||
})
|
||||
export class GameComponent implements OnInit, OnDestroy {
|
||||
gameId = '';
|
||||
game: GameFull | null = null;
|
||||
errorMessage = '';
|
||||
moveInput = '';
|
||||
legalMoves: LegalMove[] = [];
|
||||
loading = true;
|
||||
selectedSquare: string | null = null;
|
||||
highlightedSquares: string[] = [];
|
||||
|
||||
private selectedSquareMoves: LegalMove[] = [];
|
||||
private streamSubscription: Subscription | null = null;
|
||||
private pollSubscription: Subscription | null = null;
|
||||
private routeSubscription: Subscription | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly gameApi: GameApiService
|
||||
) {}
|
||||
|
||||
get state(): GameState | null {
|
||||
return this.game?.state ?? null;
|
||||
}
|
||||
|
||||
get legalMoveUciList(): string[] {
|
||||
return this.legalMoves.map((move) => move.uci);
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.routeSubscription = this.route.paramMap.subscribe((paramMap) => {
|
||||
const id = paramMap.get('gameId');
|
||||
if (!id) {
|
||||
this.errorMessage = 'Missing gameId in route.';
|
||||
this.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.gameId = id;
|
||||
this.loadGame();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.routeSubscription?.unsubscribe();
|
||||
this.streamSubscription?.unsubscribe();
|
||||
this.pollSubscription?.unsubscribe();
|
||||
}
|
||||
|
||||
onBoardSquareSelected(square: string): void {
|
||||
if (!this.state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedSquare && this.highlightedSquares.includes(square)) {
|
||||
const selectedMove = this.selectedSquareMoves.find((move) => move.to === square);
|
||||
if (selectedMove) {
|
||||
this.moveInput = selectedMove.uci;
|
||||
this.submitMove();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const piece = this.getPieceAtSquare(this.state.fen, square);
|
||||
if (!piece || !this.isCurrentTurnPiece(piece)) {
|
||||
this.clearSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
this.errorMessage = '';
|
||||
this.gameApi.getLegalMoves(this.gameId, square).subscribe({
|
||||
next: (response) => {
|
||||
this.selectedSquare = square;
|
||||
this.selectedSquareMoves = response.moves;
|
||||
this.highlightedSquares = response.moves.map((move) => move.to);
|
||||
},
|
||||
error: () => {
|
||||
this.clearSelection();
|
||||
this.errorMessage = 'Could not load legal moves for selected square.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
submitMove(): void {
|
||||
const uci = this.moveInput.trim();
|
||||
if (!uci) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.errorMessage = '';
|
||||
this.gameApi.makeMove(this.gameId, uci).subscribe({
|
||||
next: (state) => {
|
||||
if (this.game) {
|
||||
this.game = { ...this.game, state };
|
||||
}
|
||||
this.moveInput = '';
|
||||
this.clearSelection();
|
||||
this.loadLegalMoves();
|
||||
},
|
||||
error: (error: { error?: { message?: string } }) => {
|
||||
this.errorMessage = error.error?.message ?? 'Move rejected.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadGame(): void {
|
||||
this.loading = true;
|
||||
this.errorMessage = '';
|
||||
this.clearSelection();
|
||||
this.streamSubscription?.unsubscribe();
|
||||
this.pollSubscription?.unsubscribe();
|
||||
|
||||
this.gameApi.getGame(this.gameId).subscribe({
|
||||
next: (game) => {
|
||||
this.game = game;
|
||||
this.loading = false;
|
||||
this.loadLegalMoves();
|
||||
this.startStream();
|
||||
this.startPolling();
|
||||
},
|
||||
error: (error: { error?: { message?: string } }) => {
|
||||
this.errorMessage = error.error?.message ?? `Could not load game ${this.gameId}.`;
|
||||
this.loading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadLegalMoves(): void {
|
||||
this.gameApi.getLegalMoves(this.gameId).subscribe({
|
||||
next: (response) => {
|
||||
this.legalMoves = response.moves;
|
||||
},
|
||||
error: () => {
|
||||
this.legalMoves = [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private startStream(): void {
|
||||
this.streamSubscription = this.gameApi.streamGame(this.gameId).subscribe({
|
||||
next: (event) => this.applyStreamEvent(event),
|
||||
error: () => {
|
||||
this.errorMessage = 'Live stream disconnected.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private startPolling(): void {
|
||||
this.pollSubscription = interval(1500)
|
||||
.pipe(
|
||||
startWith(0),
|
||||
switchMap(() => this.gameApi.getGame(this.gameId))
|
||||
)
|
||||
.subscribe({
|
||||
next: (game) => {
|
||||
const previousMoves = this.game?.state.moves.join(',') ?? '';
|
||||
this.game = game;
|
||||
if (previousMoves !== game.state.moves.join(',')) {
|
||||
this.clearSelection();
|
||||
this.loadLegalMoves();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private applyStreamEvent(event: GameStreamEvent): void {
|
||||
if (event.type === 'gameFull') {
|
||||
this.game = event.game;
|
||||
this.clearSelection();
|
||||
this.loadLegalMoves();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'gameState' && this.game) {
|
||||
const moveCountBefore = this.game.state.moves.length;
|
||||
this.game = { ...this.game, state: event.state };
|
||||
if (event.state.moves.length !== moveCountBefore) {
|
||||
this.clearSelection();
|
||||
}
|
||||
this.loadLegalMoves();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'error') {
|
||||
this.errorMessage = event.error.message;
|
||||
}
|
||||
}
|
||||
|
||||
private clearSelection(): void {
|
||||
this.selectedSquare = null;
|
||||
this.selectedSquareMoves = [];
|
||||
this.highlightedSquares = [];
|
||||
}
|
||||
|
||||
private isCurrentTurnPiece(pieceCode: string): boolean {
|
||||
if (!this.state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const isWhitePiece = pieceCode === pieceCode.toUpperCase();
|
||||
return (this.state.turn === 'white' && isWhitePiece) || (this.state.turn === 'black' && !isWhitePiece);
|
||||
}
|
||||
|
||||
private getPieceAtSquare(fen: string, targetSquare: string): string | null {
|
||||
const placement = fen.split(' ')[0] ?? '';
|
||||
const rows = placement.split('/');
|
||||
if (rows.length !== 8 || targetSquare.length !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const file = targetSquare.charCodeAt(0) - 97;
|
||||
const rank = Number(targetSquare[1]);
|
||||
const rowIndex = 8 - rank;
|
||||
|
||||
if (Number.isNaN(rank) || file < 0 || file > 7 || rowIndex < 0 || rowIndex > 7) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let column = 0;
|
||||
for (const symbol of rows[rowIndex]) {
|
||||
if (symbol >= '1' && symbol <= '8') {
|
||||
column += Number(symbol);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (column === file) {
|
||||
return symbol;
|
||||
}
|
||||
|
||||
column += 1;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
.welcome-shell {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.welcome-card {
|
||||
width: min(900px, 100%);
|
||||
border-radius: 12px;
|
||||
border: 2px solid #5A2C28;
|
||||
background: #F3C8A0;
|
||||
padding: 2rem;
|
||||
box-shadow: 0 8px 24px rgba(90, 44, 40, 0.2);
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0 0 0.25rem;
|
||||
color: #5A2C28;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0 0 1.25rem;
|
||||
}
|
||||
|
||||
.mode-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.mode {
|
||||
border: 2px solid #5A2C28;
|
||||
border-radius: 10px;
|
||||
padding: 1rem;
|
||||
text-align: left;
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.mode span {
|
||||
font-size: 1.15rem;
|
||||
color: #5A2C28;
|
||||
}
|
||||
|
||||
.mode small {
|
||||
color: #5A2C28;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.mode-active {
|
||||
background: #B9DAD1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mode-active:hover:enabled {
|
||||
background: #B9C2DA;
|
||||
}
|
||||
|
||||
.mode-disabled {
|
||||
background: #E1EAA9;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #5A2C28;
|
||||
font-weight: 700;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<main class="welcome-shell">
|
||||
<section class="welcome-card">
|
||||
<h1>Welcome to NowChess</h1>
|
||||
<p>Pick a mode to begin.</p>
|
||||
|
||||
<div class="mode-grid">
|
||||
<button type="button" class="mode mode-disabled" disabled>
|
||||
<span>Bot</span>
|
||||
<small>Coming soon</small>
|
||||
</button>
|
||||
|
||||
<button type="button" class="mode mode-active" (click)="startOneVsOne()" [disabled]="creating">
|
||||
<span>1 vs 1</span>
|
||||
<small>{{ creating ? 'Creating game...' : 'Start now' }}</small>
|
||||
</button>
|
||||
|
||||
<button type="button" class="mode mode-disabled" disabled>
|
||||
<span>Future Technique</span>
|
||||
<small>Placeholder</small>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (errorMessage) {
|
||||
<p class="error">{{ errorMessage }}</p>
|
||||
}
|
||||
</section>
|
||||
</main>
|
||||
@@ -0,0 +1,43 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { finalize } from 'rxjs';
|
||||
import { GameApiService } from '../../services/game-api.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-welcome',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './welcome.component.html',
|
||||
styleUrl: './welcome.component.css'
|
||||
})
|
||||
export class WelcomeComponent {
|
||||
creating = false;
|
||||
errorMessage = '';
|
||||
|
||||
constructor(
|
||||
private readonly router: Router,
|
||||
private readonly gameApi: GameApiService
|
||||
) {}
|
||||
|
||||
startOneVsOne(): void {
|
||||
if (this.creating) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.errorMessage = '';
|
||||
this.creating = true;
|
||||
|
||||
this.gameApi
|
||||
.createGame()
|
||||
.pipe(finalize(() => (this.creating = false)))
|
||||
.subscribe({
|
||||
next: (game) => {
|
||||
void this.router.navigate(['/game', game.gameId]);
|
||||
},
|
||||
error: (error: { error?: { message?: string } }) => {
|
||||
this.errorMessage = error.error?.message ?? 'Unable to create a game.';
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { environment } from '../../environments/environment';
|
||||
import {
|
||||
ErrorEvent,
|
||||
GameFull,
|
||||
GameState,
|
||||
GameStreamEvent,
|
||||
LegalMovesResponse
|
||||
} from '../models/game.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class GameApiService {
|
||||
private readonly apiBase = environment.apiBaseUrl;
|
||||
private readonly wsBase = environment.wsBaseUrl;
|
||||
|
||||
constructor(private readonly http: HttpClient) {}
|
||||
|
||||
createGame(): Observable<GameFull> {
|
||||
return this.http.post<GameFull>(`${this.apiBase}/api/board/game`, {});
|
||||
}
|
||||
|
||||
getGame(gameId: string): Observable<GameFull> {
|
||||
return this.http.get<GameFull>(`${this.apiBase}/api/board/game/${gameId}`);
|
||||
}
|
||||
|
||||
makeMove(gameId: string, uci: string): Observable<GameState> {
|
||||
return this.http.post<GameState>(`${this.apiBase}/api/board/game/${gameId}/move/${uci}`, {});
|
||||
}
|
||||
|
||||
getLegalMoves(gameId: string, square?: string): Observable<LegalMovesResponse> {
|
||||
let params = new HttpParams();
|
||||
if (square) {
|
||||
params = params.set('square', square);
|
||||
}
|
||||
return this.http.get<LegalMovesResponse>(`${this.apiBase}/api/board/game/${gameId}/moves`, { params });
|
||||
}
|
||||
|
||||
streamGame(gameId: string): Observable<GameStreamEvent> {
|
||||
return new Observable<GameStreamEvent>((observer) => {
|
||||
const wsUrl = `${this.wsBase}/api/board/game/${gameId}/stream`;
|
||||
const streamUrl = `${this.apiBase}/api/board/game/${gameId}/stream`;
|
||||
const ws = new WebSocket(wsUrl);
|
||||
const abortController = new AbortController();
|
||||
let connected = false;
|
||||
let fallbackActive = false;
|
||||
|
||||
const parseEvent = (raw: string): GameStreamEvent | null => {
|
||||
if (!raw.trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as GameStreamEvent;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const emitErrorEvent = (message: string): void => {
|
||||
const errorEvent: ErrorEvent = {
|
||||
type: 'error',
|
||||
error: { code: 'STREAM_ERROR', message }
|
||||
};
|
||||
observer.next(errorEvent);
|
||||
};
|
||||
|
||||
const startNdjsonFallback = async (): Promise<void> => {
|
||||
if (fallbackActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
fallbackActive = true;
|
||||
|
||||
try {
|
||||
const response = await fetch(streamUrl, {
|
||||
headers: { Accept: 'application/x-ndjson' },
|
||||
signal: abortController.signal
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
emitErrorEvent(`Unable to open stream: HTTP ${response.status}`);
|
||||
observer.complete();
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() ?? '';
|
||||
|
||||
for (const line of lines) {
|
||||
const event = parseEvent(line);
|
||||
if (event) {
|
||||
observer.next(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observer.complete();
|
||||
} catch (error) {
|
||||
if ((error as Error).name !== 'AbortError') {
|
||||
emitErrorEvent((error as Error).message);
|
||||
observer.error(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onopen = () => {
|
||||
connected = true;
|
||||
};
|
||||
|
||||
ws.onmessage = (message) => {
|
||||
const payload = typeof message.data === 'string' ? message.data : '';
|
||||
const event = parseEvent(payload);
|
||||
if (event) {
|
||||
observer.next(event);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
if (!connected) {
|
||||
void startNdjsonFallback();
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
if (!connected) {
|
||||
void startNdjsonFallback();
|
||||
} else {
|
||||
observer.complete();
|
||||
}
|
||||
};
|
||||
|
||||
return () => {
|
||||
abortController.abort();
|
||||
ws.close();
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export const environment = {
|
||||
apiBaseUrl: 'http://localhost:8080',
|
||||
wsBaseUrl: 'ws://localhost:8080'
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export const environment = {
|
||||
apiBaseUrl: 'http://localhost:8080',
|
||||
wsBaseUrl: 'ws://localhost:8080'
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>NowChess Frontend</title>
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,6 @@
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { appConfig } from './app/app.config';
|
||||
import { App } from './app/app';
|
||||
|
||||
bootstrapApplication(App, appConfig)
|
||||
.catch((err) => console.error(err));
|
||||
@@ -0,0 +1,27 @@
|
||||
:root {
|
||||
--warm-primary: #BA6D4B;
|
||||
--warm-dark: #5A2C28;
|
||||
--warm-light: #F3C8A0;
|
||||
--cool-mint: #B9DAD1;
|
||||
--cool-blue: #B9C2DA;
|
||||
--cool-purple: #C19EF5;
|
||||
--cool-lime: #E1EAA9;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100%;
|
||||
font-family: "Comic Sans MS", "Comic Sans", cursive;
|
||||
background: linear-gradient(160deg, var(--warm-light), var(--cool-mint));
|
||||
color: var(--warm-dark);
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
Reference in New Issue
Block a user