Как правильно прописать старт программы - Java
Формулировка задачи:
Ребятки, помогите плиз. Есть код змейки, в интерфейс прилепил 2 кнопки. Одна с выходом, вторая с "new game",
проблем не было с первой кнопкой, прописать пару слов, а вот как прописать чтобы при нажатии начиналась новая игра, я не знаю... Помогите, пожалуйста.
И ещё... Пожаулйста, помогите написать код, чтобы когда змейка сжирала еду, была отображена табличка с очками, к примеру, за каждое сожранное яблоко - 10 очей. Спасибо всем, кто помог!
1 class
3 class
package snake1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Snake1 extends JPanel implements ActionListener {
public static final int SCALE = 32;
public static final int WIDTH = 20;
public static final int HEIGHT = 20;
public static final int SPEED = 120;
Food a = new Food((int) (Math.random() * WIDTH), (int) (Math.random() * HEIGHT));
Snake s = new Snake(10, 10, 9, 10);
Timer t = new Timer(SPEED, this);
public Snake1() { //konstruktor
t.start();
addKeyListener(new Keyboard());
setFocusable(true);
}
public void paint(Graphics g) {
g.setColor(color(255, 140, 0));
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
g.setColor(color(192, 192, 192));
for (int xx = 0; xx <= WIDTH * SCALE; xx += SCALE) {
g.drawLine(xx, 0, xx, HEIGHT * SCALE);
}
for (int yy = 0; yy <= HEIGHT * SCALE; yy += SCALE) {
g.drawLine(0, yy, WIDTH * SCALE, yy);
}
for (int d = 0; d < s.length; d++) {
g.setColor(color(20, 30, 150));
g.fillRect(s.snakeX[d] * SCALE + 1, s.snakeY[d] * SCALE + 1, SCALE - 1, SCALE - 1);
}
g.setColor(color(255, 0, 0));
g.fillRect(a.posX * SCALE + 1, a.posY * SCALE + 1, SCALE - 1, SCALE - 1);
}
public Color color(int red, int green, int blue) {
return new Color(red, green, blue);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(WIDTH * SCALE, HEIGHT * SCALE + 20);
f.setLocationRelativeTo(null);
f.add(new Snake1());
f.setVisible(true);
//TOHLE JSEM PRIDAL
addMenu(f);
}
@Override
public void actionPerformed(ActionEvent arg0) {
s.move();
if ((s.snakeX[0] == a.posX) & (s.snakeY[0] == a.posY)) {
a.setRandomPosition();
s.length++;
}
for (int k = 1; k < s.length; k++) {
if ((s.snakeX[k] == a.posX) & (s.snakeY[k] == a.posY)) {
a.setRandomPosition();
}
if ((s.snakeX[0] == a.posX) & (s.snakeY[0] == a.posY)) {
a.setRandomPosition();
s.length++;
}
}
repaint();
}
private class Keyboard extends KeyAdapter {
public void keyPressed(KeyEvent kEvt) {
int key = kEvt.getKeyCode();
if ((key == KeyEvent.VK_RIGHT) & s.direction != 2) {
s.direction = 0;
}
if ((key == KeyEvent.VK_DOWN) & s.direction != 3) {
s.direction = 1;
}
if ((key == KeyEvent.VK_LEFT) & s.direction != 0) {
s.direction = 2;
}
if ((key == KeyEvent.VK_UP) & s.direction != 1) {
s.direction = 3;
}
}
}
/**
* metoda na vytvoreni menu
* @param f JFrame
*/
static void addMenu(JFrame f) {
JMenuBar menuBar = new JMenuBar();
f.setJMenuBar(menuBar);
JMenuItem leftMenu = new JMenuItem("leftMenu");
JMenuItem rightMenu = new JMenuItem("rightMenu");
menuBar.add(leftMenu);
menuBar.add(rightMenu);
JMenuItem newAction = new JMenuItem("New");
JMenuItem cutAction = new JMenuItem("Exit");
leftMenu.add(newAction);
rightMenu.add(cutAction);
newAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("NEW");
}
});
cutAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("EXIT");
System.exit(0);
}
});
}
}package snake1;
public class Snake {
Snake1 main;
public int direction = 0;
public int length = 2;
public int snakeX[] = new int[main.WIDTH*main.HEIGHT];
public int snakeY[] = new int[main.WIDTH*main.HEIGHT];
public Snake(int x0, int y0, int x1, int y1){
snakeX[0] = x0;
snakeY[0] = y0;
snakeX[1] = x1;
snakeY[1] = y1;
}
public void move() {
for (int d = length; d > 0; d--) {
snakeX[d] = snakeX[d-1];
snakeY[d] = snakeY[d-1];
}
if(direction == 0) snakeX[0]++;
if(direction == 1) snakeY[0]++;
if(direction == 2) snakeX[0]--;
if(direction == 3) snakeY[0]--;
for (int d = length-1; d > 0; d--) {
if((snakeX[0] == snakeX[d]) & (snakeY[0] == snakeY[d])) length = d-2;
}
if(snakeX[0] > main.WIDTH) snakeX[0] = 0;
if(snakeX[0] < 0) snakeX[0] = main.WIDTH-1;
if(snakeY[0] > main.HEIGHT) snakeY[0] = 0;
if(snakeY[0] < 0) snakeY[0] = main.HEIGHT-1;
if (length < 2) length = 2;
}
}package snake1;
public class Food {
Snake1 main;
public int posX;
public int posY;
public Food(int startX, int startY){ // konstruktor
posX = startX;
posY = startY;
}
public void setRandomPosition() {
posX = (int) (Math.random()*main.WIDTH);
posY = (int) (Math.random()*main.WIDTH);
}
}Решение задачи: «Как правильно прописать старт программы»
textual
Листинг программы
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GamePanel extends JPanel implements ActionListener {
private final int SCALE = 32;
private final int WIDTH = 20;
private final int HEIGHT = 20;
public static final int SPEED = 300;
public static final int ALL_SCALES = 16*20;
private final int snakeX[] = new int[ALL_SCALES];
private final int snakeY[] = new int[ALL_SCALES];
private final int RAND_POS = 15;
private int len, a_x, a_y;
private static int direction = 0;
private boolean game_over = false;
public static Timer t;
static JPanel contentPane;
public GamePanel() {
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setBackground(color(255, 140, 0));
initGame();
}
private void initGame() {
len = 2;
for (int z = 0; z < len; z++) {
snakeX[z] = 50 - z * SCALE;
snakeY[z] = 50;
}
locateFood();
t = new Timer(SPEED, this);
}
private void locateFood(){
int r = (int) (Math.random() * RAND_POS);
a_x = r * RAND_POS;
r = (int) (Math.random() * RAND_POS);
a_y = r * RAND_POS;
}
@Override
public void actionPerformed(ActionEvent e) {
if(!game_over){
move();
checkFood();
}
repaint();
}
private void checkFood(){
if(a_x >= snakeX[0] && a_x <= snakeX[0]+SCALE && a_y >= snakeY[0] && a_y <= snakeY[0]+SCALE ){
len++;
locateFood();
}
if(game_over) t.stop();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(!game_over){
g.setColor(color(255, 0, 0));
g.fillRect(a_x, a_y, SCALE-1, SCALE-1);
for(int z = 0; z < len; z++){
g.setColor(color(20, 30, 150));
g.fillRect(snakeX[z], snakeY[z], SCALE-1, SCALE-1);
}
} else{
gameOver(g);
}
}
private void gameOver(Graphics g){
String msg = "Victory!";
Font font = new Font("Helvetica", Font.BOLD, 20);
g.setColor(Color.white);
g.setFont(font);
g.drawString(msg, 150, 150);
}
private void move(){
if(len >= 10) game_over = true;
for(int z = len; z > 0; z--){
snakeX[z] = snakeX[z-1];
snakeY[z] = snakeY[z-1];
}
if(direction == 2){
snakeX[0] -= SCALE;
}
if(direction == 1){
snakeY[0] += SCALE;
}
if(direction == 0){
snakeX[0] += SCALE;
}
if(direction == 3){
snakeY[0] -= SCALE;
}
}
public static void main(String[] args) {
createGUI();
}
private static void createGUI(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setLocation(50, 10);
f.setTitle("Snake");
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(600, 600));
contentPane.setFocusable(true);
contentPane.addKeyListener(new KeyBoard());
f.setContentPane(contentPane);
f.pack();
f.setVisible(true);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Game");
menuBar.add(menu);
JMenuItem menuNew = new JMenuItem("New Game");
JMenuItem menuExit = new JMenuItem("Exit");
menu.add(menuNew);
menu.add(menuExit);
f.setJMenuBar(menuBar);
menuExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menuNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();;
contentPane.add(new GamePanel());
contentPane.revalidate();
contentPane.repaint();
t.start();
}
});
}
public Color color(int red, int green, int blue) {
return new Color(red, green, blue);
}
private static class KeyBoard implements KeyListener{
@Override
public void keyTyped(KeyEvent e) { }
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT && direction != 0 ){ direction = 2; }
if(key == KeyEvent.VK_RIGHT && direction != 2){ direction = 0; }
if(key == KeyEvent.VK_DOWN && direction != 3){ direction = 1; }
if(key == KeyEvent.VK_UP && direction != 1){ direction = 3; }
}
@Override
public void keyReleased(KeyEvent e) { }
}
}