How to use the 'svm_toy' Applet example in LibSVM? - java

I'm using LIBSVM. In the download package is a svm_toy.java file. I could not find out how it works. Here is the source code:
import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
/**
* SVM package
* #author unknown
*
*/
public class svm_toy extends Applet {
static final String DEFAULT_PARAM="-t 2 -c 100";
int XLEN;
int YLEN;
// off-screen buffer
Image buffer;
Graphics buffer_gc;
// pre-allocated colors
final static Color colors[] =
{
new Color(0,0,0),
new Color(0,120,120),
new Color(120,120,0),
new Color(120,0,120),
new Color(0,200,200),
new Color(200,200,0),
new Color(200,0,200)
};
class point {
point(double x, double y, byte value)
{
this.x = x;
this.y = y;
this.value = value;
}
double x, y;
byte value;
}
Vector<point> point_list = new Vector<point>();
byte current_value = 1;
public void init()
{
setSize(getSize());
final Button button_change = new Button("Change");
Button button_run = new Button("Run");
Button button_clear = new Button("Clear");
Button button_save = new Button("Save");
Button button_load = new Button("Load");
final TextField input_line = new TextField(DEFAULT_PARAM);
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
p.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 1;
gridbag.setConstraints(button_change,c);
gridbag.setConstraints(button_run,c);
gridbag.setConstraints(button_clear,c);
gridbag.setConstraints(button_save,c);
gridbag.setConstraints(button_load,c);
c.weightx = 5;
c.gridwidth = 5;
gridbag.setConstraints(input_line,c);
button_change.setBackground(colors[current_value]);
p.add(button_change);
p.add(button_run);
p.add(button_clear);
p.add(button_save);
p.add(button_load);
p.add(input_line);
this.add(p,BorderLayout.SOUTH);
button_change.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_change_clicked(); button_change.setBackground(colors[current_value]); }});
button_run.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
button_clear.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_clear_clicked(); }});
button_save.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_save_clicked(input_line.getText()); }});
button_load.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_load_clicked(); }});
input_line.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
void draw_point(point p)
{
Color c = colors[p.value+3];
Graphics window_gc = getGraphics();
buffer_gc.setColor(c);
buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
window_gc.setColor(c);
window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
}
void clear_all()
{
point_list.removeAllElements();
if(buffer != null)
{
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
repaint();
}
void draw_all_points()
{
int n = point_list.size();
for(int i=0;i<n;i++)
draw_point(point_list.elementAt(i));
}
void button_change_clicked()
{
++current_value;
if(current_value > 3) current_value = 1;
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
void button_run_clicked(String args)
{
// guard
if(point_list.isEmpty()) return;
svm_parameter param = new svm_parameter();
// default values
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 40;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = new int[0];
param.weight = new double[0];
// parse options
StringTokenizer st = new StringTokenizer(args);
String[] argv = new String[st.countTokens()];
for(int i=0;i<argv.length;i++)
argv[i] = st.nextToken();
for(int i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
if(++i>=argv.length)
{
System.err.print("unknown option\n");
break;
}
switch(argv[i-1].charAt(1))
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'w':
++param.nr_weight;
{
int[] old = param.weight_label;
param.weight_label = new int[param.nr_weight];
System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
}
{
double[] old = param.weight;
param.weight = new double[param.nr_weight];
System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
}
param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
System.err.print("unknown option\n");
}
}
// build problem
svm_problem prob = new svm_problem();
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == svm_parameter.PRECOMPUTED)
{
}
else if(param.svm_type == svm_parameter.EPSILON_SVR ||
param.svm_type == svm_parameter.NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
prob.x = new svm_node[prob.l][1];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.y[i] = p.y;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[1];
x[0] = new svm_node();
x[0].index = 1;
int[] j = new int[XLEN];
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm.svm_predict(model, x));
}
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(0,0,0,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(int i=1;i<XLEN;i++)
{
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(i,0,i,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(i,0,i,YLEN-1);
buffer_gc.setColor(colors[5]);
window_gc.setColor(colors[5]);
buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
window_gc.drawLine(i-1,j[i-1],i,j[i]);
if(param.svm_type == svm_parameter.EPSILON_SVR)
{
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
}
}
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
prob.x = new svm_node [prob.l][2];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.x[i][1] = new svm_node();
prob.x[i][1].index = 2;
prob.x[i][1].value = p.y;
prob.y[i] = p.value;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[2];
x[0] = new svm_node();
x[1] = new svm_node();
x[0].index = 1;
x[1].index = 2;
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
for (int j = 0; j < YLEN ; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm.svm_predict(model, x);
if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
buffer_gc.setColor(colors[(int)d]);
window_gc.setColor(colors[(int)d]);
buffer_gc.drawLine(i,j,i,j);
window_gc.drawLine(i,j,i,j);
}
}
draw_all_points();
}
void button_clear_clicked()
{
clear_all();
}
void button_save_clicked(String args)
{
FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
try {
DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
int svm_type = svm_parameter.C_SVC;
int svm_type_idx = args.indexOf("-s ");
if(svm_type_idx != -1)
{
StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
svm_type = atoi(svm_str_st.nextToken());
}
int n = point_list.size();
if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.y+" 1:"+p.x+"\n");
}
}
else
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
}
}
fp.close();
} catch (IOException e) { System.err.print(e); }
}
void button_load_clicked()
{
FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
clear_all();
try {
BufferedReader fp = new BufferedReader(new FileReader(filename));
String line;
while((line = fp.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
if(st.countTokens() == 5)
{
byte value = (byte)atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x,y,value));
}
else if(st.countTokens() == 3)
{
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x,y,current_value));
}else
break;
}
fp.close();
} catch (IOException e) { System.err.print(e); }
draw_all_points();
}
protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
{
if(e.getX() >= XLEN || e.getY() >= YLEN) return;
point p = new point((double)e.getX()/XLEN,
(double)e.getY()/YLEN,
current_value);
point_list.addElement(p);
draw_point(p);
}
}
public void paint(Graphics g)
{
// create buffer first time
if(buffer == null) {
buffer = this.createImage(XLEN,YLEN);
buffer_gc = buffer.getGraphics();
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
g.drawImage(buffer,0,0,this);
}
public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }
public void setSize(Dimension d) { setSize(d.width,d.height); }
public void setSize(int w,int h) {
super.setSize(w,h);
XLEN = w;
YLEN = h-50;
clear_all();
}
public static void main(String[] argv)
{
new AppletFrame("svm_toy",new svm_toy(),500,500+50);
}
}
class AppletFrame extends Frame {
AppletFrame(String title, Applet applet, int width, int height)
{
super(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
applet.init();
applet.setSize(width,height);
applet.start();
this.add(applet);
this.pack();
this.setVisible(true);
}
}
Could someone give me an example or explanation? I also would like to scale my training data. Where is the right place to scale?
Thanks

SVM-Toy
SVM Toy is - as the name suggests - a simple toy build by the LIBSVM dev team and is not recommended for "productive" visualization of the SVM's decision boundary.
Moreover looking into the source-code of svm_toy it becomes clear, that this tool only supports 2D vectors.
Relevant code fragment is taken from the button_load_clicked() Method:
while ((line = fp.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
if (st.countTokens() == 5) {
byte value = (byte) atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x, y, value));
} else if (st.countTokens() == 3) {
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x, y, current_value));
} else {
break;
}
}
As you can see, the svm_toy implementation can only handle 2D vectors, which means it only supports vectors, which were constructed out of two features.
That means, you can only read and display files which are build from only two features like for example the fourclass dataset provided by the LIBSVM authors. However it seems, that this feature is not supported within this implementation.
I think, that the tool is designed for interactive visualization. You are able to change the color and click on the black application screen. After you set some points (each color representing an own class), you can click "run" and the decision boundary is displayed.
Displaying the desicion boundary in an high dimensional vector space is even nearly impossible. I would recommend to not use this tool implementation for any productive / scientific purpose.
Scaling
Scaling of your training data should be done after you transformed it into it's numeric representation and before you are going forward to train your SVM with this data.
In short that means, you have to do the following steps before using svm_train
Construct the numeric representation for each data point (with the help of feature selection, ...)
Analyse the resulting numeric representation for each data point
Scale your data for example to [-1,1]
Go ahead and train your SVM model. Note well, that you have to repeat 1-3 for predicting unknown data points. The only difference is, that you already know the necessary features, so there is no need for feature selection.

