Быстрый вопрос, я разработал 3 AI с разной глубиной.
В настоящее время, чтобы выбрать, с каким ИИ вы хотите играть против, вам нужно войти в java файл с именем Main.java и изменить его в зависимости от того, что вы хотите. Строка для изменения:
chessGame.setPlayer(Piece.COLOR_BLACK, ai3);//Here A.I is assigned
Я хочу разрешить пользователю иметь опцию в начале игры, чтобы выбрать AI, на который я надеялся на помощь с интерфейсом, я думал, что что-то вроде JOptionpane может работать.
(Я просто не уверен, как сделать это для выбора AI)
Текущий A.I
ai1 ai2 ai3
package chess;
import chess.ai.SimpleAiPlayerHandler;
import chess.gui.ChessGui;
import chess.logic.ChessGame;
import chess.logic.Piece;
public class Main {
public static void main(String[] args) {
// Creating the Game
ChessGame chessGame = new ChessGame();
// Creating the Human Player
//Human Player is the Object chessGui
ChessGui chessGui = new ChessGui(chessGame);
//Creating the A.I's
SimpleAiPlayerHandler ai1 = new SimpleAiPlayerHandler(chessGame);//Super Dumb
SimpleAiPlayerHandler ai2 = new SimpleAiPlayerHandler(chessGame);//Dumb
SimpleAiPlayerHandler ai3 = new SimpleAiPlayerHandler(chessGame);//Not So Dumb
// Set strength of AI, how far they can see ahead
ai1.maxDepth = 1;
ai1.maxDepth = 2;
ai3.maxDepth = 3;
//Assign the Human to White
chessGame.setPlayer(Piece.COLOR_WHITE, chessGui);
//Assign the not so dumb A.I to black
chessGame.setPlayer(Piece.COLOR_BLACK, ai3);
// in the end we start the game
new Thread(chessGame).start();
}
}
Спасибо за любую помощь.
Вероятно, вы должны использовать JComboBox, чтобы позволить пользователю выбрать один из трех доступных вариантов. Если вы создадите JFrame с помощью JComboBox, вы можете затем создать свой основной игровой фрейм и передать его значение из JComboBox.
Например, у вас может быть JComboBox, чтобы задать параметры сложности Easy, Medium и Hard. Используя прослушиватель действий в JButton, вы получите выбранное значение из JComboBox и преобразуйте его в значение int, соответствующее вашему минимаксному алгоритму. То есть, проход 1 для легкого, 2 для среднего и 3 для жестких.
Затем измените свой класс ai так, чтобы maxDepth находился в конструкторе. Затем, когда вы создаете экземпляр своего ai, просто дайте ему значение, которое было передано вперед от предыдущего кадра, и вы создадите только тот, который вам нужен при правильной настройке трудности.
РЕДАКТИРОВАТЬ:
Похоже, вам удалось добиться чего-то подобного, что здорово! В случае, если это поможет вам, я включил краткий пример того, как я сделал бы это ниже. Обратите внимание, что я также настроил его так, чтобы ваш конструктор SimpleAiPlayerHandler также принял значение int для создания экземпляра переменной maxDepth. Вам нужно добавить это. Поскольку он использует классы, которых у меня нет, я не могу их скомпилировать. Однако, если кому-то еще нужно сделать что-то подобное, просто удалите все в DifficultyListener, кроме оператора печати, и строки, которая затрудняет работу с JComboBox, и вы увидите, что она работает (и компилируется).
import javax.swing.*;
import java.awt.event.*;
public class ChessSplash extends JFrame {
private final JComboBox<Difficulty> difficultySetting;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ChessSplash gui = new ChessSplash();
gui.setVisible(true);
}
});
}
public enum Difficulty {
EASY(1, "Easy"), MEDIUM(2, "Medium"), HARD(3, "Hard");
private final int intValue;
private final String stringValue;
private Difficulty(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
@Override
public String toString() {
return stringValue;
}
};
public ChessSplash() {
super("Chess Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
difficultySetting = new JComboBox<>(Difficulty.values());
JButton startButton = new JButton("Start Game");
startButton.addActionListener(new DifficultyListener());
JPanel mainPanel = new JPanel();
add(mainPanel);
mainPanel.add(difficultySetting);
mainPanel.add(startButton);
pack();
}
private class DifficultyListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//Declare AI
SimpleAiPlayerHandler ai;
//Declare and Instantiate Chess Game
ChessGame chessGame = new ChessGame();
//Human Player is the Object chessGui
ChessGui chessGui = new ChessGui(chessGame);
//Assign Human Player to White
chessGame.setPlayer(Piece.COLOR_WHITE, chessGui);
//Get the selected difficulty setting
Difficulty difficulty = (Difficulty)difficultySetting.getSelectedItem();
//Instantiate Computer AI pass it the maxDepth for use in the constructor
ai = new SimpleAiPlayerHandler(difficulty.intValue, chessGame);
//Assign Computer Player to Black
chessGame.setPlayer(Piece.COLOR_BLACK, ai);
//Demonstrate the enum combobox works
System.out.println(difficulty.intValue);
//Dispose of the splash JFrame
ChessSplash.this.dispose();
//Start your game thread (I would probably do something to move this
//onto the EDT if you're doing this is swing personally
new Thread(chessGame).start();
}
}
}
enum
приведен здесь .
JComboBox
, см. Как использоватьJRadioButton
списком для более подробной информации, или вы можете использоватьJRadioButton
илиJToggleButton
вButtonGroup
, см. Как использовать кнопки,JRadioButton
иJToggleButton
для более подробной информации.