I never seen Java act this way, but it seems to be bypassing my loop.
I'm using slick2D with 2 classes.
Graphic
public class graphic extends BasicGame {
public static int POS1 = 100;
public static int POS2 = 100;
public static String text = "f";
public static boolean test = false;
public static boolean test3 = false;
public static boolean w = false;
public static boolean m = false;
public static boolean left = false;
public static boolean right = false;
Boolean test2 = false;
public graphic(String gamename){
super(gamename);
}
public void start() {
try{
AppGameContainer appgc;
appgc = new AppGameContainer(new graphic("ProjectES"));
appgc.setDisplayMode(1300, 800, false); //width, height
appgc.start();
}catch(SlickException es){
System.out.println("MAJOR ERROR, GRAPICH.START");
}
}
#Override
public void render(GameContainer gc, Graphics g) throws SlickException {
g.setColor(Color.white);
g.drawString("Y " + Main.year + " M" + Main.month + " W" + Main.week, 550, 10);
if(Objectsellinghandler.test == true){
//g.fillRect(100, 100, 500, 150); //window
Image popup1 = new Image("res/Window.png");
popup1.draw(370,250);
g.setColor(Color.orange);
g.drawString(Main.text0, 380,260);
g.drawString(Main.text1, 380,280);
g.drawString(Main.text2, 380,300);
g.drawString(Main.text3, 380,320);
g.drawString(Main.text4, 380,340);
}
if(Objectsellinghandler.test == true){
//g.fillRect(100, 100, 500, 150); //window
Image popup1 = new Image("res/Window.png");
popup1.draw(370,250);
g.setColor(Color.orange);
g.drawString(Main.text0, 380,260);
g.drawString(Main.text1, 380,280);
g.drawString(Main.text2, 380,300);
g.drawString(Main.text3, 380,320);
g.drawString(Main.text4, 380,340);
}
//Image img = new Image("res/image.png");
//img.draw(POS1,POS2);
}
#Override
public void init(GameContainer arg0) throws SlickException {
// TODO Auto-generated method stub
}
#Override
public void update(GameContainer gc, int arg1) throws SlickException {
Input input = gc.getInput();
Main.MainInput = input.toString();
if(test2 == false){
Main.MainInput = "w";
text = "gg";
System.out.println("gg");
test2 = true;
Main.year++;
Thread time = new Thread(new Time());
time.start();
}
if(input.isKeyDown(Input.KEY_W) && test3 == false){
test3 = true;
test = true;
w = true;
m = false;
left = false;
right = false;
System.out.println("test1111");
Thread t1 = new Thread(new Objectsellinghandler());
t1.start();
}
if(input.isKeyDown(Input.KEY_M)){
m = true;
w = false;
left = false;
right = false;
System.out.println("RLLY");
}
if(input.isKeyDown(Input.KEY_LEFT)){
left = true;
m = false;
w = false;
right = false;
}
if(input.isKeyDown(Input.KEY_RIGHT)){
right = true;
left = false;
m = false;
w = false;
}
Main.MainInput = "";
//if(){
//test2 = true;
// System.out.println("WHY ARE YOU RUNNING");
//Thread t1 = new Thread(new Objectsellinghandler());
//t1.run();
// }
}
}
Objectsellinghandler.
public class Objectsellinghandler implements Runnable{
public static boolean test = false;
public void beginning(){
}
#Override
public void run() {
System.out.println("gg");
test = true;
if(Main.rep < 1){
Main.text0 = "You are starting out with $" + Main.money + " from a bank loan, to";
Main.text1 = "start you off, were buying 100 units of a red lamp";
Main.text2 = "from china, for $2600.";
Main.text4 = "Press M to continue.";
int I = 0;
while(graphic.m = false){
System.out.println(I);
}
System.out.println(graphic.m);
graphic.m = false;
Main.MainInput = "";
/*Main.text0 = "";
Main.text1 = "";
Main.text2 = "";
Main.text4 = "";
*/
Main.money = Main.money - RedlampI.priceperhundred;
RedlampI.amount = RedlampI.amount + 100;
Main.text0 = "The items have been purchased, it will be here in one";
Main.text1 = "month";
double month = Main.month;
double monthcomparing = month + 1;
System.out.println("month " + Main.month + "monthcomparing " + monthcomparing + "Main month" + Main.month);
while(monthcomparing != month){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
month = Main.month;
}
System.out.println("month " + Main.month + "monthcomparing " + monthcomparing + "Main month" + Main.month);
Main.text0 = "The shipment is here, shipping costed $200";
Main.money = Main.money - 200;
Main.text1 = "You have " + Main.money + " money left, A good price is $35 but you";
Main.text2 = "can choose any price between $20 and $40 for this item.";
Main.text4 = "Press M to continue.";
I = 0;
while(graphic.m = false){
System.out.println(Main.MainInput);
}
graphic.m = false;
Main.MainInput = "";
test = false;
Main.text0 = "";
Main.text1 = "";
Main.text2 = "";
Main.text4 = "";
RedlampI objectselling1 = new RedlampI();
objectselling1.onsale();
Thread.currentThread().interrupt();
return;
}
}
}
The loop waiting for boolean "m" is instatly bypassed! Even though it is false.
And this code seems to be running before the thread is created!
double month = Main.month;
double monthcomparing = month + 1;
monthcomparing + "Main month" + Main.month);
This multithreading is being really, really strange and its been over 24 hours and I can't figure out why.
while(graphic.m = false), in addition to being a spinlock and thus a Bad Thing, is an assignment to graphic.m and will always be immediately false.
Using while(graphic.m == false) will make your code "correct" but still Bad. Using while(!graphic.m) is a little less bad, but using a better waiting strategy is the Right Thing.
Update: Now that I think about it, this should be producing an "unreachable code" error. A compile-time constant of false is only permitted in if, not while.
Related
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.
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();
}
}
I am trying to record my vocals and then merge them with an audio file together using OPENSL ES Library. I found this GitHub sample called Native-Audio. It merges the two audios. But the background audio file is playing much faster than the actual rate in the final output.
Please use headphones to notice the difference.
Samples Links: Before and After
Also, it uses the files from the assets folder only. How can I manually select MP3 files from file manager?
private void mixAudio(){
try {
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) ||
!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED))
{
// Show rationale and request permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
1000);
}
else {
buttonMix.setEnabled(false);
buttonMix.setText("MIXING....");
textViewMixPath.setText("");
buttonPlay.setEnabled(false);
buttonRecord.setEnabled(false);
buttonStart.setEnabled(false);
listView.setEnabled(false);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
//File file = new File(baseDir + "/mix.wav");
String path = Environment.getExternalStorageDirectory().getPath() + "/VocalRecorder";
File fileParent = new File(path);
if (!fileParent.exists()){
fileParent.mkdir();
}
final File file = new File(fileParent.getPath() + "/mix.wav");
//String author = getApplicationContext().getPackageName() + ".provider";
//Uri videoUri = FileProvider.get(this, author, mediaFile);
//final File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + "mix.wav");
//MediaMuxer muxer = new MediaMuxer(file.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
String beat = beats[selectedBeat];
//beat = beat.replace(".wav", ".mp3");
AssetFileDescriptor afd = getAssets().openFd(beat);
MediaCodec codec = null;
//ByteBuffer outputBuffer;
//short[] data; // data for the AudioTrack playback
//int outputBufferIndex = -1;
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
final long duration = Long.parseLong(durationStr);
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
// right now I am pointing to a URI but I have tested that both will
// play the media file using MediaPlayer
int sampleRate = 0;
int numChannels = 0;
int dstIndex = -1;
int numTracks = extractor.getTrackCount(); //This says 1
for (int i = 0; i < numTracks; ++i) { // so this will just run once
MediaFormat format = extractor.getTrackFormat(i); // getting info so it looks good so far
String mime = format.getString(MediaFormat.KEY_MIME); // "audio/mpeg"
if (mime.startsWith("audio/")) {
extractor.selectTrack(i);
codec = MediaCodec.createDecoderByType(mime);
codec.configure(format, null, null, 0);
//format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AMR_NB);
//dstIndex = muxer.addTrack(format);
//writer.setFrameRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
//writer.setSamplesPerFrame(format.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
//writer.setBitsPerSample(16);
sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
break;
}
}
// Calculate the number of frames required for specified duration
long numFrames = (long)(duration * sampleRate/1000);
// Create a wav file with the name specified as the first argument
WavFile wavFile = WavFile.newWavFile(file, numChannels, numFrames, 16, sampleRate);
if (codec == null) {
throw new IllegalArgumentException("No decoder for file format");
}
//ByteBuffer[] inputBuffers = decoder.getInputBuffers();
//ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
/*
Boolean eosReceived = false;
while (!eosReceived) {
int inIndex = decoder.dequeueInputBuffer(1000);
if (inIndex >= 0) {
ByteBuffer buffer = decoder.getInputBuffer(inIndex);
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize < 0) {
// We shouldn't stop the playback at this point, just pass the EOS
// flag to mDecoder, we will get it again from the
// dequeueOutputBuffer
Log.d("DecodeActivity", "InputBuffer BUFFER_FLAG_END_OF_STREAM");
decoder.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
} else {
decoder.queueInputBuffer(inIndex, 0, sampleSize, extractor.getSampleTime(), 0);
extractor.advance();
}
int outIndex = decoder.dequeueOutputBuffer(info, 1000);
switch (outIndex) {
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
Log.d("DecodeActivity", "INFO_OUTPUT_BUFFERS_CHANGED");
//outputBuffers = decoder.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
MediaFormat format = decoder.getOutputFormat();
Log.d("DecodeActivity", "New format " + format);
//audioTrack.setPlaybackRate(format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
Log.d("DecodeActivity", "dequeueOutputBuffer timed out!");
break;
default:
ByteBuffer outBuffer = decoder.getOutputBuffer(outIndex);
Log.v("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + outBuffer);
final byte[] chunk = new byte[info.size];
outBuffer.get(chunk); // Read the buffer all at once
outBuffer.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
//audioTrack.write(chunk, info.offset, info.offset + info.size); // AudioTrack write data
decoder.releaseOutputBuffer(outIndex, false);
break;
}
// All decoded frames have been rendered, we can stop playing now
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d("DecodeActivity", "OutputBuffer BUFFER_FLAG_END_OF_STREAM");
break;
}
}
}
*/
short recordedData[] = recordedData();
int recordMixStartIndex = -1;
//muxer.start();
codec.start();
Boolean sawInputEOS = false;
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
MediaCodec.BufferInfo infoMux = new MediaCodec.BufferInfo();
int count = 0;
while (!sawInputEOS) {
int inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_US);
Log.i(LOG_TAG, "inputBufIndex : " + inputBufIndex);
if (inputBufIndex >= 0) {
ByteBuffer dstBuf = codec.getInputBuffer(inputBufIndex);
int sampleSize = extractor.readSampleData(dstBuf, 0);
Log.i(LOG_TAG, "sampleSize : " + sampleSize);
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.i(LOG_TAG, "Saw input end of stream!");
sawInputEOS = true;
sampleSize = 0;
} else {
presentationTimeUs = extractor.getSampleTime();
Log.i(LOG_TAG, "presentationTimeUs " + presentationTimeUs);
}
codec.queueInputBuffer(inputBufIndex,
0, //offset
sampleSize,
presentationTimeUs,
sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!sawInputEOS) {
Log.i(LOG_TAG, "extractor.advance()");
extractor.advance();
}
}
final int res = codec.dequeueOutputBuffer(info, TIMEOUT_US);
if (res >= 0) {
int outputBufIndex = res;
ByteBuffer buf = codec.getOutputBuffer(outputBufIndex);
//final byte[] chunk = new byte[info.size];
//buf.get(chunk); // Read the buffer all at once
short[] shortArray = new short[info.size/2];
buf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortArray);
buf.clear(); // ** MUST DO!!! OTHERWISE THE NEXT TIME YOU GET THIS SAME BUFFER BAD THINGS WILL HAPPEN
if (shortArray.length > 0) {
//mAudioTrack.write(chunk, 0, chunk.length);
//infoMux.presentationTimeUs = info.presentationTimeUs;
//infoMux.flags = info.flags;
//muxer.writeSampleData(dstIndex, ByteBuffer.wrap(chunk),
// infoMux);
long []longData = new long[shortArray.length];
// Merge data with vocal
// Calculate the time
final long bufferTimer = info.presentationTimeUs/1000;
int vocalCount = 0;
for (int i = 0; i < shortArray.length; i ++) {
//writer.writeShortLittle(shortArray[i]);
long offsetTime = i*1000/(sampleRate*2); // 2 channels
Boolean mixed = false;
if ((offsetTime + bufferTimer > recordStartTime) && (offsetTime + bufferTimer <= recordStopTime + 500)){
if (recordMixStartIndex == -1){
recordMixStartIndex = 0;
}
if (recordMixStartIndex < recordedData.length){
//Log.i("TAG", "############ mix record data: " + recordMixStartIndex);
longData[i] = TPMixSamples((int)(recordedData[recordMixStartIndex]), (int)shortArray[i]/3);
if (vocalCount >= 3) {
recordMixStartIndex++;
vocalCount = 0;
}
else{
vocalCount ++;
}
mixed = true;
}
}
else {
// All done, set sawInputEOS to stop mixing
if (bufferTimer > recordStopTime + 500){
sawInputEOS = true;
}
}
if (!mixed) {
longData[i] = shortArray[i];
}
}
Log.i("TAG", "############ write frames: " + longData.length/2);
wavFile.writeFrames(longData, longData.length/2);
count ++;
if (count % 5 == 0){
runOnUiThread(new Runnable() {
#Override
public void run() {
long percent = bufferTimer*100/duration;
buttonMix.setText("MIXING..." + percent + "%");
}
});
}
}
codec.releaseOutputBuffer(outputBufIndex, false /* render */);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
sawInputEOS = true;
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
//codecOutputBuffers = codec.getOutputBuffers();
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
final MediaFormat oformat = codec.getOutputFormat();
Log.d(LOG_TAG, "Output format has changed to " + oformat);
//mAudioTrack.setPlaybackRate(oformat.getInteger(MediaFormat.KEY_SAMPLE_RATE));
}
}
// Close the wavFile
wavFile.close();
// muxer.stop();
// muxer.release();
codec.stop();
codec.release();
extractor.release();
runOnUiThread(new Runnable() {
#Override
public void run() {
buttonMix.setText("MIX DONE");
buttonPlay.setEnabled(true);
buttonRecord.setEnabled(true);
textViewMixPath.setText(file.getPath());
buttonStart.setEnabled(true);
listView.setEnabled(true);
}
});
}
catch (Exception e){
}
}
});
thread.start();
}
}
catch (Exception e){
e.printStackTrace();
}
}
private final int INT16_MIN = - 32768;
private final int INT16_MAX = 32767;
private long TPMixSamples(int a, int b) {
if (a > INT16_MAX) {a = INT16_MAX;}
if (a < INT16_MIN) {a = INT16_MIN;}
return
// If both samples are negative, mixed signal must have an amplitude between the lesser of A and B, and the minimum permissible negative amplitude
a < 0 && b < 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MIN) :
// If both samples are positive, mixed signal must have an amplitude between the greater of A and B, and the maximum permissible positive amplitude
( a > 0 && b > 0 ?
((int)a + (int)b) - (((int)a * (int)b)/INT16_MAX)
// If samples are on opposite sides of the 0-crossing, mixed signal should reflect that samples cancel each other out somewhat
:
a + b);
}
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native void createBufferQueueAudioPlayer(int sampleRate, int samplesPerBuf);
/////
public static native boolean createAssetAudioPlayer(AssetManager assetManager, String filename);
// true == PLAYING, false == PAUSED
public static native void setPlayingAssetAudioPlayer(boolean isPlaying);
public static native int getDurationAssetAudioPlayer();
public static native int getCurrentPositionAssetAudioPlayer();
//////
public static native boolean createUriAudioPlayer(String uri);
public static native void setPlayingUriAudioPlayer(boolean isPlaying);
public static native void setLoopingUriAudioPlayer(boolean isLooping);
public static native void setChannelMuteUriAudioPlayer(int chan, boolean mute);
public static native void setChannelSoloUriAudioPlayer(int chan, boolean solo);
public static native int getNumChannelsUriAudioPlayer();
public static native void setVolumeUriAudioPlayer(int millibel);
public static native void setMuteUriAudioPlayer(boolean mute);
public static native void enableStereoPositionUriAudioPlayer(boolean enable);
public static native void setStereoPositionUriAudioPlayer(int permille);
public static native boolean selectClip(int which, int count);
public static native void stopClip();
public static native boolean enableReverb(boolean enabled);
public static native boolean createAudioRecorder();
public static native void startRecording();
public static native void stopRecording();
public static native void pauseRecording();
public static native void resumeRecording();
public static native short[] recordedData();
public static native double recordedDuration();
public static native void shutdown();
/** Load jni .so on initialization */
static {
System.loadLibrary("native-audio-jni");
}
I've recently stumbled upon Tiny GP (A Genetic Programming program), and I found it pretty useful, so I decided to change all System.out.println() in the program to a write to text file method.
Problem: In the text file, for some reason, only says "PROBLEM SOLVED", instead of printing out generations and other things that it is supposed to (see code).
Tiny GP modified class file:
package main;
/*
* Program: tiny_gp.java
*
* Author: Riccardo Poli (email: rpoli#essex.ac.uk)
*
* Modified by Preston Tang
*/
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class tiny_gp {
String Name;
double[] fitness;
char[][] pop;
static Random rd = new Random();
static final int ADD = 110,
SUB = 111,
MUL = 112,
DIV = 113,
FSET_START = ADD,
FSET_END = DIV;
static double[] x = new double[FSET_START];
static double minrandom, maxrandom;
static char[] program;
static int PC;
static int varnumber, fitnesscases, randomnumber;
static double fbestpop = 0.0, favgpop = 0.0;
static long seed;
static double avg_len;
static final int MAX_LEN = 10000,
POPSIZE = 100000,
DEPTH = 5,
GENERATIONS = 100,
TSIZE = 2;
public static final double PMUT_PER_NODE = 0.05,
CROSSOVER_PROB = 0.9;
public static double[][] targets;
public double run() {
/* Interpreter */
char primitive = program[PC++];
if (primitive < FSET_START) {
return (x[primitive]);
}
switch (primitive) {
case ADD:
return (run() + run());
case SUB:
return (run() - run());
case MUL:
return (run() * run());
case DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001) {
return (num);
} else {
return (num / den);
}
}
}
return (0.0); // should never get here
}
public int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_START) {
return (++buffercount);
}
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
public void setup_fitness(String fname) {
try {
int i, j;
String line;
BufferedReader in
= new BufferedReader(
new FileReader(fname));
line = in.readLine();
StringTokenizer tokens = new StringTokenizer(line);
varnumber = Integer.parseInt(tokens.nextToken().trim());
randomnumber = Integer.parseInt(tokens.nextToken().trim());
minrandom = Double.parseDouble(tokens.nextToken().trim());
maxrandom = Double.parseDouble(tokens.nextToken().trim());
fitnesscases = Integer.parseInt(tokens.nextToken().trim());
targets = new double[fitnesscases][varnumber + 1];
if (varnumber + randomnumber >= FSET_START) {
Write("too many variables and constants");
//System.out.println("too many variables and constants");
}
for (i = 0; i < fitnesscases; i++) {
line = in.readLine();
tokens = new StringTokenizer(line);
for (j = 0; j <= varnumber; j++) {
targets[i][j] = Double.parseDouble(tokens.nextToken().trim());
}
}
in.close();
} catch (FileNotFoundException e) {
Write("ERROR: Please provide a data file");
//System.out.println("ERROR: Please provide a data file");
System.exit(0);
} catch (Exception e) {
Write("ERROR: Incorrect data format");
//System.out.println("ERROR: Incorrect data format");
System.exit(0);
}
}
public double fitness_function(char[] Prog) {
int i = 0, len;
double result, fit = 0.0;
len = traverse(Prog, 0);
for (i = 0; i < fitnesscases; i++) {
for (int j = 0; j < varnumber; j++) {
x[j] = targets[i][j];
}
program = Prog;
PC = 0;
result = run();
fit += Math.abs(result - targets[i][varnumber]);
}
return (-fit);
}
public int grow(char[] buffer, int pos, int max, int depth) {
char prim = (char) rd.nextInt(2);
int one_child;
if (pos >= max) {
return (-1);
}
if (pos == 0) {
prim = 1;
}
if (prim == 0 || depth == 0) {
prim = (char) rd.nextInt(varnumber + randomnumber);
buffer[pos] = prim;
return (pos + 1);
} else {
prim = (char) (rd.nextInt(FSET_END - FSET_START + 1) + FSET_START);
switch (prim) {
case ADD:
case SUB:
case MUL:
case DIV:
buffer[pos] = prim;
one_child = grow(buffer, pos + 1, max, depth - 1);
if (one_child < 0) {
return (-1);
}
return (grow(buffer, one_child, max, depth - 1));
}
}
return (0); // should never get here
}
public int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_START) {
if (buffer[buffercounter] < varnumber) {
Write("X" + (buffer[buffercounter] + 1) + " ");
//System.out.print("X" + (buffer[buffercounter] + 1) + " ");
} else {
WriteDouble(x[buffer[buffercounter]]);
//System.out.print(x[buffer[buffercounter]]);
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" + ");
//System.out.print(" + ");
break;
case SUB:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" - ");
//System.out.print(" - ");
break;
case MUL:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" * ");
//System.out.print(" * ");
break;
case DIV:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" / ");
//System.out.print(" / ");
break;
}
a2 = print_indiv(buffer, a1);
Write(")");
//System.out.print(")");
return (a2);
}
public static char[] buffer = new char[MAX_LEN];
public char[] create_random_indiv(int depth) {
char[] ind;
int len;
len = grow(buffer, 0, MAX_LEN, depth);
while (len < 0) {
len = grow(buffer, 0, MAX_LEN, depth);
}
ind = new char[len];
System.arraycopy(buffer, 0, ind, 0, len);
return (ind);
}
public char[][] create_random_pop(int n, int depth, double[] fitness) {
char[][] pop = new char[n][];
int i;
for (i = 0; i < n; i++) {
pop[i] = create_random_indiv(depth);
fitness[i] = fitness_function(pop[i]);
}
return (pop);
}
public void stats(double[] fitness, char[][] pop, int gen) {
int i, best = rd.nextInt(POPSIZE);
int node_count = 0;
fbestpop = fitness[best];
favgpop = 0.0;
for (i = 0; i < POPSIZE; i++) {
node_count += traverse(pop[i], 0);
favgpop += fitness[i];
if (fitness[i] > fbestpop) {
best = i;
fbestpop = fitness[i];
}
}
avg_len = (double) node_count / POPSIZE;
favgpop /= POPSIZE;
Write("Generation=" + gen + " Avg Fitness=" + (-favgpop)
+ " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
+ "\nBest Individual: ");
//System.out.print("Generation=" + gen + " Avg Fitness=" + (-favgpop)
// + " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
// + "\nBest Individual: ");
print_indiv(pop[best], 0);
Write("\n");
//System.out.print("\n");
//System.out.flush();
}
public int tournament(double[] fitness, int tsize) {
int best = rd.nextInt(POPSIZE), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] > fbest) {
fbest = fitness[competitor];
best = competitor;
}
}
return (best);
}
public int negative_tournament(double[] fitness, int tsize) {
int worst = rd.nextInt(POPSIZE), i, competitor;
double fworst = 1e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] < fworst) {
fworst = fitness[competitor];
worst = competitor;
}
}
return (worst);
}
public char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = rd.nextInt(len1);
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start,
(xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring,
xo1start + (xo2end - xo2start),
(len1 - xo1end));
return (offspring);
}
public char[] mutation(char[] parent, double pmut) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < FSET_START) {
parentcopy[mutsite] = (char) rd.nextInt(varnumber + randomnumber);
} else {
switch (parentcopy[mutsite]) {
case ADD:
case SUB:
case MUL:
case DIV:
parentcopy[mutsite]
= (char) (rd.nextInt(FSET_END - FSET_START + 1)
+ FSET_START);
}
}
}
}
return (parentcopy);
}
public void print_parms() {
Write("-- TINY GP (Java version) --\n");
//System.out.print("-- TINY GP (Java version) --\n");
Write("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
+ "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
+ "\nCROSSOVER_PROB=" + CROSSOVER_PROB
+ "\nPMUT_PER_NODE=" + PMUT_PER_NODE
+ "\nMIN_RANDOM=" + minrandom
+ "\nMAX_RANDOM=" + maxrandom
+ "\nGENERATIONS=" + GENERATIONS
+ "\nTSIZE=" + TSIZE
+ "\n----------------------------------\n");
// System.out.print("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
// + "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
// + "\nCROSSOVER_PROB=" + CROSSOVER_PROB
// + "\nPMUT_PER_NODE=" + PMUT_PER_NODE
// + "\nMIN_RANDOM=" + minrandom
// + "\nMAX_RANDOM=" + maxrandom
// + "\nGENERATIONS=" + GENERATIONS
// + "\nTSIZE=" + TSIZE
// + "\n----------------------------------\n");
}
public tiny_gp(String fname, long s) {
fitness = new double[POPSIZE];
seed = s;
if (seed >= 0) {
rd.setSeed(seed);
}
setup_fitness(fname);
for (int i = 0; i < FSET_START; i++) {
x[i] = (maxrandom - minrandom) * rd.nextDouble() + minrandom;
}
pop = create_random_pop(POPSIZE, DEPTH, fitness);
}
public void evolve() {
int gen = 0, indivs, offspring, parent1, parent2, parent;
double newfit;
char[] newind;
print_parms();
stats(fitness, pop, 0);
for (gen = 1; gen < GENERATIONS; gen++) {
if (fbestpop > -1e-5) {
Write("PROBLEM SOLVED\n");
//System.out.print("PROBLEM SOLVED\n");
System.exit(0);
}
for (indivs = 0; indivs < POPSIZE; indivs++) {
if (rd.nextDouble() < CROSSOVER_PROB) {
parent1 = tournament(fitness, TSIZE);
parent2 = tournament(fitness, TSIZE);
newind = crossover(pop[parent1], pop[parent2]);
} else {
parent = tournament(fitness, TSIZE);
newind = mutation(pop[parent], PMUT_PER_NODE);
}
newfit = fitness_function(newind);
offspring = negative_tournament(fitness, TSIZE);
pop[offspring] = newind;
fitness[offspring] = newfit;
}
stats(fitness, pop, gen);
}
Write("PROBLEM *NOT* SOLVED\n");
//System.out.print("PROBLEM *NOT* SOLVED\n");
System.exit(1);
}
public void Write(String context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(context);
}
} catch (IOException ex) {
}
}
public void WriteDouble(double context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String ncontext = Double.toString(context);
bufferedWriter.write(ncontext);
}
} catch (IOException ex) {
}
}
};
The Functions Mapper file that uses the Tiny GP class file:
package function_mapper;
import javax.swing.JOptionPane;
import main.*;
public class Function_Mapper {
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog(null, "File Name", "Input Dialog", JOptionPane.INFORMATION_MESSAGE);
long s = -1;
if (args.length == 2) {
s = Integer.valueOf(args[0]).intValue();
fname = args[1];
}
if (args.length == 1) {
fname = args[0];
}
tiny_gp gp = new tiny_gp(fname, s);
gp.evolve();
}
}
Much help appreciated, thanks!
The Write method overwrites the contents of the file on each invocation. There are two ways to fix this.
An easier one, is to append file, instead of overwriting it. It could be achieved by passing append argument to the FileWriter (I simplified code a little bit along the way).
// true on the next line means "append"
try (Writer writer = new FileWriter("GP.txt", true)) {
writer.write(Double.toString(context));
} catch (IOException ex) {
}
A harder, but much fore efficient one is to openwriter in the constructor, use it in Write method, and close in the specially introduced close method of the tiny_gp.
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