|
| 1 | +package com.xebia.functional.xef.java.auto.jdk21; |
| 2 | + |
| 3 | +import com.xebia.functional.xef.java.auto.AIScope; |
| 4 | +import com.xebia.functional.xef.java.auto.ExecutionContext; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.concurrent.ExecutionException; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.stream.Collectors; |
| 9 | + |
| 10 | +public class ChessAI { |
| 11 | + |
| 12 | + public record ChessMove(String player, String move){} |
| 13 | + public record ChessBoard(String board){} |
| 14 | + public record GameState(Boolean ended, String winner){} |
| 15 | + |
| 16 | + public static void main(String[] args) throws ExecutionException, InterruptedException { |
| 17 | + try (AIScope scope = new AIScope(new ExecutionContext(Executors.newVirtualThreadPerTaskExecutor()))) { |
| 18 | + var moves = new ArrayList<ChessMove>(); |
| 19 | + var gameEnded = false; |
| 20 | + var winner = ""; |
| 21 | + |
| 22 | + while (!gameEnded) { |
| 23 | + var currentPlayer = ((moves.size() % 2) == 0) ? "Player 1 (White)" : "Player 2 (Black)"; |
| 24 | + |
| 25 | + var prompt = String.format(""" |
| 26 | + |%s, it's your turn. |
| 27 | + |Previous moves: %s |
| 28 | + |Make your next move:""", |
| 29 | + currentPlayer, |
| 30 | + moves.stream().map(ChessMove::toString).collect(Collectors.joining(", "))); |
| 31 | + |
| 32 | + ChessMove move = scope.prompt(prompt, ChessMove.class).get(); |
| 33 | + moves.add(move); |
| 34 | + |
| 35 | + // Update boardState according to move.move |
| 36 | + // ... |
| 37 | + |
| 38 | + var boardPrompt = String.format(""" |
| 39 | + Given the following chess moves: %s, |
| 40 | + generate a chess board on a table with appropriate emoji representations for each move and piece. |
| 41 | + Add a brief description of the move and it's implications""", |
| 42 | + moves.stream().map(it -> it.player + ":" + it.move).collect(Collectors.joining(", "))); |
| 43 | + |
| 44 | + ChessBoard chessBoard= scope.prompt(boardPrompt, ChessBoard.class).get(); |
| 45 | + System.out.println("Current board:\n" + chessBoard.board); |
| 46 | + |
| 47 | + var gameStatePrompt = String.format(""" |
| 48 | + Given the following chess moves: %s, |
| 49 | + has the game ended (win, draw, or stalemate)?""", |
| 50 | + moves.stream().map(ChessMove::toString).collect(Collectors.joining(", "))); |
| 51 | + |
| 52 | + GameState gameState = scope.prompt(gameStatePrompt, GameState.class).get(); |
| 53 | + |
| 54 | + gameEnded = gameState.ended; |
| 55 | + winner = gameState.winner; |
| 56 | + } |
| 57 | + |
| 58 | + System.out.println("Game over. Final move: " + moves.get(moves.size() - 1) + ", Winner: " + winner); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments