I have problem with threads.. When I turn my game then GUI appears, I set difficulty and game begins, everything look fine but... When I close GUI then game closes too, other problem is with turning game from game class. When I try run it with main class of game that wont work just throws execeptions. So my question is how to set game class to run it other thread, so it won't turn off when i turn off my window? And why it only works with GUI and how to fix it?
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
import javazoom.jl.player.Player;
public class Snake implements ActionListener, KeyListener {
public static Snake snake;
public JFrame jframe;
public RenderPanel renderPanel;
public Timer timer = new Timer(20, this);
public LinkedList<Point> snakeParts = new LinkedList<Point>();
public static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, SCALE = 10;
public static final int WIDTH = 800, HEIGHT = WIDTH / 12 * 9;
public int direction = DOWN, score, tailLength = 10, time;
public double ticks = 0;
public static double dificullty = 3;
public Point head, cherry;
public Random random;
public boolean over = false, paused;
public Dimension dim;
// private boolean running = false;
public Snake() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Snake");
jframe.setVisible(true);
jframe.setPreferredSize(new Dimension(WIDTH, HEIGHT));
jframe.setMaximumSize(new Dimension(WIDTH, HEIGHT));
jframe.setMinimumSize(new Dimension(WIDTH, HEIGHT));
jframe.setLayout(new GridLayout());
jframe.setResizable(false);
jframe.setLocationRelativeTo(null);
jframe.add(renderPanel = new RenderPanel());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.addKeyListener(this);
startGame();
}
public void startGame() {
over = false;
paused = false;
time = 0;
score = 0;
tailLength = 0;
ticks = 0;
direction = DOWN;
head = new Point(0, -1);
random = new Random();
snakeParts.clear();
cherry = new Point(random.nextInt(70), random.nextInt(55));
timer.start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
renderPanel.repaint();
ticks++;
if (ticks % dificullty == 0 && head != null && !over && !paused) {
time++;
snakeParts.add(new Point(head.x, head.y));
if (direction == UP)
if (head.y - 1 >= 0 && noTailAt(head.x, head.y - 1))
head = new Point(head.x, head.y - 1);
else
over = true;
if (direction == DOWN)
if (head.y + 1 < Snake.HEIGHT / SCALE - 2
&& noTailAt(head.x, head.y + 1))
head = new Point(head.x, head.y + 1);
else
over = true;
if (direction == LEFT)
if (head.x - 1 >= 0 && noTailAt(head.x - 1, head.y))
head = new Point(head.x - 1, head.y);
else
over = true;
if (direction == RIGHT)
if (head.x + 1 < Snake.WIDTH / SCALE
&& noTailAt(head.x + 1, head.y))
head = new Point(head.x + 1, head.y);
else
over = true;
if (snakeParts.size() > tailLength)
snakeParts.remove(0);
if (cherry != null) {
if (head.equals(cherry)) {
score += 10;
tailLength++;
cherry.setLocation(random.nextInt(75), random.nextInt(60));
}
}
}
}
public boolean noTailAt(int x, int y) {
for (Point point : snakeParts) {
if (point.equals(new Point(x, y))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
new Snake();
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_A || key == KeyEvent.VK_LEFT)
&& direction != RIGHT)
direction = LEFT;
if ((key == KeyEvent.VK_D || key == KeyEvent.VK_RIGHT)
&& direction != LEFT)
direction = RIGHT;
if ((key == KeyEvent.VK_W || key == KeyEvent.VK_UP)
&& direction != DOWN)
direction = UP;
if ((key == KeyEvent.VK_S || key == KeyEvent.VK_DOWN)
&& direction != UP)
direction = DOWN;
if (key == KeyEvent.VK_SPACE)
if (over)
startGame();
else
paused = !paused;
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
//render panel class
public class RenderPanel extends JPanel {
public static Color green = new Color(1666073);
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(green);
g.fillRect(0, 0, Snake.WIDTH, Snake.HEIGHT);
Snake snake = Snake.snake;
g.setColor(Color.BLUE);
for (Point point : snake.snakeParts) {
g.fillRect(point.x * Snake.SCALE, point.y * Snake.SCALE ,
Snake.SCALE, Snake.SCALE);
}
g.fillRect(snake.head.x * Snake.SCALE, snake.head.y * Snake.SCALE,
Snake.SCALE, Snake.SCALE);
g.setColor(Color.RED);
g.fillRect(snake.cherry.x * Snake.SCALE, snake.cherry.y * Snake.SCALE,
Snake.SCALE, Snake.SCALE);
String string = "Score: " + snake.score + ", Length: "
+ snake.tailLength + ", Time: " + snake.time / 20;
g.setColor(Color.white);
g.drawString(string, (int) (getWidth() / 2 - string.length() * 2.5f),
10);
string = "Game Over!";
if (snake.over)
g.drawString(string,
(int) (getWidth() / 2 - string.length() * 2.5f),
(int) snake.dim.getHeight() / 4);
string = "Paused!";
if (snake.paused && !snake.over)
g.drawString(string,
(int) (getWidth() / 2 - string.length() * 2.5f),
(int) snake.dim.getHeight() / 4);
string = "To move press W, A, S, D.";
g.setColor(Color.white);
g.drawString(string, (int) (getWidth() / 2 - string.length() * 2.5f),
30);
string = "To pause/restart press space.";
g.setColor(Color.white);
g.drawString(string, (int) (getWidth() / 2 - string.length() * 2.5f),
50);
}
}
//GUI
public class Window extends RenderPanel{
private JFrame frame;
private String filename = "Kalimba.mp3";
private Player player;
private FileInputStream fis;
private BufferedInputStream bis;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
window.Play();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Play() {
try {
fis = new FileInputStream(filename);
bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
new Thread() {
public void run() {
try {
player.play();
}
catch (Exception e) { System.out.println(e); }
}
}.start();
}
/**
* Create the application.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 400, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JButton btnNewButton = new JButton("Start Game!");
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnNewButton.setBounds(101, 24, 194, 32);
btnNewButton.setVerticalAlignment(SwingConstants.TOP);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Snake.snake = new Snake();
}
});
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("EXIT");
btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnNewButton_1.setBounds(101, 117, 194, 32);
frame.getContentPane().add(btnNewButton_1);
final JComboBox<?> comboBox = new JComboBox();
comboBox.setMaximumRowCount(3);
comboBox.setModel(new DefaultComboBoxModel(new String[] { "Easy",
"Medium", "Hard" }));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 16));
comboBox.setBounds(101, 67, 194, 39);
frame.getContentPane().add(comboBox);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if(comboBox.getSelectedIndex() == 0)
Snake.dificullty = 3;
if(comboBox.getSelectedIndex() == 1)
Snake.dificullty = 1.5;
if(comboBox.getSelectedIndex() == 2)
Snake.dificullty = 1;
}
});
}
}