more IRC integration

refactoring, cleanup
logging to irc
This commit is contained in:
Lucas Pleß 2012-06-01 17:00:34 +02:00
parent 745a2cafff
commit cac0383251
25 changed files with 1025 additions and 846 deletions

View File

@ -1,93 +0,0 @@
package de.ctdo.crashtest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* User: lpless
* Date: 10.05.12
* Time: 11:03
*/
public class BuntiClient {
private String baseAddress;
private HttpClient client = new DefaultHttpClient();
private LampelClient lampel = new LampelClient();
public BuntiClient(String server, int port) {
baseAddress = "http://" + server + ":" + port + "/";
}
public void setPar56(int id, int red, int green, int blue) {
if(true) return;
try {
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(
"{ \"timeStamp\": 0, \"updates\": [ {\"deviceId\": "+id+", \"options\": { \"red\": "+
red+", \"green\": "+green+", \"blue\": "+blue+" } } ] }" ,
"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(response);
post.abort();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setLampel(boolean red, boolean yellow, boolean green) {
if(true) return;
int value = 0;
if( green ) value |= 0x01;
if( yellow ) value |= 0x02;
if( red ) value |= 0x04;
lampel.sendCommand("io set port 2 " + Integer.toHexString(value));
/* try {
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(
"{ \"timeStamp\": 0, \"updates\": [ {\"deviceId\": 4, \"options\": { \"red\": "+
red+", \"green\": "+green+", \"yellow\": "+yellow+" } } ] }" ,
"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(response);
post.abort();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
}

View File

@ -1,73 +0,0 @@
package de.ctdo.crashtest;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Communication implements Runnable {
private final static int LISTEN_PORT = 2342;
private Boolean isStopped = false;
private ServerSocket serverSocket;
private Thread runningThread;
private ExecutorService threadPool = Executors.newFixedThreadPool(10);
private GuiControl control;
public Communication(GuiControl control) {
this.control = control;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
@Override
public void run() {
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(!isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
this.threadPool.execute(new CommunicationRunner(clientSocket, this.control));
}
this.threadPool.shutdown();
System.out.println("Server Stopped.") ;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(LISTEN_PORT);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
}

View File

@ -1,76 +0,0 @@
package de.ctdo.crashtest;
import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class CommunicationRunner implements Runnable {
private Socket clientSocket = null;
private GuiControl control;
public CommunicationRunner(Socket clientSocket, GuiControl control) {
this.clientSocket = clientSocket;
this.control = control;
}
@Override
public void run() {
try {
clientSocket.setSoTimeout(5000);
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
System.out.println("got line: " + line);
runCommand(line);
output.close();
input.close();
System.out.println("Request processed: " + time + clientSocket.getRemoteSocketAddress());
} catch (SocketTimeoutException e) {
System.out.println("Socket Timeout, closing " + clientSocket.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void runCommand(String line) {
// must contain a ":"
// then split and switch on the command
int pos = line.indexOf(":");
if(pos > 0) {
String command = line.substring(0, pos).toLowerCase().trim();
String parameter = line.substring(pos+1, line.length()).trim();
if(command.equals("wall")) {
control.setWall(parameter);
} else if(command.equals("timerstart")) {
control.startTimer(Integer.parseInt(parameter));
} else if(command.equals("timerstop")) {
control.stopTimer();
} else if(command.equals("timerpause")) {
control.pauseTimer(Boolean.parseBoolean(parameter));
} else if(command.equals("setextra")) {
control.setExtra(parameter);
} else if(command == "reset") {
control.resetGame();
}
}
}
}

View File

@ -1,18 +0,0 @@
package de.ctdo.crashtest;
public interface GuiControl {
void startTimer(int seconds);
void stopTimer(); // and hide
void pauseTimer(Boolean pause);
void setWall(String message);
void setExtra(String text);
int getTimerSeconds();
int getTimerSecondsLast();
Boolean getTimerRunning();
void resetGame();
}

View File

@ -1,36 +0,0 @@
package de.ctdo.crashtest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class LampelClient {
private static final int ECMD_TCP_PORT = 2701;
private static final String LAMPEL_HOST = "lampel.ctdo.de";
public void sendCommand(String command) {
try {
Socket client = new Socket(LAMPEL_HOST, ECMD_TCP_PORT);
client.setSoTimeout(800);
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
outToServer.writeBytes(command + '\n');
String result = inFromServer.readLine();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,173 +0,0 @@
package de.ctdo.crashtest;
import java.util.ArrayList;
import java.util.List;
public class Statemachine {
private final char BLUE_BUTTON = 'E';
private final char LIGHT_BARRIER = 'F';
private final char TABLE_ONE = 'G';
private final char TABLE_TWO = 'H';
private final char TABLE_THREE = 'I';
private final char ROKET_INPUT = 'B';
private long lastHandleInput = 0;
private final List<StateChangeListener> stateChangeListenerList = new ArrayList<StateChangeListener>();
private int stateChangeCounter = 0;
public void addStateChangedListener(StateChangeListener listener) {
stateChangeListenerList.add(listener);
}
public enum state {
IDLE,
ENTERED_ROOM,
TABLE_GAME_ONE,
TABLE_GAME_TWO,
TABLE_GAME_THREE,
TABLE_GAME_FOUR,
TABLE_GAME_FIVE,
TABLE_GAME_SIX,
TABLE_GAME_SEVEN,
TABLE_FINISH,
ROKET_DONE
}
private state currentState = state.IDLE;
public state getCurrentState() {
return currentState;
}
public int getStateChangeCounter() {
return stateChangeCounter;
}
public void reset() {
stateChangeCounter = 0;
currentState = state.IDLE;
onStateChanged();
}
public void handleInput(char input) {
if(System.currentTimeMillis() - lastHandleInput < 200 ) return;
state newState = getNewState(input);
if( newState != currentState ) {
stateChangeCounter++;
System.out.println("newState = " + newState);
workForState(newState);
currentState = newState;
onStateChanged();
}
lastHandleInput = System.currentTimeMillis();
}
private void onStateChanged() {
for(StateChangeListener listener: stateChangeListenerList) {
listener.stateChanged(currentState);
}
}
private void workForState(state newState) {
switch (newState) {
case IDLE:
break;
case ENTERED_ROOM:
break;
case TABLE_GAME_ONE:
break;
case TABLE_GAME_TWO:
break;
case TABLE_GAME_THREE:
break;
case TABLE_GAME_FOUR:
break;
case TABLE_GAME_FIVE:
break;
case TABLE_GAME_SIX:
break;
case TABLE_GAME_SEVEN:
break;
}
}
private state getNewState(char input) {
state retVal = currentState;
switch (currentState) {
case IDLE:
if(input == LIGHT_BARRIER) {
retVal = state.ENTERED_ROOM;
}
break;
case ENTERED_ROOM:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_ONE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_TWO;
}
break;
case TABLE_GAME_TWO:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_THREE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_THREE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_FOUR;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FOUR:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_FIVE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FIVE:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_SIX;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_SIX:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_SEVEN;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_SEVEN:
if(input == BLUE_BUTTON) {
retVal = state.TABLE_FINISH;
}
break;
case TABLE_FINISH:
if(input == ROKET_INPUT) {
retVal = state.ROKET_DONE;
}
}
return retVal;
}
}

View File

@ -1,16 +1,29 @@
package de.ctdo.crashtest; package de.ctdo.crashtest;
import de.ctdo.crashtest.game.TheGame;
import de.ctdo.crashtest.gui.IGuiControl;
import de.ctdo.crashtest.gui.MainGui;
public class Steuerung { public class Steuerung {
private TheGame game;
private IGuiControl gui;
public static void main(String args[]) { public static void main(String args[]) {
new SteuerungFrame(); new Steuerung();
} }
public Steuerung() {
gui = new MainGui();
game = new TheGame(gui);
}
} }

View File

@ -1,359 +0,0 @@
package de.ctdo.crashtest;
import jerklib.*;
import jerklib.events.IRCEvent;
import jerklib.events.JoinCompleteEvent;
import jerklib.events.listeners.IRCEventListener;
import org.bff.javampd.*;
import org.bff.javampd.exception.MPDConnectionException;
import org.bff.javampd.exception.MPDDatabaseException;
import org.bff.javampd.exception.MPDPlayerException;
import org.bff.javampd.exception.MPDResponseException;
import org.bff.javampd.objects.MPDSong;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
public class SteuerungFrame extends JFrame implements StateChangeListener, GuiControl, IRCEventListener {
private JTextArea textWall;
private JLabel countDown;
private JLabel extraField;
private JPanel lowerPanel;
private char lastKey = ' ';
private MPD mpd;
private MPDPlayer player;
private int timerSeconds = 0;
private int timerSecondsLast = 0;
private int timeSpentTableGame = 0;
private int timeSpentRokets = 0;
private Timer timer;
private Statemachine machine = new Statemachine();
private BuntiClient bunti = new BuntiClient("bunti.ctdo.de", 8080);
private Communication server;
private ConnectionManager irc;
private Session ircsession;
public SteuerungFrame() {
initGui();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setBounds(200,200, 400, 200);
//server = new Communication(this);
irc = new ConnectionManager(new ProfileImpl("crashtest","crashtest", "crashtest2", "crashtest3"));
ircsession = irc.requestConnection("irc.chaostreff-dortmund.de");
ircsession.addIRCEventListener(this);
//initTimer();
machine.addStateChangedListener(this);
machine.reset();
//initMPD();
this.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
lastKey = e.getKeyChar();
/*if (lastKey == KeyEvent.VK_F) {
Random r = new Random();
setLEDs(r.nextInt(255), r.nextInt(255),r.nextInt(255));
} */
if (lastKey == KeyEvent.VK_1) {
machine.reset();
} else {
machine.handleInput(e.getKeyChar());
}
updateGui();
}
});
this.addWindowStateListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
System.out.print("oihdf");
}
@Override
public void windowClosing(WindowEvent e) {
try {
if (mpd != null) mpd.close();
if (server != null) server.stop();
} catch (MPDConnectionException e1) {
e1.printStackTrace();
} catch (MPDResponseException e1) {
e1.printStackTrace();
}
}
});
//new Thread(server).start();
}
private void initMPD() {
try {
mpd = new MPD("dampfradio.raum.chaostreff-dortmund.de", 6600);
player = mpd.getMPDPlayer();
MPDDatabase database = mpd.getMPDDatabase();
Collection<MPDSong> bla = database.findTitle("");
} catch (UnknownHostException e) {
e.printStackTrace();
return;
} catch (MPDConnectionException e) {
e.printStackTrace();
return;
} catch (MPDDatabaseException e) {
e.printStackTrace();
}
}
private void initTimer() {
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timerSecondsLast--;
setTimerText();
if(timerSecondsLast <= 0) {
timerSecondsLast = 0;
timer.stop();
}
}
});
}
private void setTimerText() {
int mins = timerSecondsLast / 600;
int secs = timerSecondsLast % 600 / 10 ;
int tsecs = timerSecondsLast % 9;
countDown.setText(" " + mins + ":" + secs + "." + tsecs);
}
@Override
public void stateChanged(Statemachine.state newState) {
updateGui();
if(ircsession != null) {
for(Channel chan: ircsession.getChannels()) {
chan.say("New State: " + newState);
}
}
switch (newState) {
case IDLE:
//setLEDs(0x40,0,0xff);
setLEDs(0,0,0);
bunti.setLampel(false,false,false);
break;
case ENTERED_ROOM:
bunti.setLampel(false,false,false);
setLEDs(20,0,100);
// start von Mo Do - Eins, Zwei Polizei
break;
case TABLE_GAME_ONE:
bunti.setLampel(true,false,false);
setLEDs(255,0,100);
break;
case TABLE_GAME_TWO:
bunti.setLampel(false,true,false);
setLEDs(255,0,100);
break;
case TABLE_GAME_THREE:
bunti.setLampel(false,true,false);
setLEDs(255,35,0);
break;
case TABLE_GAME_FOUR:
bunti.setLampel(false,true,false);
setLEDs(255,55,0);
break;
case TABLE_GAME_FIVE:
bunti.setLampel(false,true,false);
setLEDs(255,75,0);
break;
case TABLE_GAME_SIX:
bunti.setLampel(false,true,false);
setLEDs(255,100,0);
break;
case TABLE_GAME_SEVEN:
bunti.setLampel(false,false,true);
setLEDs(255,100,0);
break;
case TABLE_FINISH: // und roket muss starten
bunti.setLampel(false,false,true);
setLEDs(0, 255, 0);
break;
case ROKET_DONE:
bunti.setLampel(true,true,true);
setLEDs(255, 196, 0);
break;
}
}
private void setLEDs(int red, int green, int blue) {
bunti.setPar56(0,red,green,blue);
bunti.setPar56(1,red,green,blue);
bunti.setPar56(2,red,green,blue);
bunti.setPar56(3,red,green,blue);
}
private void initGui() {
textWall = new JTextArea();
countDown = new JLabel();
extraField = new JLabel();
lowerPanel = new JPanel();
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(textWall, BorderLayout.NORTH);
container.add(lowerPanel, BorderLayout.SOUTH);
lowerPanel.setLayout(new BorderLayout());
lowerPanel.add(countDown, BorderLayout.WEST);
lowerPanel.add(extraField, BorderLayout.EAST);
Font wallFont = new Font("Arcade Interlaced", Font.PLAIN, 66);
Font lowerFont = new Font("Arcade Interlaced", Font.PLAIN, 80);
Color fontColor = new Color(0x00, 190, 100);
textWall.setFont(wallFont);
textWall.setForeground(fontColor);
textWall.setBackground(Color.BLACK);
textWall.setText("follow the white rabbit...");
textWall.setLineWrap(true);
textWall.setWrapStyleWord(true);
textWall.setFocusable(false);
countDown.setFont(lowerFont);
countDown.setHorizontalAlignment(SwingConstants.LEFT);
countDown.setForeground(fontColor);
//countDown.setBackground(Color.BLACK);
extraField.setFont(lowerFont);
extraField.setHorizontalAlignment(SwingConstants.RIGHT);
extraField.setForeground(fontColor);
//extraField.setBackground(Color.BLACK);
lowerPanel.setBackground(Color.BLACK);
container.setBackground(Color.BLACK);
countDown.setText(" 15:00.0");
extraField.setText("B ");
updateGui();
}
private void updateGui() {
/*lblState.setText("<html>LastKey: " + lastKey + "<br>CurrentState: " +
machine.getCurrentState() + "<br>ChangeCounter: " +
machine.getStateChangeCounter() + "</html>"); */
}
@Override
public void startTimer(int seconds) {
timerSeconds = seconds*10;
timerSecondsLast = seconds*10;
timer.start();
}
@Override
public void stopTimer() {
timer.stop();
timerSeconds = 0;
timerSecondsLast = 0;
}
@Override
public void pauseTimer(Boolean pause) {
if(pause) {
timer.stop();
} else {
timer.start();
}
}
@Override
public void setWall(final String message) {
Runnable runnable = new Runnable() {
@Override
public void run() {
textWall.setText(message);
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public void setExtra(final String text) {
Runnable runnable = new Runnable() {
@Override
public void run() {
extraField.setText(text + " " + lastKey + " ");
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public int getTimerSeconds() {
return timerSeconds;
}
@Override
public int getTimerSecondsLast() {
return timerSecondsLast;
}
@Override
public Boolean getTimerRunning() {
return null;
}
@Override
public void resetGame() {
}
@Override
public void recieveEvent(IRCEvent e) {
if (e.getType() == IRCEvent.Type.CONNECT_COMPLETE) {
e.getSession().joinChannel("#crashtest");
} else if (e.getType() == IRCEvent.Type.JOIN_COMPLETE) {
JoinCompleteEvent jce = (JoinCompleteEvent) e;
jce.getChannel().say("hello master. what's your order?");
}
}
}

View File

@ -1,16 +0,0 @@
package de.ctdo.crashtest;
public class TheGame {
// hier müssen alle Verbindungen nach Aussen rein
// MPD
// Lampel
// Bunti
// IRC
// Die GUI muss als Interface bekannt sein
// fuer Updates der GUI und den Keypress Event
// Logik des Spiels muss hier programmiert werden
}

View File

@ -0,0 +1,133 @@
package de.ctdo.crashtest.domotics;
import de.ctdo.crashtest.log.Logger;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.*;
import java.net.Socket;
public class BuntiClient implements IBuntiClient {
private String baseAddress;
private final HttpClient client = new DefaultHttpClient();
public BuntiClient(String server, int port) {
baseAddress = "http://" + server + ":" + port + "/";
}
@Override
public void setPar56(final int red, final int green, final int blue) {
//if(true) return;
Runnable r = new Runnable() {
@Override
public void run() {
try {
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringBuilder jsonString = new StringBuilder();
jsonString.append("{ \"timeStamp\": 0, \"updates\": [ ");
for(int i = 0; i< 4; i++) {
jsonString.append(" {\"deviceId\": ");
jsonString.append(i);
jsonString.append(", \"options\": { \"red\": ");
jsonString.append(red);
jsonString.append(", \"green\": ");
jsonString.append(green);
jsonString.append(", \"blue\": ");
jsonString.append(blue);
jsonString.append(" } } ");
if(i!=3) jsonString.append(",");
}
jsonString.append("] }");
System.out.println("bunti request: " + jsonString.toString());
StringEntity entity = new StringEntity( jsonString.toString(), "UTF-8");
post.setEntity(entity);
client.execute(post);
post.abort();
} catch (UnsupportedEncodingException e) {
Logger.sLog("bunti error: " + e.getMessage());
} catch (ClientProtocolException e) {
Logger.sLog("bunti error: " + e.getMessage());
} catch (IOException e) {
Logger.sLog("bunti error: " + e.getMessage());
}
}
};
new Thread(r).start();
}
@Override
public void setLampel(final boolean red, final boolean yellow, final boolean green) {
//if(true) return;
Runnable r = new Runnable() {
@Override
public void run() {
int value = 0;
// if( green ) value |= 0x01;
// if( yellow ) value |= 0x02;
// if( red ) value |= 0x04;
try {
Socket client = new Socket("lampel.ctdo.de", 2701);
client.setSoTimeout(800);
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
outToServer.writeBytes("io set port 2 " + Integer.toHexString(value) + '\n');
inFromServer.readLine();
client.close();
} catch (IOException e) {
Logger.sLog("cannot send to lampel: " + e.getMessage());
}
}
};
new Thread(r).start();
/* try {
HttpPost post = new HttpPost(baseAddress + "/control/devices");
post.addHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(
"{ \"timeStamp\": 0, \"updates\": [ {\"deviceId\": 4, \"options\": { \"red\": "+
red+", \"green\": "+green+", \"yellow\": "+yellow+" } } ] }" ,
"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(response);
post.abort();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
}

View File

@ -0,0 +1,11 @@
package de.ctdo.crashtest.domotics;
/**
* @author: lucas
* @date: 01.06.12 14:25
*/
public interface IBuntiClient {
void setPar56(final int red, final int green, final int blue);
void setLampel(final boolean red, final boolean yellow, final boolean green);
}

View File

@ -0,0 +1,14 @@
package de.ctdo.crashtest.game;
/**
* @author: lucas
* @date: 01.06.12 14:17
*/
public interface IStatemachine {
void addStateChangedListener(StateChangeListener listener);
void reset();
Statemachine.state getCurrentState();
void setNewState(Statemachine.state newState);
int getStateChangeCounter();
void handleInput(char input);
}

View File

@ -1,4 +1,4 @@
package de.ctdo.crashtest; package de.ctdo.crashtest.game;
/** /**
* User: lpless * User: lpless

View File

@ -0,0 +1,168 @@
package de.ctdo.crashtest.game;
import java.util.ArrayList;
import java.util.List;
public class Statemachine implements IStatemachine {
public enum state {
IDLE,
ENTERED_ROOM,
TABLE_GAME_ONE,
TABLE_GAME_TWO,
TABLE_GAME_THREE,
TABLE_GAME_FOUR,
TABLE_GAME_FIVE,
TABLE_GAME_SIX,
TABLE_GAME_SEVEN,
TABLE_FINISH,
ROKET_DONE
}
private final char RESET = '1';
private final char BLUE_BUTTON = 'E';
private final char LIGHT_BARRIER = 'F';
private final char TABLE_ONE = 'G';
private final char TABLE_TWO = 'H';
private final char TABLE_THREE = 'I';
private final char ROKET_INPUT = 'B';
private final List<StateChangeListener> stateChangeListenerList = new ArrayList<StateChangeListener>();
private long lastHandleInput = 0;
private int stateChangeCounter = 0;
private state currentState = state.IDLE;
@Override
public void addStateChangedListener(StateChangeListener listener) {
stateChangeListenerList.add(listener);
}
@Override
public state getCurrentState() {
return currentState;
}
@Override
public void setNewState(state newState) {
currentState = newState;
stateChangeCounter++;
onStateChanged();
}
@Override
public int getStateChangeCounter() {
return stateChangeCounter;
}
@Override
public void reset() {
stateChangeCounter = 0;
currentState = state.IDLE;
onStateChanged();
}
@Override
public void handleInput(char input) {
if(System.currentTimeMillis() - lastHandleInput < 200 ) return;
state newState = getNewState(input);
if( newState != currentState ) {
stateChangeCounter++;
System.out.println("newState = " + newState);
currentState = newState;
onStateChanged();
}
lastHandleInput = System.currentTimeMillis();
}
/**
* notifies all listeners about the changed state
*/
private void onStateChanged() {
for(StateChangeListener listener: stateChangeListenerList) {
listener.stateChanged(currentState);
}
}
/**
* Calculates the new game state from the current state and new input button
* @param input the char from the input
* @return returns the new state
*/
private state getNewState(char input) {
state retVal = currentState;
if(input == RESET) {
retVal = state.IDLE;
} else {
switch (currentState) {
case IDLE:
if(input == LIGHT_BARRIER) {
retVal = state.ENTERED_ROOM;
}
break;
case ENTERED_ROOM:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_ONE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_TWO;
}
break;
case TABLE_GAME_TWO:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_THREE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_THREE:
if(input == TABLE_TWO) {
retVal = state.TABLE_GAME_FOUR;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FOUR:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_FIVE;
} else if (input == TABLE_ONE) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_FIVE:
if(input == TABLE_ONE) {
retVal = state.TABLE_GAME_SIX;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_SIX:
if(input == TABLE_THREE) {
retVal = state.TABLE_GAME_SEVEN;
} else if (input == TABLE_TWO) {
retVal = state.TABLE_GAME_ONE;
}
break;
case TABLE_GAME_SEVEN:
if(input == BLUE_BUTTON) {
retVal = state.TABLE_FINISH;
}
break;
case TABLE_FINISH:
if(input == ROKET_INPUT) {
retVal = state.ROKET_DONE;
}
}
}
return retVal;
}
}

View File

@ -0,0 +1,249 @@
package de.ctdo.crashtest.game;
import de.ctdo.crashtest.domotics.*;
import de.ctdo.crashtest.gui.*;
import de.ctdo.crashtest.irc.*;
public class TheGame implements StateChangeListener, GuiEventListener, IRCEventListener {
private IGuiControl guiControl;
private IIrcClient ircClient;
private IStatemachine machine;
private IBuntiClient bunti;
private int timertSeconds = 0;
private int timertSecondsLast = 0;
private int timeSpentTableGame = 0;
private int timeSpentRokets = 0;
public TheGame(IGuiControl guiControl) {
this.guiControl = guiControl;
this.ircClient = new IrcClient();
this.machine = new Statemachine();
this.bunti = new BuntiClient("bunti.ctdo.de", 8080);
initGame();
}
private void initGame() {
guiControl.addListener(this);
ircClient.addListener(this);
machine.addStateChangedListener(this);
machine.reset();
}
/**
* Event listener for state change events from statemachine
* @param newState the new game state from statemachine
*/
@Override
public void stateChanged(Statemachine.state newState) {
ircClient.say("New State: " + newState);
switch (newState) {
case IDLE:
bunti.setPar56(0,0,0);
bunti.setLampel(false,false,false);
guiControl.showCountDown(false);
break;
case ENTERED_ROOM:
bunti.setLampel(false,false,false);
bunti.setPar56(20,0,100);
break;
case TABLE_GAME_ONE:
bunti.setLampel(true,false,false);
guiControl.showCountDown(true);
bunti.setPar56(255,0,100);
break;
case TABLE_GAME_TWO:
bunti.setLampel(false,true,false);
bunti.setPar56(255,0,100);
break;
case TABLE_GAME_THREE:
bunti.setLampel(false,true,false);
bunti.setPar56(255,35,0);
break;
case TABLE_GAME_FOUR:
bunti.setLampel(false,true,false);
bunti.setPar56(255,55,0);
break;
case TABLE_GAME_FIVE:
bunti.setLampel(false,true,false);
bunti.setPar56(255,75,0);
break;
case TABLE_GAME_SIX:
bunti.setLampel(false,true,false);
bunti.setPar56(255,100,0);
break;
case TABLE_GAME_SEVEN:
bunti.setLampel(false,false,true);
bunti.setPar56(255,100,0);
break;
case TABLE_FINISH: // und roket muss starten
bunti.setLampel(false,false,true);
bunti.setPar56(0, 255, 0);
break;
case ROKET_DONE:
bunti.setLampel(true,true,true);
bunti.setPar56(255, 196, 0);
break;
}
}
/**
* Event listener for keyPress events from the GUI
* @param key the pressed key
*/
@Override
public void keyPress(char key) {
machine.handleInput(key);
guiControl.setExtra("btn: " + key);
}
/**
* Event lister for window closing event from the GUI
*/
@Override
public void windowClosing() {
}
/**
* Event listener for IRC Messages
* @param message the message from the IRC user
*/
@Override
public void handleMessage(final String message) {
if(message.startsWith("help")) {
handleHelpCommand(message);
} else if(message.equals("reset")) {
machine.reset();
ircClient.say("reset done");
} else if(message.startsWith("state")) {
handleStateCommand(message);
} else if(message.startsWith("timer")) {
handleTimerCommand(message);
} else if(message.startsWith("score")) {
handleScoreCommand(message);
} else if(message.startsWith("wall")) {
guiControl.setWall(message.substring("wall".length()).trim());
} else if(message.startsWith("extra")) {
guiControl.setExtra(message.substring("extra".length()).trim());
} else {
ircClient.say("y u no use valid command?");
}
}
private void handleTimerCommand(final String message) {
String params = message.substring("timer".length()).trim().toLowerCase();
if(params.startsWith("start")) {
String timeStr = params.substring("start".length()).trim();
if(timeStr.length() > 0) {
int time = 0;
try {
time = Integer.parseInt(timeStr);
guiControl.showCountDown(true);
ircClient.say("got it, starting with " + time + " seconds");
}
catch (NumberFormatException e) {
ircClient.say("your number looks a bit odd...");
}
} else {
ircClient.say("invalid parameter");
}
} else if(params.startsWith("stop")) {
guiControl.showCountDown(false);
ircClient.say("timer stopped");
} else if(params.startsWith("pause")) {
} else if(params.startsWith("resume")) {
}
}
private void handleStateCommand(final String message) {
if(message.equals("state")) {
ircClient.say(machine.getCurrentState().name());
} else {
String params = message.substring("state".length()).trim().toLowerCase();
Boolean ok = false;
for(Statemachine.state st: Statemachine.state.values()) {
String stateName = st.name().toLowerCase();
if(stateName.equals(params)) {
ok = true;
machine.setNewState(st);
ircClient.say("consider it done, sir!");
break;
}
}
if(!ok) ircClient.say("ehm, impossibruu!");
}
}
private void handleScoreCommand(final String message) {
ircClient.say("stateChangeCounter: " + machine.getStateChangeCounter());
ircClient.say("timerlast: " + timertSecondsLast / 10);
}
private void handleHelpCommand(final String message) {
if(message.equals("help")) {
ircClient.say("commands: help, reset, state, timer, wall, extra, score");
} else if(message.contains("reset")) {
ircClient.say("resets the game to IDLE");
} else if(message.contains("state")) {
ircClient.say("get or set game state");
ircClient.say("> state <NEWSTATE>");
ircClient.say("valid states: ");
int counter = 0;
StringBuilder sb = new StringBuilder();
for(Statemachine.state st: Statemachine.state.values()) {
sb.append(st.name());
sb.append(" ");
if(++counter == 4) {
counter = 0;
ircClient.say(sb.toString());
sb.setLength(0);
}
}
if(sb.length() > 0) {
ircClient.say(sb.toString());
}
} else if(message.contains("timer")) {
ircClient.say("control timer. commands are: start, stop, pause, resume.");
ircClient.say("for start give lenght in seconds as parameter");
ircClient.say("e.g.: timer start 120");
} else if(message.contains("wall")) {
ircClient.say("set text message on the screen");
} else if(message.contains("extra")) {
ircClient.say("set small extra message on the screen");
} else if(message.contains("score")) {
ircClient.say("i will tell you the current game score");
} else {
ircClient.say("dafuq?");
}
}
}

View File

@ -0,0 +1,14 @@
package de.ctdo.crashtest.gui;
import java.awt.event.KeyEvent;
/**
* @author: lucas
* @date: 01.06.12 10:29
*/
public interface GuiEventListener {
void keyPress(final char key);
void windowClosing();
}

View File

@ -0,0 +1,17 @@
package de.ctdo.crashtest.gui;
/**
* @author: lucas
* @date: 01.06.12 10:13
*/
public interface IGuiControl {
void setWall(final String message);
void setExtra(final String text);
void setCountDown(final int tseconds);
void showCountDown(final Boolean show);
void addListener(final GuiEventListener listener);
}

View File

@ -0,0 +1,184 @@
package de.ctdo.crashtest.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
public class MainGui extends JFrame implements IGuiControl {
private final JTextArea textWall = new JTextArea();
private final JLabel countDown = new JLabel();
private final JLabel extraField = new JLabel();
private final JPanel lowerPanel = new JPanel();
private final List<GuiEventListener> listenerList = new ArrayList<GuiEventListener>();
public MainGui() {
initGui();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setBounds(0,0, 1280, 1024);
addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char lastKey = e.getKeyChar();
for(GuiEventListener listener: listenerList) {
listener.keyPress(lastKey);
}
}
});
addWindowStateListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
for(GuiEventListener listener: listenerList) {
listener.windowClosing();
}
}
});
}
//
//
// private void initTimer() {
// timer = new Timer(100, new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// timerSecondsLast--;
// setTimerText();
//
// if(timerSecondsLast <= 0) {
// timerSecondsLast = 0;
// timer.stop();
// }
// }
// });
// }
//
private void setCountDownText(final int tseconds) {
int mins = tseconds / 600;
int secs = tseconds % 600 / 10 ;
int tsecs = tseconds % 9;
countDown.setText(" " + mins + ":" + secs + "." + tsecs);
}
private void initGui() {
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(textWall, BorderLayout.NORTH);
container.add(lowerPanel, BorderLayout.SOUTH);
lowerPanel.setLayout(new BorderLayout());
lowerPanel.add(countDown, BorderLayout.WEST);
lowerPanel.add(extraField, BorderLayout.EAST);
Font wallFont = new Font("Arcade Interlaced", Font.PLAIN, 66);
Font lowerFont = new Font("Arcade Interlaced", Font.PLAIN, 80);
Color fontColor = new Color(0x00, 190, 100);
textWall.setFont(wallFont);
textWall.setForeground(fontColor);
textWall.setBackground(Color.BLACK);
textWall.setText("follow the white rabbit...");
textWall.setLineWrap(true);
textWall.setWrapStyleWord(true);
textWall.setFocusable(false);
countDown.setFont(lowerFont);
countDown.setHorizontalAlignment(SwingConstants.LEFT);
countDown.setForeground(fontColor);
extraField.setFont(lowerFont);
extraField.setHorizontalAlignment(SwingConstants.RIGHT);
extraField.setForeground(fontColor);
lowerPanel.setBackground(Color.BLACK);
container.setBackground(Color.BLACK);
countDown.setText(" 15:00.0");
extraField.setText(" ");
}
// @Override
// public void startTimer(int seconds) {
// timerSeconds = seconds*10;
// timerSecondsLast = seconds*10;
// timer.start();
// }
//
// @Override
// public void stopTimer() {
// timer.stop();
// timerSeconds = 0;
// timerSecondsLast = 0;
// }
//
// @Override
// public void pauseTimer(Boolean pause) {
// if(pause) {
// timer.stop();
// } else {
// timer.start();
// }
// }
@Override
public void setWall(final String message) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
textWall.setText(message);
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public void setExtra(final String text) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
extraField.setText(text + " ");
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public void setCountDown(final int tseconds) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
setCountDownText(tseconds);
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public void showCountDown(final Boolean show) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
countDown.setVisible(show);
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public void addListener(final GuiEventListener listener) {
listenerList.add(listener);
}
}