Related

Java Socket Programming MultiPlayer Kart Racing Game

Basically, I am developing a multiplayer kart racing game in Java using TCP as the transport protocol.
Below are my codes, may I know why the gameframe is not showing up after the IP Address has been typed? Instead, currently it will only be shown after the server has closed down. I am using multi-threading to support sending and receiving.
Main (Client):-
public static void main(String[] args) throws IOException
{
String ipAddress = JOptionPane.showInputDialog(null, "Enter the address: ");
if (!ipAddress.isEmpty())
{
// Main program to declare GameFrame object
Socket socket = new Socket(ipAddress, 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
Thread thread = new Thread(new GameFrame(socket, reader, writer));
thread.start();
}
}
GameFrame:-
public class GameFrame extends JFrame implements Runnable
{
// Exit message
private final String message = "Are you sure you want to exit the game?";
// Exit message popup title
private final String title = "Exiting Game";
// Declare RacingTrack object
private RacingTrack racingTrack;
// Declare JFrame object
private JFrame mainGameFrame;
public GameFrame(Socket socket, BufferedReader reader, DataOutputStream writer)
{
racingTrack = new RacingTrack(socket, reader, writer);
mainGameFrame = new JFrame();
mainGameFrame.setBounds(0, 0, 900, 700);
mainGameFrame.setLocationRelativeTo(null);
mainGameFrame.setVisible(true);
mainGameFrame.add(racingTrack);
mainGameFrame.addKeyListener(racingTrack);
mainGameFrame.setResizable(false);
mainGameFrame.setTitle("Karts Racing Game");
mainGameFrame.setFocusable(true);
mainGameFrame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
mainGameFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION)
mainGameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else if (result == JOptionPane.NO_OPTION)
mainGameFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
}
#Override
public void run()
{
System.out.println("Game Frame Thread running.");
mainGameFrame.setVisible(true);
}
Server:-
public class Server
{
public static void main( String args[] )
{
int connectedClient = 0;
ServerSocket service = null;
Socket server = null;
BufferedReader inputStream;
DataOutputStream outputStream;
try
{
service = new ServerSocket(8888);
System.out.println("Server has started.");
}
catch (IOException e)
{
System.out.println(e);
}
try
{
while (connectedClient < 2)
{
server = service.accept();
connectedClient++;
ClientThread clientThread = new ClientThread(server, connectedClient);
System.out.println("Player " + connectedClient + " connected. IP Address: " + server.getInetAddress());
Thread thread = new Thread(clientThread);
thread.start();
System.out.println("Player: " + connectedClient + " thread running.");
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
ClientThread:-
public class ClientThread implements Runnable
{
Socket socket;
int playerNum;
boolean keepRunning = true;
int kartNumIndex;
int x;
int y;
int speed;
BufferedReader reader;
DataOutputStream writer;
ArrayList<ClientThread> clients = new ArrayList<>();
public ClientThread(Socket socket, int player)
{
this.socket = socket;
this.playerNum = player;
}
#Override
public void run()
{
try
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new DataOutputStream(socket.getOutputStream());
writer.writeByte(playerNum);
writer.flush();
while (keepRunning == true)
{
playerNum = reader.read();
kartNumIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
broadcastToAllClients(playerNum, kartNumIndex, x, y, speed);
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
public void broadcastToAllClients(int playerNum, int kartNumIndex, int x, int y, int speed)
{
try
{
for (ClientThread client : clients)
{
client.writer.write(playerNum);
client.writer.write(kartNumIndex);
client.writer.write(x);
client.writer.write(y);
client.writer.write(speed);
client.writer.flush();
}
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
}
RacingTrack Constructor (partial):-
public class RacingTrack extends JPanel implements KeyListener
{
Socket clientSocket;
BufferedReader reader;
DataOutputStream writer;
int playerNum;
int kartNum;
int kartImageIndex;
int x;
int y;
int speed;
private Kart kart1;
private Kart kart2;
private SoundEffect soundEffect;
private Timer animationTimer;
private final int delay = 0;
private Set<Integer> pressedKeys;
boolean isKart1Lose;
boolean isKart2Lose;
private ElapseCounter kart1T;
private ElapseCounter kart2T;
/* Coordinates, Width, and Height of the value given and modified */
/* Racing Track 1 */
// Grass
private final int GRASS_X_COOR = 150;
private final int GRASS_Y_COOR = 200;
private final int GRASS_WIDTH = 550;
private final int GRASS_HEIGHT = 320;
// Outer Edge
private final int OUTER_EDGE_X_COOR = 50;
private final int OUTER_EDGE_Y_COOR = 100;
private final int OUTER_EDGE_WIDTH = 750;
private final int OUTER_EDGE_HEIGHT = 520;
// Inner Edge
private final int INNER_EDGE_X_COOR = 150;
private final int INNER_EDGE_Y_COOR = 200;
private final int INNER_EDGE_WIDTH = 550;
private final int INNER_EDGE_HEIGHT = 320;
// Mid Lane
private final int MID_LANE_X_COOR = 100;
private final int MID_LANE_Y_COOR = 150;
private final int MID_LANE_WIDTH = 650;
private final int MID_LANE_HEIGHT = 420;
// Start Line
private final int START_LINE_X1_COOR = 425;
private final int START_LINE_Y1_COOR = 520;
private final int START_LINE_X2_COOR = 425;
private final int START_LINE_Y2_COOR = 620;
/* Racing Track 2 */
// Grass
private final int GRASS_TOP_X_COOR = 450;
private final int GRASS_TOP_Y_COOR = 240;
private final int GRASS_LEFT_X_COOR = 260;
private final int GRASS_LEFT_Y_COOR = 520;
private final int GRASS_RIGHT_X_COOR = 640;
private final int GRASS_RIGHT_Y_COOR = 520;
// Outer Lane
private final int OUTER_LANE_TOP_X_COOR = 450;
private final int OUTER_LANE_TOP_Y_COOR = 110;
private final int OUTER_LANE_LEFT_X_COOR = 50;
private final int OUTER_LANE_LEFT_Y_COOR = 622;
private final int OUTER_LANE_RIGHT_X_COOR = 850;
private final int OUTER_LANE_RIGHT_Y_COOR = 622;
// Mid Lane
private final int MID_LANE_TOP_X_COOR = 450;
private final int MID_LANE_TOP_Y_COOR = 170;
private final int MID_LANE_LEFT_X_COOR = 140;
private final int MID_LANE_LEFT_Y_COOR = 570;
private final int MID_LANE_RIGHT_X_COOR = 760;
private final int MID_LANE_RIGHT_Y_COOR = 570;
// Obtain car shape bounds
private Rectangle kart1Shape;
private Rectangle kart2Shape;
// Obtain outer edges bound
private Rectangle outerEdgeLeft = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, 1, OUTER_EDGE_HEIGHT);
private Rectangle outerEdgeTop = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, OUTER_EDGE_WIDTH, 1);
private Rectangle outerEdgeRight = new Rectangle(OUTER_EDGE_X_COOR + OUTER_EDGE_WIDTH, OUTER_EDGE_Y_COOR, 1, OUTER_EDGE_HEIGHT);
private Rectangle outerEdgeBottom = new Rectangle(OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR + OUTER_EDGE_HEIGHT, OUTER_EDGE_WIDTH, 1);
private Line2D outerEdgeTop2 = new Line2D.Double(OUTER_LANE_TOP_X_COOR, OUTER_LANE_TOP_Y_COOR, OUTER_LANE_LEFT_X_COOR, OUTER_LANE_LEFT_Y_COOR);
private Line2D outerEdgeLeft2 = new Line2D.Double(OUTER_LANE_LEFT_X_COOR, OUTER_LANE_LEFT_Y_COOR, OUTER_LANE_RIGHT_X_COOR, OUTER_LANE_RIGHT_Y_COOR);
private Line2D outerEdgeRight2 = new Line2D.Double(OUTER_LANE_RIGHT_X_COOR, OUTER_LANE_RIGHT_Y_COOR, OUTER_LANE_TOP_X_COOR, OUTER_LANE_TOP_Y_COOR);
private Rectangle innerEdgeLeft = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR, 1, GRASS_HEIGHT);
private Rectangle innerEdgeTop = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR, GRASS_WIDTH, 1);
private Rectangle innerEdgeRight = new Rectangle(GRASS_X_COOR + GRASS_WIDTH, GRASS_Y_COOR, 1, GRASS_HEIGHT);
private Rectangle innerEdgeBottom = new Rectangle(GRASS_X_COOR, GRASS_Y_COOR + GRASS_HEIGHT, GRASS_WIDTH, 1);
private Line2D innerEdgeTop2 = new Line2D.Double(GRASS_TOP_X_COOR, GRASS_TOP_Y_COOR, GRASS_LEFT_X_COOR, GRASS_LEFT_Y_COOR);
private Line2D innerEdgeLeft2 = new Line2D.Double(GRASS_LEFT_X_COOR, GRASS_LEFT_Y_COOR, GRASS_RIGHT_X_COOR, GRASS_RIGHT_Y_COOR);
private Line2D innerEdgeRight2 = new Line2D.Double(GRASS_RIGHT_X_COOR, GRASS_RIGHT_Y_COOR, GRASS_TOP_X_COOR, GRASS_TOP_Y_COOR);
// Obtain goal line bound
private Rectangle goalLineBound = new Rectangle(START_LINE_X1_COOR, START_LINE_Y1_COOR, 1, START_LINE_Y2_COOR - START_LINE_Y1_COOR);
// Constructor
public RacingTrack(Socket socket, BufferedReader reader, DataOutputStream writer)
{
this.reader = reader;
this.writer = writer;
try
{
playerNum = reader.read();
System.out.println("I am Player Number " + playerNum);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
// Set this JPanel to allow overlay layout
// so that the kart icons can be printed above it
this.setLayout(new OverlayLayout(this));
// Create kart objects
// Specify the kart number, x-coordinates and y-coordinates
// kart1 = new Kart(1, 430, 521);
// kart2 = new Kart(2, 430, 570);
if (playerNum == 1)
{
kart1 = new Kart(1, 430, 521);
try
{
writer.write(kart1.getKartNum());
writer.write(kart1.getKartImageIndex());
writer.write(kart1.getXCoordinate());
writer.write(kart1.getYCoordinate());
writer.write(kart1.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart2 = new Kart(kartNum, x, y);
kart2.setKartImageIndex(kartImageIndex);
kart2.setSpeed(speed);
}
else if (playerNum == 2)
{
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart1 = new Kart(kartNum, x, y);
kart1.setKartImageIndex(kartImageIndex);
kart1.setSpeed(speed);
kart2 = new Kart(1, 430, 570);
try
{
writer.write(kart2.getKartNum());
writer.write(kart2.getKartImageIndex());
writer.write(kart2.getXCoordinate());
writer.write(kart2.getYCoordinate());
writer.write(kart2.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
if (playerNum == 1)
kart1.start();
else if (playerNum == 2)
kart2.start();
isKart1Lose = false;
isKart2Lose = false;
kart1T = new ElapseCounter();
kart2T = new ElapseCounter();
pressedKeys = new HashSet<>();
animationTimer = new Timer(delay, new TimeHandler());
animationTimer.start();
}
private class TimeHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
speedLabel.setText("<html>Kart 1 Speed: " + kart1.getSpeed() + " <br> Kart 2 Speed: " + kart2.getSpeed() + "</html>");
kart1Shape = kart1.getKartShape();
kart2Shape = kart2.getKartShape();
if (playerNum == 1)
{
if (isKart1Lose == false)
{
if (kart1Shape.intersects(outerEdgeLeft))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeTop))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeRight))
setKart1Lose();
else if (kart1Shape.intersects(outerEdgeBottom))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeLeft))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeTop))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeRight))
setKart1Lose();
else if (kart1Shape.intersects(innerEdgeBottom))
setKart1Lose();
else if (kart1Shape.intersects(goalLineBound))
winnerFound(1);
}
}
else if (playerNum == 2)
{
if (isKart2Lose == false)
{
if (kart2Shape.intersects(outerEdgeLeft))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeTop))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeRight))
setKart2Lose();
else if (kart2Shape.intersects(outerEdgeBottom))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeLeft))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeTop))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeRight))
setKart2Lose();
else if (kart2Shape.intersects(innerEdgeBottom))
setKart2Lose();
else if (kart2Shape.intersects(goalLineBound))
winnerFound(2);
}
}
if (kart1Shape.intersects(kart2Shape))
{
if (playerNum == 1)
isKart1Lose = true;
else
isKart2Lose = true;
if (playerNum == 1)
kart1T.setStop();
else
kart2T.setStop();
animationTimer.stop();
if (playerNum == 1)
kart1.stop();
else
kart2.stop();
}
if (isKart1Lose == true && isKart2Lose == true)
bothKartsCrashed();
repaint();
}
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
super.setBackground(Color.gray);
Color c1 = Color.green;
Color c2 = Color.black;
Color c3 = Color.white;
g.setColor( c1 );
// x-coordinate, y-coordinate, width, height
g.fillRect( GRASS_X_COOR, GRASS_Y_COOR, GRASS_WIDTH, GRASS_HEIGHT ); // grass
g.setColor( c2 );
g.drawRect( OUTER_EDGE_X_COOR, OUTER_EDGE_Y_COOR, OUTER_EDGE_WIDTH, OUTER_EDGE_HEIGHT ); // outer edge
g.drawRect( INNER_EDGE_X_COOR, INNER_EDGE_Y_COOR, INNER_EDGE_WIDTH, INNER_EDGE_HEIGHT ); // inner edge
g.setColor( c3 );
Graphics2D g2d = (Graphics2D)g.create();
Stroke dashed = new BasicStroke(2, BasicStroke.JOIN_BEVEL, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
g2d.setStroke(dashed);
g2d.drawRect( MID_LANE_X_COOR, MID_LANE_Y_COOR, MID_LANE_WIDTH, MID_LANE_HEIGHT ); // mid-lane marker
g2d.dispose();
g.drawLine( START_LINE_X1_COOR, START_LINE_Y1_COOR, START_LINE_X2_COOR, START_LINE_Y2_COOR ); // start line
if (playerNum == 1)
{
try
{
writer.write(kart1.getKartNum());
writer.write(kart1.getKartImageIndex());
writer.write(kart1.getXCoordinate());
writer.write(kart1.getYCoordinate());
writer.write(kart1.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart1.draw(g, this);
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
kart2.draw(g, this, x, y);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
else if (kartNum == 2)
{
try
{
writer.write(kart2.getKartNum());
writer.write(kart2.getKartImageIndex());
writer.write(kart2.getXCoordinate());
writer.write(kart2.getYCoordinate());
writer.write(kart2.getSpeed());
writer.flush();
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
kart2.draw(g, this);
try
{
kartNum = reader.read();
kartImageIndex = reader.read();
x = reader.read();
y = reader.read();
speed = reader.read();
kart1.draw(g, this, x, y);
}
catch (IOException iOe)
{
iOe.printStackTrace();
}
}
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public synchronized void keyPressed(KeyEvent e)
{
int speed;
int carImageIndex;
// Add keypresses
pressedKeys.add(e.getKeyCode());
for (Iterator<Integer> it = pressedKeys.iterator(); it.hasNext();)
{
switch (it.next())
{
/* kart blue */
// Increase speed
// Each key press increases speed by 10
case KeyEvent.VK_UP:
if (isKart1Lose == false)
{
// get kart's speed
speed = kart1.getSpeed();
// increase the initial speed by 10
kart1.setSpeed(speed + 10);
// check if speed is more than 100
// if yes, set to 100 (maximum)
if (kart1.getSpeed() > 100)
kart1.setSpeed(100);
// drive the kart forward with the speed
moveForwardKart1(kart1.getSpeed());
}
break;
// Decrease speed
// Each key press decreases speed by 10
case KeyEvent.VK_DOWN:
if (isKart1Lose == false)
{
// get kart's speed
speed = kart1.getSpeed();
// decrease the initial speed by 10
kart1.setSpeed(speed - 10);
// check if speed is less than 0
// if yes, set to -1, then kart will reverse
// minimum is -1
if (kart1.getSpeed() < 0)
{
kart1.setSpeed(-1);
moveBackwardKart1();
}
// check if speed is 0
// if no, then drive the kart forward with the set speed
if (kart1.getSpeed() > 0)
moveForwardKart1(kart1.getSpeed());
}
break;
// Turn the kart to the left
case KeyEvent.VK_LEFT:
if (isKart1Lose == false)
{
// get kart's image index
carImageIndex = kart1.getKartImageIndex();
// set the kart's new image index
kart1.setKartImageIndex(carImageIndex - 1);
// if kart's image index is less than 0
// set it to 15
if (carImageIndex - 1 < 0)
kart1.setKartImageIndex(15);
}
break;
// Turn the kart to the right
case KeyEvent.VK_RIGHT:
if (isKart1Lose == false)
{
// get kart's image index
carImageIndex = kart1.getKartImageIndex();
// set the kart's new image index
kart1.setKartImageIndex(carImageIndex + 1);
// if kart's image index is more than 15
// set it to 0
if (carImageIndex + 1 > 15)
kart1.setKartImageIndex(0);
}
break;
}
}
}
#Override
public void keyReleased(KeyEvent e)
{
pressedKeys.remove(e.getKeyCode());
}
// For KART1
// Method that drive the kart forward with appropriate speed
// speed will affect the pixel displacement
// (speed / 10) to get the first digit so that the kart can move accordingly
// if speed is 1, the kart moves by 1 pixel; ie: x + 1 or y + 1 depends on direction
// if speed is 5, the kart moves by 5 pixel; ie: x + 5 or y + 5 depends on direction
// this is done by increasing or decreasing the x and/or y coordinates
private void moveForwardKart1(int speed)
{
switch (kart1.getKartImageIndex())
{
case 0:
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
case 1:
case 2:
case 3:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
case 4:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
break;
case 5:
case 6:
case 7:
kart1.setXCoordinate(kart1.getXCoordinate() + (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 8:
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 9:
case 10:
case 11:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() + (speed / 10));
break;
case 12:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
break;
case 13:
case 14:
case 15:
kart1.setXCoordinate(kart1.getXCoordinate() - (speed / 10));
kart1.setYCoordinate(kart1.getYCoordinate() - (speed / 10));
break;
}
}
// For KART1
// Method that drive the kart backward (reverse)
// the coordinate(s) will only be increased or decreased by 1 pixel
// this is done by increasing or decreasing the x and/or y coordinates
private void moveBackwardKart1()
{
switch (kart1.getKartImageIndex())
{
case 0:
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
case 1:
case 2:
case 3:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
case 4:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
break;
case 5:
case 6:
case 7:
kart1.setXCoordinate(kart1.getXCoordinate() - 1);
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 8:
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 9:
case 10:
case 11:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
kart1.setYCoordinate(kart1.getYCoordinate() - 1);
break;
case 12:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
break;
case 13:
case 14:
case 15:
kart1.setXCoordinate(kart1.getXCoordinate() + 1);
kart1.setYCoordinate(kart1.getYCoordinate() + 1);
break;
}
}
}
Your code opens the socket, then raises a new thread to start the game.
The socket, reader and writer are passed into that thread until they arrive at the RacingTrack. The RacingTrack constructor immediately tries to send/receive data, and be aware reading data is a blocking call. It waits until the data has been read.
So unless you close the server and thus the TCP connection is cut, the client still hopes to receive some data and therefore waits patiently.

Communication beetwen sockets stops working after one message. BattleShipGame Swing

At the beggining I send string of tables stating where enemy ships are placed. Then in the loop (infinite for now) i try to send one message and listen one depending which turn is. After one message send and recived loops stop looping. I have suspect that it may have something to do with thread but i have no idea how to approach this. I don't expect o anyone dig through all this code but but i think it's better to include more code then less. I mainly looking for some guidance. Code below and thank you for your help.
Main class (i think customMousePressed & actionPerformed could be the main culprits)
public class BattleShipGame extends JFrame implements ActionListener {
//this 268, Draw 112 /////////////////////////////////////
private Optional<Ship> newShip;
private int logicPosX;
private int logicPosY;
private Coordinates start;
static String coordinatesInput = "", coordinatesOutput = "";
static boolean myturn = false;
private static int counter = 0;
static boolean connected = false;
Captain player = new Captain();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BattleShipGame());
}
private BattleShipGame()
{
this.setTitle("Battleship Game");
this.setSize(1100, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
JPanel panel = new JPanel();
player.initializeShips();
Timer timer = new Timer(20, this);
DrawBoardAndShips boardAndShips = new DrawBoardAndShips(player);
timer.start();
//create player
//set your ships (one map & ships to drag from place to place)
//when READY button clicked and all ships are on board ->
//->search for player (Connection - sockets)
//draw 2 maps (one with ships, one to shoot)
//receive coordinates (hit or miss - draw changes to 1 map) - win condition checker (send info to another player about shoot result)
//send coordinates
JButton reset = new JButton("RESET");
reset.addActionListener(e -> {
//set to default position of ships
player.resetPositions();
player.getShips().forEach(ship -> ship.setShipOnBoard(false));
});
JButton ready = new JButton("READY!");
ready.addActionListener((ActionEvent e) -> { //set logic when button ready pressed
//check if all ships are on board
//set ready = true
if (player.getShips().stream().filter(Ship::isShipOnBoard).count() == 10 && e.getSource() == ready) {
//set logic
for (Ship ship : player.getShips()) {
player.setMyBoard(ship);
}
//establish network connection
boolean outcome = serverOrClientDecision(JOptionPane.YES_OPTION, player);
if(outcome) {
panel.remove(reset);
panel.remove(ready);
}
revalidate();
repaint();
}
});
panel.add(reset);
panel.add(ready);
this.add(panel, BorderLayout.SOUTH);
this.add(boardAndShips, BorderLayout.CENTER);
boardAndShips.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
customMouseDragged(player, e);
}
});
boardAndShips.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
customMouseClicked(e, player);
}
#Override
public void mousePressed(MouseEvent e) {
customMousePressed(e, player);
}
#Override
public void mouseReleased(MouseEvent e) {
customMouseReleased(player);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(!coordinatesInput.isEmpty() && !player.isMyTurn()){
String[] parts = coordinatesInput.split("\\."); //////////////////
logicPosX = Integer.parseInt(parts[0]);
logicPosY = Integer.parseInt(parts[1]);
if (player.getMyBoard()[logicPosX][logicPosY] == 1) {
player.getMyBoard()[logicPosX][logicPosY] = 2;
isSunk(player.getMyBoard());
}
else if(player.getMyBoard()[logicPosX][logicPosY] == 0)
player.getMyBoard()[logicPosX][logicPosY] = -1;
coordinatesInput = "";
player.setMyTurn(true);
}
repaint();
}
public boolean serverOrClientDecision(int decision, Captain player) {
Object[] options = {"CREATE", "JOIN", "EXIT"};
Object[] options2 = {"BACK", "TRY AGAIN", "EXIT"};
if (decision == JOptionPane.YES_OPTION) {
decision = JOptionPane.showOptionDialog(this, "Create game or join one?", "Battleship Game",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null);
}
//
if(decision == JOptionPane.CANCEL_OPTION)
return false;
if (decision == JOptionPane.YES_OPTION) {
//create server
SwingWorker<Void, Void> worker = new SwingWorker<>() {
#Override
protected Void doInBackground() throws Exception {
Server server = new Server(player);
return null;
}
};
worker.execute();
} else if (decision == JOptionPane.NO_OPTION) {
//getting IP
String serversIP = JOptionPane.showInputDialog("Type server's IP");
//creating client
SwingWorker<Void, Boolean> worker1 = new SwingWorker<>() {
#Override
protected Void doInBackground() throws IOException {
Client client = new Client(serversIP, player);
return null;
}
};
worker1.execute();
while (!worker1.isDone()) {
if (connected == true)
break;
}
if (!connected) {
decision = JOptionPane.showOptionDialog(this, "Host not responding", "Join Game",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options2, null);
serverOrClientDecision(decision, player);
}
}
return true;
}
public void customMouseDragged(Captain player, MouseEvent e) {
if (player.getReady() == 0) {
newShip.filter(Ship::isHorizontal)
.ifPresent(ship -> ship.setCoordinates(new Coordinates(e.getX() - ship.getSize() * 16, e.getY() - 16)));
newShip.filter(ship -> !ship.isHorizontal())
.ifPresent(ship -> ship.setCoordinates(new Coordinates(e.getX() - 16, e.getY() - ship.getSize() * 16)));
}
}
public void customMouseClicked(MouseEvent e, Captain player) {
if (player.getReady() == 0) {
//ship is in bounds of the BOARD after rotating
player.getShips().stream()
.filter(ship -> ship.getBounds().contains(e.getPoint()))
.filter(ship -> (logicPosX < 11 && logicPosY + ship.getSize() < 11 && ship.isHorizontal())
|| (logicPosX + ship.getSize() < 11 && logicPosY < 11 && !ship.isHorizontal()))
.forEach(ship -> ship.setHorizontal(!ship.isHorizontal()));
//ship don't overlap space of other ship, if does revert rotation to previous state
if(newShip.isPresent()) {
player.getShips().stream()
.filter(ship -> ship.getId() != newShip.get().getId())
.filter(ship -> ship.getBigBounds().intersects(newShip.get().getBounds()))
.forEach(ship -> {
newShip.get().setHorizontal(!newShip.get().isHorizontal());
});
}
}
}
public void customMousePressed(MouseEvent e, Captain player) {
if (player.getReady() == 0) {
logicPosX = logicPosY = -1;
//picking up ship
newShip = player.getShips().stream().
filter(ship -> ship.getBounds().contains(e.getPoint()))
.findAny();
newShip.ifPresent(newShip -> start = newShip.getCoordinates());
} else if (player.getReady() == 2 && player.isMyTurn()) {
//System.out.println(e.getPoint().toString());
//-1 - uncovered (miss)
// 0 - covered (miss)
// 1 - covered (hit)
// 2 - uncovered (hit)
// 3 - uncovered (hit and sunk)
// is shoot in bounds of the enemy BOARD
if ((e.getX() > 600 && e.getX() < 920) && (e.getY() > 50 && e.getY() < 370)){
logicPosX = (e.getX() - 600) / 32;
logicPosY = (e.getY() - 50) / 32;
if (player.getEnemyBoard()[logicPosX][logicPosY] == 1) { // if covered (hit)
player.getEnemyBoard()[logicPosX][logicPosY] = 2;// set as uncovered (hit)
//check if ship sunk
isSunk(player.getEnemyBoard());
coordinatesOutput = Integer.toString(logicPosX) + "." + Integer.toString(logicPosY);
player.setMyTurn(false);
coordinatesOutput = "";
}
else if (player.getEnemyBoard()[logicPosX][logicPosY] == 0) { //if covered (miss)
player.getEnemyBoard()[logicPosX][logicPosY] = -1; // set as uncovered (miss)
coordinatesOutput = Integer.toString(logicPosX) + "." + Integer.toString(logicPosY);
player.setMyTurn(false);
coordinatesOutput = "";
}
}
}
}
public void customMouseReleased(Captain player) {
if (player.getReady() == 0) {
if (newShip.isPresent()) {
logicPosX = (newShip.get().getCoordinates().getX() - 150) / 32;
logicPosY = (newShip.get().getCoordinates().getY() - 50) / 32;
//ship placed on board
if (((logicPosX + newShip.get().getSize() < 11) && (logicPosY < 11) && newShip.get().isHorizontal() && logicPosX > -1 && logicPosY > -1)
|| ((logicPosX < 11) && (logicPosY + newShip.get().getSize() < 11) && !newShip.get().isHorizontal() && logicPosX > -1 && logicPosY > -1)) {
//adjust to grid
newShip.get().getCoordinates().setX(150 + logicPosX * 32);
newShip.get().getCoordinates().setY(50 + logicPosY * 32);
newShip.ifPresent(newShip -> newShip.setShipOnBoard(true));
//ship don't overlap space of other ship, if does revert move
player.getShips().stream()
.filter(ship -> ship.getId() != newShip.get().getId())
.filter(ship -> ship.getBigBounds().intersects(newShip.get().getBounds()))
.forEach(ship -> {
newShip.get().setCoordinates(start);
newShip.get().setShipOnBoard(false);
});
} else {
newShip.get().setHorizontal(true);
newShip.get().setCoordinates(start);
}
}
}
}
private void isSunk(int[][] board) {
int struck = 0;
int notStruck = 0;
Point[] struckPositions = new Point[4];
//checking every direction for not struck poles in ship
for (int n = 0; n < 4; n++) {
if (logicPosY - n > 0){
if (board[logicPosX][logicPosY - n] == 2) {
struckPositions[struck] = new Point(logicPosX, logicPosY);
struck++;
}
else if(board[logicPosX][logicPosY - n] == 1)
notStruck++;
else if(board[logicPosX][logicPosY - n] == 0)
break;
}
else
break;
}
for (int s = 1; s < 4; s++) {
if (logicPosY + s < 10){
if (board[logicPosX][logicPosY + s] == 2) {
struckPositions[struck] = new Point(logicPosX, logicPosY);
struck++;
}
else if(board[logicPosX][logicPosY + s] == 1)
notStruck++;
else if(board[logicPosX][logicPosY + s] == 0)
break;
}
else
break;
}
for (int e = 1; e < 4; e++) {
if (logicPosX + e < 10){
if (board[logicPosX + e][logicPosY] == 2) {
struckPositions[struck] = new Point(logicPosX, logicPosY);
struck++;
}
else if(board[logicPosX + e][logicPosY] == 1)
notStruck++;
else if(board[logicPosX + e][logicPosY] == 0)
break;
}
else
break;
}
for (int w = 1; w < 4; w++) {
if (logicPosX - w > 0){
if (board[logicPosX - w][logicPosY] == 2) {
struckPositions[struck] = new Point(logicPosX, logicPosY);
struck++;
}
else if(board[logicPosX - w][logicPosY] == 1)
notStruck++;
else if(board[logicPosX - w][logicPosY] == 0)
break;
}
else
break;
}
// if sunk change it in logical table
if (notStruck == 0){
for (Point p : struckPositions){
board[p.x][p.y] = 3;
//return int = struck
}
}
//else return -1; - in future to display sunk ships as small squares next to tables
}
}
Server
class Server extends Thread {
ServerSocket serverSocket;
Socket socket;
DataInputStream dataInputStream;
DataOutputStream dataOutputStream;
String sendMessage = "", message1 = "", receivedMessage = "";
public Server(Captain player) throws IOException {
System.out.println("SERVER");
int asd = 0;
player.setReady(1);
serverSocket = new ServerSocket(6666);
socket = serverSocket.accept();
player.setReady(2);
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//send logic table at the beginning of the game
for(int i1 = 0; i1 < player.getMyBoard().length; i1++){
for (int j = 0; j < player.getMyBoard()[i1].length; j++){
if(player.getMyBoard()[j][i1] == 1) /////////////////////
sendMessage += "1";
else
sendMessage += "0";
}
}
dataOutputStream.writeUTF(sendMessage);
sendMessage = "";
/*System.out.println("Sever get from Client: " + dataInputStream.readUTF());
System.out.println("Server send: " + start);*/
//receive String and convert it to enemy logic table
receivedMessage = dataInputStream.readUTF();
player.setEnemyBoard(receivedMessage);
receivedMessage = "";
player.setMyTurn(true);
while(!message1.equals("WIN") || !message1.equals("LOOSE")){
dataOutputStream.writeUTF(BattleShipGame.coordinatesOutput);
BattleShipGame.coordinatesOutput = "";
System.out.println("__");
if(!player.isMyTurn()) {
receivedMessage = dataInputStream.readUTF();
System.out.println("server NOT my turn");
if(!receivedMessage.isEmpty()) {
BattleShipGame.coordinatesInput = receivedMessage;
receivedMessage = "";
//player.setMyTurn(true);
}
} else {
sendMessage = BattleShipGame.coordinatesOutput;
System.out.print(asd++);
if(!sendMessage.isEmpty()) {
dataOutputStream.writeUTF(sendMessage);
sendMessage = "";
//player.setMyTurn(false);
}
}
dataOutputStream.flush();
}
dataInputStream.close();
socket.close();
serverSocket.close();
}
}
Client
public class Client {
Socket socket;
DataInputStream dataInputStream;
DataOutputStream dataOutputStream;
BufferedReader bufferedReader;
String sendMessage = "", message1 = "", receivedMessage = "";
public Client(String host, Captain player) throws IOException {
System.out.println("CLIENT");
socket = new Socket(host, 6666);
player.setReady(2);
BattleShipGame.connected = socket.isConnected();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//send logic table at the beginning of the game
for(int i1 = 0; i1 < player.getMyBoard().length; i1++){
for (int j = 0; j < player.getMyBoard()[i1].length; j++){
if(player.getMyBoard()[j][i1] == 1)
sendMessage += "1";
else
sendMessage += "0";
}
}
dataOutputStream.writeUTF(sendMessage);
sendMessage = "";
/*System.out.println("Client get from Server: " + dataInputStream.readUTF());
System.out.println("Client sends: " + start);*/
//receive String and convert it to enemy logic table
receivedMessage = dataInputStream.readUTF();
player.setEnemyBoard(receivedMessage);
receivedMessage = "";
player.setMyTurn(false);
while(!message1.equals("WIN") || !message1.equals("LOOSE")){
System.out.print("c");
if(!player.isMyTurn()) {
receivedMessage = dataInputStream.readUTF();
System.out.println("client NOT my turn"); /////////////////////////////
if(!receivedMessage.isEmpty()) {
BattleShipGame.coordinatesInput = receivedMessage;
receivedMessage = "";
}
} else {
sendMessage = BattleShipGame.coordinatesOutput;
System.out.println("client MY turn"); ////////////////////////////
if(!sendMessage.isEmpty()) {
dataOutputStream.writeUTF(sendMessage);
sendMessage = "";
}
}
dataOutputStream.flush();
}
dataInputStream.close();
socket.close();
}
}

Load MTL Files in LWJGL

So I am making a "game" with LWJGL, and I started loading 3D Models (Using Wavefront .obj files). I have successfully loaded the model, but instead of having textures, I wanted to try out the .mtl files, to specify the materials. I "sort of" made it, but it seems to be not completely working. Here is my code, and a picture of the Tree model I tried to render:
Tree Model
Now here is my code:
private static OBJMesh mesh;
public static Mesh load3DModel(String objFileName)
{
mesh = new OBJMesh();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(new File(objFileName)));
}
catch (FileNotFoundException e)
{
System.err.println("Could not locate OBJ File at " + objFileName);
e.printStackTrace();
}
String mtlFileName = null;
String line = null;
String currentFaceMat = null;
try
{
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
switch (line.substring(0, 2))
{
case "v ":
Vertex v = new Vertex(lineParts[1], lineParts[2], lineParts[3]);
mesh.addVertex(v);
break;
case "vn":
Normal n = new Normal(lineParts[1], lineParts[2], lineParts[3]);
mesh.addNormal(n);
break;
case "mt":
mtlFileName = FileHelper.getDirectory(objFileName) + lineParts[1];
break;
case "us":
currentFaceMat = lineParts[1];
break;
case "f ":
Face face = createFace(currentFaceMat, lineParts);
mesh.addFace(face);
break;
}
}
reader = new BufferedReader(new FileReader(mtlFileName));
Material mat = null;
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
if (line.length() > 1)
{
switch (line.substring(0, 2))
{
case "ne":
mat = new Material(lineParts[1]);
mesh.addMaterial(lineParts[1], mat);
break;
case "Ka":
mat.setKa(createVector(lineParts));
break;
case "Kd":
mat.setKd(createVector(lineParts));
break;
case "Ks":
mat.setKs(createVector(lineParts));
break;
case "Ns":
mat.setNs(Float.parseFloat(lineParts[1]));
break;
case "d ":
mat.setD(Float.parseFloat(lineParts[1]));
break;
case "il":
mat.setIllum(Integer.parseInt(lineParts[1]));
break;
}
}
}
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
mesh.normalArray = new float[mesh.vertices.size() * 3];
for (Face face : mesh.faces)
{
decodeNormals(face.indices1);
decodeNormals(face.indices2);
decodeNormals(face.indices3);
}
mesh.vertexArray = new float[mesh.vertices.size() * 3];
mesh.indexArray = new int[mesh.indices.size() * 3];
mesh.colorArray = new float[mesh.faces.size() * 3];
int vertexPointer = 0;
for (Vertex vertex : mesh.vertices)
{
mesh.vertexArray[vertexPointer++] = vertex.x;
mesh.vertexArray[vertexPointer++] = vertex.y;
mesh.vertexArray[vertexPointer++] = vertex.z;
}
for (int i = 0; i < mesh.indices.size(); i++)
{
mesh.indexArray[i] = mesh.indices.get(i);
}
int colorPointer = 0;
for (Face face : mesh.faces)
{
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.x;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.y;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.z;
}
return MeshLoader.genVertexModel(mesh.vertexArray, mesh.indexArray, mesh.colorArray);
}
private static Face createFace(String materialName, String[] lineData)
{
String[] indices1 = General.replaceEmptySlashes(lineData[1]).split("/");
String[] indices2 = General.replaceEmptySlashes(lineData[2]).split("/");
String[] indices3 = General.replaceEmptySlashes(lineData[3]).split("/");
return new Face(materialName, indices1, indices2, indices3);
}
private static Vector3f createVector(String[] lineData)
{
float x = Float.parseFloat(lineData[1]);
float y = Float.parseFloat(lineData[2]);
float z = Float.parseFloat(lineData[3]);
return new Vector3f(x, y, z);
}
private static void decodeNormals(Vector3f vertex)
{
int vertexPointer = (int) vertex.x - 1;
mesh.indices.add(vertexPointer);
Normal normal = mesh.normals.get((int) vertex.z - 1);
mesh.normalArray[vertexPointer * 3] = normal.x;
mesh.normalArray[vertexPointer * 3 + 1] = normal.y;
mesh.normalArray[vertexPointer * 3 + 2] = normal.z;
}
The OBJMesh class:
public List<Vertex> vertices = new ArrayList<Vertex>();
public List<Normal> normals = new ArrayList<Normal>();
public List<Integer> indices = new ArrayList<Integer>();
public List<Face> faces = new ArrayList<Face>();
public Map<String, Material> materials = new HashMap<String, Material>();
public float[] vertexArray;
public float[] normalArray;
public float[] colorArray;
public int[] indexArray;
public void addVertex(Vertex vertex)
{
vertices.add(vertex);
}
public void addNormal(Normal normal)
{
normals.add(normal);
}
public void addMaterial(String name, Material material)
{
materials.put(name, material);
}
public void addFace(Face face)
{
faces.add(face);
}
The Face class:
public Vector3f indices1;
public Vector3f indices2;
public Vector3f indices3;
public String material;
public Face(String material, String[] v1, String[] v2, String[] v3)
{
this.material = material;
this.indices1 = new Vector3f(Float.parseFloat(v1[0]), Float.parseFloat(v1[1]), Float.parseFloat(v1[2]));
this.indices2 = new Vector3f(Float.parseFloat(v2[0]), Float.parseFloat(v2[1]), Float.parseFloat(v2[2]));
this.indices3 = new Vector3f(Float.parseFloat(v3[0]), Float.parseFloat(v3[1]), Float.parseFloat(v3[2]));
}
The Material class just contains RGB values.
If you could find something, let me know; I have been searching for weeks (No joke!). Thank you
OpenGL expects all vertex attributes to be, well, per-vertex. The way you are at the moment populating your colorArray suggests you are only doing this per-face. Change this and it should give the correct results.

