2015-06-08 5 views
0

У меня есть этот игровой/тестовый класс примера с птицей, и у меня есть экран входа в систему, щелкнув JButton «loggin» в этом классе экрана, я бы назвал класс flappyBird Ниже.Вызов одного класса из другого при действии

Я пытался что-то подобное, но не повезло

if(event == jButtonLogin){ 
this.dispose(); 
FlappyBird bird = new FlappyBird(); 
bird.setVisible(); 

// так как он имеет JFrame в нем я, хотя эта логика будет работать.

Если кто-то может указать мне правильный путь, пожалуйста

public class FlappyBird implements ActionListener, MouseListener, KeyListener { 

    //private static final long serialVersionUID = 1L; 

    public static FlappyBird flappyBird; //creating a static flappybird so it can be acessed within main 

    public final int WIDTH = 800, HEIGHT = 600; //scren size of the game 
    public int highScore = 0; 

    public Renderer renderer; 
    public Random rand; 

    public Rectangle bird; 

    public int ticks, yMotion, score; //bird movement 
    public boolean gameOver, started; 

    public ArrayList<Rectangle> columns; //arrrayList of Recatangles names column 


    public FlappyBird() 
    { 
     JFrame jframe = new JFrame(); //main frame of game 

     Timer timer = new Timer(20,this); 

     renderer = new Renderer(); 
     rand = new Random(); 

     jframe.setSize(WIDTH, HEIGHT); 
     jframe.setLocationRelativeTo(null); 
     jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    // jframe.setResizable(false); 
     jframe.setVisible(true); 
     jframe.addMouseListener(this); 
     jframe.addKeyListener(this); 
     jframe.setTitle("FlappyTest"); 
     jframe.add(renderer); //need to create what were rendering 

     bird = new Rectangle(50 - 10,HEIGHT/2 - 10,20,20); 
     columns = new ArrayList<Rectangle>(); 

     addColumn(true); 
     addColumn(true); 
     addColumn(true); 
     addColumn(true); 

     timer.start(); 
    } 

    public void addColumn(boolean start){ 
     int space = 350; 
     int width = 100; 
     int height = 50 + rand.nextInt(300); // height of column //minum = 50 // and talles being random at 300 

     if (start) //if first pipes 
     { 
      columns.add(new Rectangle(WIDTH + width + columns.size() * 200, HEIGHT - height - 100, width, height)); //top pipe 
      columns.add(new Rectangle(WIDTH + width + (columns.size() - 1) * 200, 0, width, HEIGHT - height - space)); // bot pipe 
     } 
     else 
     { 
      columns.add(new Rectangle(columns.get(columns.size() - 1).x + 300, HEIGHT - height - 100, width, height)); //top pipe 
      columns.add(new Rectangle(columns.get(columns.size() - 1).x, 0, width, HEIGHT - height - space)); //bot pipe 
     } 
    } 

    public void paintColumn(Graphics g, Rectangle column) //passing theses two vriable on the method 
    { 
     g.setColor(Color.green); //darker() 
     g.fillRect(column.x, column.y, column.width, column.height); 
    } 

    public void jump() 
    { 
     if(gameOver) 
     { 
      bird = new Rectangle(50 - 10,HEIGHT/2 - 10,20,20); 
      columns.clear(); 
      yMotion = 0; 
      score = 0; 

      addColumn(true); 
      addColumn(true); 
      addColumn(true); 
      addColumn(true); 

      gameOver = false; 
     } 

     if(!started) 
     { 
      started = true; 
     } 
     else if(!gameOver) 
     { 
      if (yMotion > 0) 
      { 
       yMotion = 0; 
      } 
      yMotion -=15; 
     } 

    } 

    public void actionPerformed(ActionEvent arg0) //action being performed on the timer (20,THIS) 
    { 
     int speed = 10; //columns speed 

     ticks++; //keeping count of each tick of the bird 

     if(started) 
     { 

      for(int i = 0;i < columns.size(); i++) 
      { 
       Rectangle column = columns.get(i); 

       column.x -= speed; 
      } 
      if(ticks % 2 == 0 && yMotion < 15) 
      { 
       yMotion += 2; 
      } 

      for(int i = 0;i < columns.size(); i++) // for the whole columns ArrayList 
      { 
       Rectangle column = columns.get(i); // grab column at whichever i postion 

       if(column.x + column.y < 0) // column x.y less than 0 
       { 
        columns.remove(column); //remove that current column 
        if(column.y == 0) //if the column.y == 0 when it turns 0 and you have no more starting columns 
        { 
         addColumn(false); // you add the other columns false // infinite loop 
        } 
       } 
      } 

      bird.y += yMotion; 

      for(Rectangle column : columns) 
      { // FOR EACH RECTANGLE column IN COLUMNS 
       if(column.y == 0 && bird.x + bird.width/2 > column.x + column.width/2 - 10 && bird.x + bird.width/2 < column.x + column.width/2 + 10) 
       { 
        score++; 
       } 
       if(column.intersects(bird)) 
       { //colision detection with pipes 
        gameOver = true; 
        if(bird.x < column.x) 
        { 
         bird.x = column.x - bird.width; 
        } 
        else 
        { 
         if(column.y != 0){ //if its not the top column 
          bird.y = column.y - bird.height; 
         } 
         else if(bird.y < column.height) 
         { 
          bird.y = column.height; 
         } 
        } 
       } 
      } 
      if(bird.y > HEIGHT - 100) // if the Y becomes greater then the ground or if its less than 0 
      { 
       gameOver = true; 
      } 

      if(bird.y + yMotion >= HEIGHT - 120) 
       bird.y = HEIGHT - 100 - bird.height; 
      } 
     renderer.repaint(); //EVERY 20 WE CALL REPAINT USING THE RENDERER TO UPDATE IT+ 
    } 

    public void repaint(Graphics g) //MAIN SCREEN REPAINT 
    { 
     //System.out.println("Teste"); 
     System.out.println(bird.y); 

     g.setColor(Color.BLACK);  //bground of the screen 
     g.fillRect(0,0,WIDTH,HEIGHT); 

     g.setColor(Color.BLUE);  //blue line 
     g.drawLine(0, HEIGHT-100, WIDTH, HEIGHT-100); 

     g.setColor(Color.WHITE); //White Screen 
     g.fillRect(0,HEIGHT-98,WIDTH, HEIGHT-100); 

     g.setColor(Color.WHITE);  //adding bird component 
     g.fillRect(bird.x,bird.y,bird.width,bird.height); 

     for (Rectangle column : columns) 
     { 
      paintColumn(g, column); 
     } 

     g.setColor(Color.RED); 
     g.setFont(new Font("Arial",1,100)); 

     if(!started) 
     { 
      g.drawString("Click to Start!", 75, HEIGHT/2 - 50); 
     } 

     if(gameOver) 
     { 
      g.drawString("GAME OVER!", 75, HEIGHT/2 - 50); 
      if(score > highScore){ 
       highScore = score; 
      } 
     } 
     if(!gameOver && started) 
     { 
      g.drawString(String.valueOf(score),WIDTH/2-25, 100); 
     } 

     g.setColor(Color.WHITE); 
     g.setFont(new Font("Arial",1,20)); 
     g.drawString("High Score : " + highScore, 10, 50); 
    } 

    public static void main(String[] args) 
    { 
     flappyBird = new FlappyBird(); // creating a new instance of flappybird 
    } 

    @Override 
    public void mouseClicked(MouseEvent arg0) 
    { 
     jump(); 
    } 

    @Override 
    public void mouseEntered(MouseEvent arg0) 
    { 
    } 

    @Override 
    public void mouseExited(MouseEvent arg0) 
    { 
    } 

    @Override 
    public void mousePressed(MouseEvent arg0) 
    { 
    } 

    @Override 
    public void mouseReleased(MouseEvent arg0) 
    { 
    } 

    @Override 
    public void keyPressed(KeyEvent e) 
    { 
     if(e.getKeyCode() == KeyEvent.VK_SPACE) 
     { 
      jump(); 
     } 
    } 

    @Override 
    public void keyReleased(KeyEvent arg0) 
    { 

    } 

    @Override 
    public void keyTyped(KeyEvent arg0) 
    { 

    } 

} 
+0

Рассмотрите возможность использования CardLayout для переключения между видами и некоторой моделью для совместного использования данных по мере необходимости – MadProgrammer

+0

@MadProgrammer им жаль, но не могли бы вы быть более конкретными –

+0

Рассмотрите возможность использования [CardLayout] (https://docs.oracle. com/javase/tutorial/uiswing/layout/card.html), это позволит вам изменить компонент, который отображается пользователю в пределах одного кадра. Вы можете использовать модель (объект), которая содержит свойства, которые вы хотите разделить между ними, создавая один экземпляр и передавая все необходимые ему виды, например [mvc] (http://en.m.wikipedia.org/wiki/Model% E2% 80% 93view% E2% 80% 93controller) – MadProgrammer

ответ

0

Рассмотрим глядя на менеджеров компоновки для достижения поведения государства на основе игры.

Ex: В вашем основном методе, вместо вызова нового FlappyBird(), вы вместо этого назовете что-то вроде new Login().

Будьте осторожны при создании объекта «Вход» - вы не хотите повторно изобретать колесо «открытием» и созданием второго JFrame (нежелательное решение для групповой поддержки может быть сделано путем скрытия JFrames, но это не так, что вы хотите).

Вместо этого, как намекнул MadProgrammer, менеджеры макета могут мгновенно разрешить среду обмена приложениями. Некоторое обновление выполняется для того, чтобы выполнить этот проект, но в целом он более модульный, масштабируемый (если вы хотите включить страницу опций) и больше ориентирован на ООП.

В конечном счете, из объекта «Вход» пользователь может нажать кнопку, которая меняет макет на макет воспроизведения (в котором находится весь ваш материал FlappyBird).

+0

спасибо, это помогло. если бы я мог получить некоторые примеры того, что делать с кодом и указать мне правильный путь –

Смежные вопросы