View File

@ -0,0 +1,10 @@
package de.ctdo.crashtest.irc;
/**
* @author: lucas
* @date: 01.06.12 10:05
*/
public interface IIrcClient {
void say(String message);
void addListener(IRCEventListener listenerIRC);
}

View File

@ -0,0 +1,10 @@
package de.ctdo.crashtest.irc;
/**
* @author: lucas
* @date: 01.06.12 11:49
*/
public interface IRCEventListener {
void handleMessage(final String message);
}

View File

@ -0,0 +1,83 @@
package de.ctdo.crashtest.irc;
import de.ctdo.crashtest.log.ILogger;
import de.ctdo.crashtest.log.Logger;
import jerklib.Channel;
import jerklib.ConnectionManager;
import jerklib.ProfileImpl;
import jerklib.Session;
import jerklib.events.ChannelMsgEvent;
import jerklib.events.ConnectionCompleteEvent;
import jerklib.events.IRCEvent;
import jerklib.events.JoinCompleteEvent;
import java.util.ArrayList;
import java.util.List;
/**
* IRC Client wrapper
* simplifies communication with the irc channel
*/
public class IrcClient implements IIrcClient, jerklib.events.listeners.IRCEventListener, ILogger {
private final List<IRCEventListener> listenerListIRC = new ArrayList<IRCEventListener>();
private final static String CHANNEL = "#crashtest2";
private Session ircsession;
public IrcClient() {
ConnectionManager ircConnection = new ConnectionManager(new ProfileImpl("crashtest", "crashtest",
"crashtest2", "crashtest3"));
ircsession = ircConnection.requestConnection("irc.chaostreff-dortmund.de");
ircsession.addIRCEventListener(this);
}
@Override
public void recieveEvent(IRCEvent ircEvent) {
if(ircEvent instanceof ConnectionCompleteEvent) {
ircEvent.getSession().joinChannel(CHANNEL);
}
else if (ircEvent instanceof JoinCompleteEvent) {
JoinCompleteEvent jce = (JoinCompleteEvent) ircEvent;
jce.getChannel().say("hello master. what's your order?");
Logger logger = Logger.getInstance();
logger.addLogger(this);
}
else if(ircEvent instanceof ChannelMsgEvent) {
ChannelMsgEvent cme = (ChannelMsgEvent)ircEvent;
String message = cme.getMessage();
final String nick = ircsession.getNick();
if(message.contains(nick)) {
message = message.substring(Math.max(nick.length(), message.indexOf(":")+1));
message = message.trim();
System.out.println("irc message: " + message);
for(IRCEventListener listenerIRC : listenerListIRC) {
listenerIRC.handleMessage(message);
}
}
}
}
@Override
public void log(String message) {
say("LOG: " + message);
}
@Override
public void say(String message) {
if(ircsession != null) {
for(Channel chan: ircsession.getChannels()) {
chan.say(message);
}
}
}
@Override
public void addListener(final IRCEventListener listenerIRC) {
listenerListIRC.add(listenerIRC);
}
}