ArrayList Index Error

I am trying to finish up a project that uses a graphical User Interface to search through a data Base of geysers in the US. I keep getting an error for one of my Array Lists. I would include my data for the program but is is 10,000 entries long. Any help much appreciated. This is being done in BlueJ
Error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
DataBase Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class GeyserDatabase
{
private ArrayList < Geyser > Geysers;
private ArrayList < Eruption > Eruptions;
public GeyserDatabase() {
Geysers = new ArrayList < Geyser >();
Eruptions = new ArrayList < Eruption >();
}
public void readGeyserData(String filename){
try{
File f = new File(filename);
Scanner sc = new Scanner(f);
String text;
// keep reading as long as there is more data
while(sc.hasNext()) {
text = sc.nextLine();
Eruption e = new Eruption(text);
Eruptions.add(e);
}
sc.close();
}
catch(IOException e) {
System.out.println("Failed to read the data file: " + filename);
}
createGeyserList();
}
public void addEruption (Eruption e){
Eruptions.add(e);
}
public ArrayList <Eruption> getEruptionList(){
return Eruptions;
}
public ArrayList <Geyser> getGeyserList(){
return Geysers;
}
public int getNumEruptions() {
return Eruptions.size();
}
public int getNumEruptions(int m,int d,int y) {
int count = 0;
for ( Eruption e : Eruptions) {
if (e.getMonth()==m && e.getDay()==d && e.getYear()==y) {
count++;
}
}
return count;
}
public Eruption getLateNightEruption() {
Eruption latestEruption = Eruptions.get(0);
int latestHour = latestEruption.getHour();
int latestMinute = latestEruption.getMinute();
for ( Eruption e: Eruptions ) {
if (e.getHour() > latestHour || (e.getHour()==latestHour && e.getMinute()>latestMinute)) {
latestEruption = e;
latestHour = e.getHour();
latestMinute = e.getMinute();
}
}
return latestEruption;
}
public ArrayList < Eruption > getEruptions(String geyser) {
ArrayList < Eruption > result = new ArrayList < Eruption > ();
for ( Eruption e: Eruptions ) {
if (e.getGeyserName().startsWith(geyser)) {
result.add(e);
}
}
return result;
}
private void createGeyserList(){
ArrayList<String>nameList = new ArrayList<String>();
// create temporary list of unique geyser names
for(Eruption e:Eruptions){
if(!nameList.contains(e.getGeyserName())){
nameList.add(e.getGeyserName());
}
}
// create a list of geysers
ArrayList<Geyser>geyserList = new ArrayList<Geyser>();
for(String s:nameList){
Geyser g = new Geyser(s);
// count number of eruptions for current geyser name
for(Eruption e:Eruptions){
if(e.getGeyserName().equals(g.getName()))
g.increment();
}
geyserList.add(g);
}
}
public int getMostGeysers(){
return Geysers.size();
}
public Geyser findMostActiveGeyser(){
Geyser MostEruptions = Geysers.get(0);
int mostActive = MostEruptions.getNumEruptions();
for( Geyser g : Geysers){
if(g.getNumEruptions() > mostActive){
MostEruptions =g;
mostActive = g.getNumEruptions();
}
}
return MostEruptions;
}
public Geyser findLeastActiveGeyser()
{
Geyser leastActiveGeyser = Geysers.get(0);
int leastActive = leastActiveGeyser.getNumEruptions();
for(Geyser g: Geysers)
{
if(g.getNumEruptions() < leastActive)
{
leastActiveGeyser = g;
leastActive = g.getNumEruptions();
}
}
return leastActiveGeyser;
}
public String findDayWithMostEruptions(int y){
int dayMost = 1;
int monthMost = 1;
int maxSoFar = getNumEruptions(1,1,y);
for(int m = 1; m<=12; m++){
for(int d = 1; d<=31;d++){
int eruptionsDay = getNumEruptions(m,d,y);
if(eruptionsDay>maxSoFar){
dayMost = d;
monthMost = m;
maxSoFar=eruptionsDay;
}
}
}
return monthMost + "/" + dayMost + "/" + y + "Eruptions: " + maxSoFar;
}
public static void main(String args[]){
GeyserDatabase gdb = new GeyserDatabase();
}
}
GUI Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.text.*;
/***********************************************************************
* GUI front end for a Yellowstone Geyser database
*
* #author Scott Grissom
* #version August 1, 2016
public class GeyserGUI extends JFrame implements ActionListener{
/** results box */
private JTextArea resultsArea;
private GeyserDatabase db;
/**JButtons */
private JButton findLateNightEruption;
private JButton findAmountOfEruptionsonDate;
private JButton findMaxEruptionsInYear;
private JButton findGeyserByName;
private JButton findMostActiveGeyser;
private JButton findLeastActiveGeyser;
private JButton getGeyserList;
private JTextField month;
private JTextField day;
private JTextField Year;
private JTextField geyser;
/** menu items */
private JMenuBar menus;
private JMenu fileMenu;
private JMenu reportsMenu;
private JMenuItem quitItem;
private JMenuItem openItem;
private JMenuItem countItem;
private JMenuItem geyserItem;
/*********************************************************************
Main Method
*********************************************************************/
public static void main(String arg[]){
GeyserGUI gui = new GeyserGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Yellowstone Geysers");
gui.pack();
gui.setVisible(true);
}
/*********************************************************************
Constructor - instantiates and displays all of the GUI commponents
*********************************************************************/
public GeyserGUI(){
db = new GeyserDatabase();
// FIX ME: the following line should be removed
db.readGeyserData("GeyserData.txt");
// create the Gridbag layout
setLayout(new GridBagLayout());
GridBagConstraints position = new GridBagConstraints();
// create the Results Text Area (5 x 10 cells)
resultsArea = new JTextArea(20,40);
JScrollPane scrollPane = new JScrollPane(resultsArea);
position.gridx = 0;
position.gridy = 0;
position.gridheight = 10;
position.gridwidth = 5;
position.insets = new Insets(20,20,0,0);
add(scrollPane, position);
/*******************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 0;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Month"), position);
position = new GridBagConstraints();
position.gridx = 0;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
month = new JTextField(2);
add(month, position);
/*************************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 1;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Day"), position);
position = new GridBagConstraints();
position.gridx = 1;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
day = new JTextField(2);
add(day, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 2;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Year"), position);
position = new GridBagConstraints();
position.gridx = 2;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
Year = new JTextField(4);
add(Year, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 3;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Geyser"), position);
position = new GridBagConstraints();
position.gridx = 3;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
geyser = new JTextField(12);
add(geyser, position);
/*********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 0;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Eruptions"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 1;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLateNightEruption = new JButton("Late Night Eruption");
findLateNightEruption.addActionListener(this);
add(findLateNightEruption, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 2;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findAmountOfEruptionsonDate = new JButton("# On Date");
findAmountOfEruptionsonDate.addActionListener(this);
add(findAmountOfEruptionsonDate, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 3;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMaxEruptionsInYear = new JButton("Max Eruptions in Year");
findMaxEruptionsInYear.addActionListener(this);
add(findMaxEruptionsInYear, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 4;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findGeyserByName = new JButton("By Name");
findGeyserByName.addActionListener(this);
add(findGeyserByName, position);
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 5;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Geysers"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 6;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMostActiveGeyser = new JButton("Most Active");
findMostActiveGeyser.addActionListener(this);
add(findMostActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 7;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLeastActiveGeyser = new JButton("Least Active");
findLeastActiveGeyser.addActionListener(this);
add(findLeastActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 8;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
getGeyserList = new JButton("Geyser List");
getGeyserList.addActionListener(this);
add(getGeyserList, position);
// set up File menus
setupMenus();
pack();
}
/*********************************************************************
List all entries given an ArrayList of eruptions. Include a final
line with the number of eruptions listed
#param m list of eruptions
*********************************************************************/
private void displayEruptions(ArrayList <Eruption> m){
resultsArea.setText("");
for(Eruption e: m){
resultsArea.append("\n" + e.toString());
}
resultsArea.append ("\nNumber of Geysers: " + m.size());
}
/*********************************************************************
Respond to menu selections and button clicks
#param e the button or menu item that was selected
*********************************************************************/
public void actionPerformed(ActionEvent e){
Eruption item = null;
// either open a file or warn the user
if (e.getSource() == openItem){
openFile();
}else if(db.getNumEruptions() == 0){
String errorMessage = "Did you forget to open a file?";
resultsArea.setText(errorMessage);
return;
}
// menu item - quit
else if (e.getSource() == quitItem){
System.exit(1);
}
// FIX ME: Count menu item - display number of eruptions and geysers
else if (e.getSource() == countItem){
resultsArea.setText("\nNumber of Eruptions: " + db.getNumEruptions());
}
// FIX ME: display late night eruption
else if (e.getSource() == findLateNightEruption){
resultsArea.setText("Latest Eruption\n" + db.getLateNightEruption());
}
//FIX ME: display all geyser names
else if (e.getSource() == getGeyserList){
displayEruptions(db.getEruptionList());
}
//FIX ME: max eruptions day in a year (check for year)
else if(e.getSource() == findMaxEruptionsInYear){
String aux = Year.getText();
if(aux.length() == 0){
JOptionPane.showMessageDialog(this, "Enter a Year to Search For Maax Eruptions");
}
else
{
int y = Integer.parseInt(Year.getText());
String result = db.findDayWithMostEruptions(y);
resultsArea.setText(result);
}
}
// FIX ME: list all eruptions for a geyser (check for name)
else if(e.getSource() == findGeyserByName){
String name = geyser.getText();
if(name.length() == 0){
JOptionPane.showMessageDialog(this, "Provide Name");
}
else
{
ArrayList<Eruption>result = db.getEruptions(name);
displayEruptions(result);
}
}
// FIX ME: display eruptions for a particular date
else if(e.getSource()==findAmountOfEruptionsonDate){
String aux1 = Year.getText();
String aux2 = month.getText();
String aux3 = day.getText();
if(aux1.length() == 0 || aux2.length() == 0 || aux3.length() == 0)
{
JOptionPane.showMessageDialog(this, "Provide year,month, and day");
}
else
{
int y = Integer.parseInt(Year.getText());
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int result = db.getNumEruptions(m, d, y);
resultsArea.setText("Number of Eruptions: " + result);
}
}
else if(e.getSource() == findMostActiveGeyser){
resultsArea.setText("Most active Geyser: " + db.findMostActiveGeyser());
}
else if(e.getSource() == findLeastActiveGeyser){
resultsArea.setText("Least active Geyser: " + db.findLeastActiveGeyser());
}
}
/*********************************************************************
In response to the menu selection - open a data file
*********************************************************************/
private void openFile(){
JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
int returnVal = fc.showOpenDialog(this);
// did the user select a file?
if (returnVal == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
// use the name of your lottery ticket variable
db.readGeyserData(filename);
}
}
/*********************************************************************
Create a custom gridbag constraint
*********************************************************************/
private GridBagConstraints makeConstraints(int x, int y, int h, int w, int align){
GridBagConstraints rtn = new GridBagConstraints();
rtn.gridx = x;
rtn.gridy = y;
rtn.gridheight = h;
rtn.gridwidth = w;
// set alignment: LINE_START, CENTER, LINE_END
rtn.anchor = align;
return rtn;
}
/*********************************************************************
Set up the menu items
*********************************************************************/
private void setupMenus(){
// create menu components
fileMenu = new JMenu("File");
quitItem = new JMenuItem("Quit");
openItem = new JMenuItem("Open...");
reportsMenu = new JMenu("Reports");
countItem = new JMenuItem("Counts");
// assign action listeners
quitItem.addActionListener(this);
openItem.addActionListener(this);
countItem.addActionListener(this);
// display menu components
fileMenu.add(openItem);
fileMenu.add(quitItem);
reportsMenu.add(countItem);
menus = new JMenuBar();
menus.add(fileMenu);
menus.add(reportsMenu);
setJMenuBar(menus);
}
}
Geyser Code:
import java.util.Scanner;
public class Geyser
{
String geyserName;
int count = 0;
public Geyser (String name){
geyserName = name;
}
public void increment (){
count++;
}
public String getName() {
return geyserName;
}
public int getNumEruptions() {
return count;
}
public static void main(String args[]) {
Geyser g = new Geyser("xyz");
if (g.getName().equals("xyz")) {
System.out.println("getName worked well.");
}
else {
System.out.println("getName did not work well.");
}
if (g.getNumEruptions() == 0) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
g.increment();
if (g.getNumEruptions() == 1) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
}
}
Eruption Code:
import java.util.Scanner;
public class Eruption
{
int month;
int day;
int year;
int hour;
int minute;
String geyserName;
public Eruption(String info){
Scanner scnr = new Scanner(info);
scnr.useDelimiter("/|,|:");
month = scnr.nextInt();
day = scnr.nextInt();
year = scnr.nextInt();
geyserName = scnr.next();
hour = scnr.nextInt();
minute = scnr.nextInt();
}
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public String getGeyserName(){
return geyserName;
}
public String toString( ){
String geyserString = geyserName + " " + "on" + month +"/"+ day +"/" + year + "at" + hour +":"+ minute;
return geyserString;
}
public static void main(String [] args){
Eruption e = new Eruption("1/2/2016,Old Faithful,10:46");
if (e.getMonth() == 1) {
System.out.println("getMonth worked well");
}
}
}

SVM Predict reading datatest

I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}
It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now

Categories

Resources