This repository has been archived on 2022-08-16. You can view files and clone it, but cannot push or open issues or pull requests.
connect-four/src/de/itsblue/ConnectFour/player/RemotePlayer.java

102 lines
2.9 KiB
Java

/*
Connect four - written in java
Copyright (C) 2020 Oliver Schappacher and Dorian Zedler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.itsblue.ConnectFour.player;
import de.itsblue.ConnectFour.Plate.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import de.itsblue.ConnectFour.*;
/**
* Player is an abstract class meant for usage with de.itsblue.ConnectFour. It
* is a template for a connect four player.
*
* @author Dorian Zedler
*/
public abstract class RemotePlayer extends Player implements ActionListener {
protected Socket socket;
protected Scanner in;
protected PrintWriter out;
protected Player opponent;
public RemotePlayer(ButtonRow gameControllingButtonRow, PlateType usingPlateType, Player opponent) {
super(gameControllingButtonRow, usingPlateType);
this.opponent = opponent;
opponent.addActionListener(this);
}
protected void startListening() {
// listen to the socket
ExecutorService pool = Executors.newFixedThreadPool(200);
pool.execute(this.new SocketListener(this.in, this));
}
protected abstract void handleResponse(String response);
/**
* Function to set wether it is this player's turn
*/
@Override
public void setIsMyTurn(boolean isMyTurn) {
super.setIsMyTurn(isMyTurn);
if (isMyTurn)
this.gameControllingButtonRow.setEnabled(false);
else
this.gameControllingButtonRow.setEnabled(true);
}
@Override
public abstract void actionPerformed(ActionEvent e);
private class SocketListener implements Runnable {
RemotePlayer parent;
Scanner in;
public SocketListener(Scanner in, RemotePlayer parent) {
this.parent = parent;
this.in = in;
}
@Override
public void run() {
// listen to the socket
try {
while (in.hasNextLine()) {
String response = in.nextLine();
this.parent.handleResponse(response);
}
out.println("QUIT");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}