View File

@ -0,0 +1,10 @@
package de.ctdo.crashtest.log;
/**
* @author: lucas
* @date: 01.06.12 16:46
*/
public interface ILogger {
void log(String message);
}

View File

@ -0,0 +1,34 @@
package de.ctdo.crashtest.log;
import java.util.ArrayList;
import java.util.List;
public class Logger {
private final static Logger instance = new Logger();
private final List<ILogger> loggerList = new ArrayList<ILogger>();
public void addLogger(ILogger listener) {
loggerList.add(listener);
}
private Logger() {
}
public static Logger getInstance() {
return instance;
}
public void log(String message) {
System.out.println("LOG: " + message);
for(ILogger logger: loggerList) {
logger.log(message);
}
}
public static void sLog(String message) {
getInstance().log(message);
}
}

View File

@ -0,0 +1,10 @@
package de.ctdo.crashtest.mpd;
/**
* @author: lucas
* @date: 01.06.12 10:36
*/
public interface IMPDController {
void playSong(String artist, String title);
void setVolume(int volume);
}

View File

@ -0,0 +1,63 @@
package de.ctdo.crashtest.mpd;
import de.ctdo.crashtest.log.Logger;
import org.bff.javampd.MPD;
import org.bff.javampd.MPDDatabase;
import org.bff.javampd.MPDPlayer;
import org.bff.javampd.exception.MPDConnectionException;
import org.bff.javampd.exception.MPDDatabaseException;
import org.bff.javampd.objects.MPDSong;
import java.net.UnknownHostException;
import java.util.Collection;
/**
* @author: lucas
* @date: 01.06.12 10:34
*/
public class MPDController implements IMPDController {
private MPD mpd;
private MPDPlayer player;
public MPDController() {
initMPD();
}
private void initMPD() {
try {
mpd = new MPD("dampfradio.raum.chaostreff-dortmund.de", 6600);
player = mpd.getMPDPlayer();
MPDDatabase database = mpd.getMPDDatabase();
Collection<MPDSong> bla = database.findTitle("");
} catch (UnknownHostException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDConnectionException e) {
Logger.sLog("MPD error: " + e.getMessage());
} catch (MPDDatabaseException e) {
Logger.sLog("MPD error: " + e.getMessage());
}
}
@Override
public void playSong(String artist, String title) {
if(mpd != null && player != null) {
// MPDSong finden in der DB
// dann abspielen
}
}
@Override
public void setVolume(int volume) {
if(mpd != null && player != null) {
}
}
}