-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.php
More file actions
56 lines (45 loc) · 1.57 KB
/
app.php
File metadata and controls
56 lines (45 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
require __DIR__ . '/vendor/autoload.php';
use Chess\Board;
use Chess\Position;
use Chess\Player;
use Chess\Pieces\Bishop;
use Chess\Pieces\Knight;
try {
$board = new Board();
$white = new Player("white");
$black = new Player("black");
$board->placePiece(new Bishop($white), new Position(2, 0));
$board->placePiece(new Knight($white), new Position(1, 0));
$board->placePiece(new Bishop($black), new Position(5, 7));
$board->placePiece(new Knight($black), new Position(6, 7));
$board->display();
$players = [$white, $black];
$currentTurn = 0;
while (true) {
$currentPlayer = $players[$currentTurn % 2];
echo ucfirst($currentPlayer->getName()) . "'s turn. Enter move (e.g. b1 c3) or 'exit': ";
$input = trim(fgets(STDIN));
if (strtolower($input) === 'exit') {
echo "Game over.\n";
break;
}
if (!preg_match('/^[a-h][1-8]\s[a-h][1-8]$/', $input)) {
echo "Invalid format. Please enter like 'b1 c3'.\n";
continue;
}
[$fromStr, $toStr] = explode(' ', $input);
$from = new Position(ord($fromStr[0]) - ord('a'), (int)$fromStr[1] - 1);
$to = new Position(ord($toStr[0]) - ord('a'), (int)$toStr[1] - 1);
try {
$board->movePiece($from, $to, $currentPlayer);
echo "Move successful.\n";
$board->display();
$currentTurn++;
} catch (\Throwable $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
} catch (\Exception $e) {
echo $e->getMessage();
}