Commit 60771cf7 authored by mva021's avatar mva021
Browse files

Replaced game with new solution

parent 357cb687
package inf101.v20.sem2.GUI;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import javax.swing.JPanel;
import inf101.v20.sem2.grid.Grid;
import inf101.v20.sem2.grid.Location;
import inf101.v20.sem2.games.IGame;
import inf101.v20.sem2.games.Player;
public class ClickableGrid extends MouseAdapter {
private JPanel pane;
private Grid<GamePanel> clickablePanels; //clickable grid for user input
private IGame game;
HashMap<Player,Color> color;
public ClickableGrid(IGame game,List<Color> colors) {
this.game = game;
//assign colors to the players
setColors(game, colors);
//create clickable panels
pane = new JPanel();
int rows = game.getGameBoard().numRows();
int cols = game.getGameBoard().numCols();
clickablePanels = new Grid<GamePanel>(rows, cols, null);
pane.setLayout(new GridLayout(rows, cols));
makeClickablePanels();
//set gui options
pane.setRequestFocusEnabled(true);
pane.requestFocus();
pane.setVisible(true);
pane.validate();
}
private void setColors(IGame game, List<Color> colors) {
color = new HashMap<Player, Color>();
for(Player p : game.players()) {
color.put(p, colors.get(color.size()));
}
color.put(null, Color.WHITE);
}
/**
* Should be called after a click to update the UI to reflect the current game state
*/
public void updateGui() {
for(Location loc : game.getGameBoard().locations()) {
Color color = getColor(game.getGameBoard().get(loc));
clickablePanels.get(loc).setColor(color);
}
pane.updateUI();
}
protected Color getColor(Player player) {
return color.get(player);
}
/**
* Makes a grid of same size as the one in game and fills it with clickable panels
* @return
*/
private void makeClickablePanels() {
for(Location loc : game.getGameBoard().locations()) {
GamePanel pan = new GamePanel(this);
clickablePanels.set(loc, pan);
pane.add(pan);
}
}
/**
* This is what happens when the mouse clicks on one of the squares of the grid.
*/
public void mousePressed(MouseEvent me){
if(clickablePanels.contains(me.getSource())) {
Location loc = clickablePanels.locationOf(me.getSource());
System.err.println("Making move: "+loc);
game.makeGuiMove(loc);
}
else
System.err.println("Clicked on wrong thing: "+me.getSource());
}
public Component getPanel() {
return pane;
}
}
\ No newline at end of file
package inf101.v20.sem2.GUI;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import inf101.v20.sem2.games.Game;
import inf101.v20.sem2.games.Player;
import inf101.v20.sem2.games.TicTacToe;
public class GUIMain {
public static void main(String[] args) {
ArrayList<Player> players = new ArrayList<Player>();
players.add(new GuiPlayer(TicTacToe.piece1));
players.add(new GuiPlayer(TicTacToe.piece2));
Game game = new TicTacToe(players);
MNKGameGUI gameGUI = new MNKGameGUI(game);
game.setGui(gameGUI);
GameGUI gui = new GameGUI(gameGUI);
}
}
\ No newline at end of file
package inf101.v20.sem2.mnkgames.GUI; package inf101.v20.sem2.GUI;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Dimension; import java.awt.event.ActionEvent;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import java.awt.event.ActionListener; import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JButton;
import javax.swing.JLabel; import javax.swing.JFrame;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import inf101.v20.sem2.mnkgames.MNKGame; import inf101.v20.sem2.games.FourinRow;
import inf101.v20.sem2.twoPlayerGame.TwoPlayerGame; import inf101.v20.sem2.games.Player;
import inf101.v20.sem2.twoPlayerGame.player.HumanPlayer; import inf101.v20.sem2.games.TicTacToe;
/** public class GameGUI implements ActionListener{
*
* @author Anna Eilertsen private JButton playConnectFourButton; //Button to start new 4 in row game
*/ private JButton playTicTacToeButton; //Button to start new TicTacToe game
public class MNKGameGUI extends JPanel implements ActionListener{ private JFrame frame;
private MNKGameGUI gameBoard;
private static final long serialVersionUID = 8755882090377973497L;
public GameGUI(MNKGameGUI gameBoard) {
/** this.gameBoard = gameBoard;
s * Initializes a JFrame in which we place the game JPanel buttons = createButtonPanel();
* @param gameSupplier A lambda function that provides new games
*/ //make new main window for the game
public static void run(GameSupplier gameSupplier) { frame = new JFrame();
JFrame f = new JFrame("mnkGame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(buttons, BorderLayout.SOUTH);
MNKGameGUI ap = new MNKGameGUI(gameSupplier);
ap.collectPlayerInfo(); drawGameBoard();
ap.initialize(); }
f.add("Center", ap);
f.pack(); private void drawGameBoard() {
f.setVisible(true); //add the clickable grid panel
} frame.add("Center", gameBoard);
// Fields frame.pack();
private JButton playConnectFourButton; frame.setVisible(true);
private JButton playTicTacToeButton; }
private JLabel statusMessage;
private GameSupplier gameSupplier; /**
private TwoPlayerGame<MNKGame> game; * Helper method that creates the button panel
private GUIBoard board; */
private JPanel createButtonPanel() {
public MNKGameGUI(GameSupplier gameSupplier) { playTicTacToeButton = new JButton();
this.gameSupplier = gameSupplier; playTicTacToeButton.addActionListener(this);
//initialize to default values playTicTacToeButton.setText("Tic-Tac-Toe");
game = new TwoPlayerGame<>(gameSupplier.getTicTacToeGame());
} playConnectFourButton = new JButton();
playConnectFourButton.addActionListener(this);
/* playConnectFourButton.setText("Connect Four");
* (non-Javadoc)
* JPanel buttons = new JPanel();
* @see buttons.setLayout(new BorderLayout());
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) buttons.add(playConnectFourButton, BorderLayout.WEST);
* Called whenever a button is pressed buttons.add(playTicTacToeButton, BorderLayout.EAST);
*/ return buttons;
@Override }
public void actionPerformed(ActionEvent e) {
if(e.getSource() == playConnectFourButton) { /*
reset(gameSupplier.getConnectFourGame()); * (non-Javadoc)
} *
if(e.getSource() == playTicTacToeButton) { * @see
reset(gameSupplier.getTicTacToeGame()); * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
} * Called whenever a button is pressed
} */
@Override
private void reset(MNKGame newGame) { public void actionPerformed(ActionEvent e) {
this.game = game.newGame(newGame); Iterable<Player> players = getPlayers();
updateMessage(); if(e.getSource() == playConnectFourButton) {
removeAll(); gameBoard.reset(new FourinRow(players));
initialize(); }
this.updateUI(); if(e.getSource() == playTicTacToeButton) {
} gameBoard.reset(new TicTacToe(players));
}
public void registerClick(int x, int y) {
try { drawGameBoard();
game.takeTurnforHumanPlayer(x, y); }
}
catch(Exception e){ private Iterable<Player> getPlayers() {
//GUI ERROR HANDLING ArrayList<Player> players = new ArrayList<Player>();
} //add player1
board.updateToGame(game); players.add(new GuiPlayer(TicTacToe.piece1));
updateMessage(); //add player2
MNKGameGUI.super.updateUI(); if(promptMultiplayer()) {
if(!game.hasPossibleMoves()) { //make AI
stop(); }else {
} players.add(new GuiPlayer(TicTacToe.piece2));
} }
/**
* Helper method to control the status message return players;
*/ }
private void updateMessage() {
if (game.hasWinner()) /**
statusMessage.setText("The game is over! The winner is " + game.winner()); * Helper method that prompts for multiplayer or not
else if(game.hasPossibleMoves()) { * @return true if multiplayer is selected, false otherwise
statusMessage.setText("Next move from " + game.currentPlayer()); */
}else{ private boolean promptMultiplayer() {
statusMessage.setText("The game is over! No one won."); Object[] possibilities = {"Multiplayer", "Single Player (against AI)"};
} String s = (String)JOptionPane.showInputDialog(
} null,
"Welcome:\n"
/** + "Select one or two players",
* Should be called once a game stops "MKGame StartUp",
*/ JOptionPane.PLAIN_MESSAGE,
private void stop() { null,
board.makeAllUnclickable(); possibilities,
} null);
//If a string was returned, say so.
@Override if ((s != null) && (s.length() > 0)) {
public Dimension getPreferredSize() { System.out.println("Received " + s);
return new Dimension(100*game.height(), 100*game.width()); }
} return s.charAt(0)=='M';
}
/** }
* Sets up the GUI.
*/
public void initialize() {
setLayout(new BorderLayout());
board = new GUIBoard(this, game);
add(board);
JPanel buttons = createButtonPanel();
add(buttons, BorderLayout.SOUTH);
add(statusMessage, BorderLayout.NORTH);
validate();
}
/**
* Helper method that creates the button panel
*/
private JPanel createButtonPanel() {
playTicTacToeButton = new JButton();
playTicTacToeButton.addActionListener(this);
playTicTacToeButton.setText("Tic-Tac-Toe");
playConnectFourButton = new JButton();
playConnectFourButton.addActionListener(this);
playConnectFourButton.setText("Connect Four");
statusMessage = new JLabel();
statusMessage.setText("Welcome to this game! " + game.player1() + " begins.");
JPanel buttons = new JPanel();
buttons.setLayout(new BorderLayout());
buttons.add(playConnectFourButton, BorderLayout.WEST);
buttons.add(playTicTacToeButton, BorderLayout.EAST);
return buttons;
}
/**
* Helper method to collect player info
*/
private void collectPlayerInfo() {
boolean multiplayer = promptMultiplayer();
game.setHumanPlayer1(HumanPlayer.promptPlayerName("Player 1"));
if(multiplayer) {
game.setHumanPlayer2(HumanPlayer.promptPlayerName("Player 2"));
}
else {
game.setAIPlayer2();
}
}
/**
* Helper method that prompts for multiplayer or not
* @return true if multiplayer is selected, false otherwise
*/
private boolean promptMultiplayer() {
Object[] possibilities = {"Multiplayer", "Single Player (against AI)"};
String message = "Welcome:\n" + "Select one or two players";
String s = (String)JOptionPane.showInputDialog(null,message,"MKGame StartUp",
JOptionPane.PLAIN_MESSAGE,null,possibilities,null);
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
System.out.println("Received " + s);
}
return s.charAt(0)=='M';
}
}
\ No newline at end of file
package inf101.v20.sem2.GUI;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
/**
* A class for clickable panels with x,y-coordinates
*
* @author anna
*
*/
public class GamePanel extends JPanel{
private Color color;
private static final long serialVersionUID = 1L;
public GamePanel(MouseListener listener) {
this.color = Color.WHITE;
//use methods in JPanel to set initial style
setEnabled(true);
setBorder(BorderFactory.createLineBorder(Color.GRAY));
//add mouse listener which calls click method
addMouseListener(listener);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(3, 3);
}
@Override
public Color getBackground() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
\ No newline at end of file
package inf101.v20.sem2.GUI;
import javax.swing.JOptionPane;
import inf101.v20.sem2.grid.Location;
import inf101.v20.sem2.games.AbstractPlayer;
import inf101.v20.sem2.games.IGame;
import inf101.v20.sem2.games.Player;
public class GuiPlayer extends AbstractPlayer {
public GuiPlayer(String piece, String name) {
super(piece, name);
}
public GuiPlayer(String piece) {
super(piece, getPlayerName(piece));
}
@Override
public Location getMove(IGame game) {
throw new IllegalStateException("This method should not be called.");
}
public static String getPlayerName(String piece) {
String name = null;
while(!Player.isValidName(name)) {
name = JOptionPane.showInputDialog("Player "+piece+". Type in your name.");
}
return name;
}
}
package inf101.v20.sem2.GUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import inf101.v20.sem2.games.Game;
/**
*
* @author Anna Eilertsen
*/
public class MNKGameGUI extends JPanel{
private static final long serialVersionUID = 8755882090377973497L;
// Fields
private Game game; //the game logic
private ClickableGrid clickablePanels; //clickable grid for user input
private JLabel statusMessage; //field for displaying message to user
public MNKGameGUI(Game game) {
this.game = game;
statusMessage = new JLabel();
statusMessage.setText("Welcome to this game! " + game.getCurrentPlayerName() + " begins.");
clickablePanels = new ClickableGrid(game, MNKGameGUI.getColors());
initialize();
}
/**
* Sets up the GUI.
*/
private void initialize() {
setLayout(new BorderLayout());
add("North", statusMessage);
add("Center", clickablePanels.getPanel());
setVisible(true);
validate();
}
public void reset(Game newGame) {
this.game = newGame;
//updateMessage();
removeAll();
initialize();
this.updateUI();
}
public void updateMessage(String message) {
statusMessage.setText(message);
}
/**
* Maps from Piece values to colors
*
* @param pieceAt The piece to be drawn
* @return The color that this GUI implementation associates with the provided piece
*/
protected static List<Color> getColors() {
Color[] colors = {Color.BLUE,Color.RED};
return Arrays.asList(colors);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100*game.getGameBoard().numRows(), 100*game.getGameBoard().numRows());
}
@Override
public void updateUI() {
if(clickablePanels!=null)
clickablePanels.updateGui();
super.updateUI();
}
}
\ No newline at end of file
package inf101.v20.sem2.games;
public abstract class AbstractPlayer implements Player {
protected String symbol;
protected String name;
public AbstractPlayer(String piece, String name) {
if(piece == null)
throw new IllegalArgumentException("Each player need to have a Symbol to play");
this.symbol = piece;
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean usesSameSymbol(Player player) {
return getSymbol().contentEquals(player.getSymbol());
}