开始一个新游戏(运行带有新游戏按钮的程序)JavaFX

时间:2016-01-11 18:50:42

标签: javafx

我写了一个蛇游戏,当它击中它的尾巴时,它将是Game Over并发出警报。我在新游戏的警报阶段设置了一个按钮,我想先用它来再次运行我的鳕鱼。有什么方法或什么......

这是我的警报课

class alart {
    public static void Game_over_alart(int dom) {

        dom = (dom - 9) * 10  ;
        Label sdom = new Label(Integer.toString(dom));

        Stage window = new Stage();
        window.setTitle("Game_Over");
        Label gameOver = new Label("Game Over");
        Label scor = new Label("SCORE : ");
        Label best = new Label("BEST : ");
        Text newgame = new Text("NEW GAME");

        HBox hbox1 = new HBox(2, scor , sdom );
        HBox hbox2 = new HBox(2, best);

        VBox vbox = new VBox(2, hbox1, hbox2);

        gameOver.setStyle(""
                + "-fx-alignment: top;"
                + "-fx-font-size: 40px;"
                + "-fx-font-style: italic;"
                + "-fx-font-weight: bold;"
                + "-fx-font-family: fantasy;"
                + "-fx-text-fill: lightgrey  ;");
        // + "-fx-background-color: gray");


        DropShadow d = new DropShadow(5, Color.BLACK);

        ScaleTransition st=new ScaleTransition(Duration.millis(100),newgame);
        st.setToX(1.1);
        st.setToY(1.1);
        st.setFromX(1);
        st.setFromY(1);
        //st.setAutoReverse(true);
       // st.setCycleCount(Animation.INDEFINITE);



        gameOver.setEffect(d);
        BorderPane b = new BorderPane();
        b.setTop(gameOver);
        b.setCenter(vbox);
        b.setBottom(newgame);
        gameOver.setAlignment(Pos.CENTER);
        Scene s = new Scene(b, 400, 200);
        window.setScene(s);
        window.show();
        window.setResizable(false);

        newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {


            @Override
            public void handle(MouseEvent event) {

            }

        });

        newgame.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event1) {
                st.play();

            }
        });

        newgame.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event1) {
                st.setFromX(1.1);
                st.setFromY(1.1);
                st.setToX(1);
                st.setToY(1);

            }
        });
    }
}

这是我的整个代码

/**
 * Created by Nadia on 12/31/2015.
 */

import javafx.animation.Animation;
import javafx.animation.AnimationTimer;
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import sun.jvm.hotspot.debugger.cdbg.Sym;

import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;

public class Main_Snake extends Application{

    Canvas canvas = new Canvas(399, 599);
    Rectangle round = new Rectangle(0 ,0 , 400 , 600 );

    B_Part snake = new Snake();
    B_Part apple = new Apple();
    B_Part mane = new Mane();

    @Override
    public void start(Stage primaryStage) throws Exception {

        round.setStroke(Color.BLACK);
        round.setFill(Color.WHITE);
        StackPane ss = new StackPane();
        ss.getChildren().addAll(round, canvas);

        BorderPane b = new BorderPane();
        b.setBottom(ss);
        Scene scene = new Scene(b, 410, 700);
        primaryStage.setScene(scene);
        primaryStage.setTitle ( "Snake" );
        primaryStage.show();
        primaryStage.setResizable(false);

        play();



    }


    public void play() {
        AnimationTimer timer = new AnimationTimer() {

            private long lastUpdate = 0;

            @Override
            public void handle(long now) {

                if (now - lastUpdate >= 20_000_000) {  // payin avordane sor@

                    GraphicsContext gc = canvas.getGraphicsContext2D();
                    gc.setFill(Color.WHITE);
                    gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());




                        try {
                            for ( int i = 0 ; i < 5 ; i++)
                                mane.Move(canvas.getScene());

                        } catch (Game_Over_Exception e) {

                        }finally {
                            mane.Drow(canvas);
                        }


                    try {
                        apple.Move(canvas.getScene());

                    }catch (Exception e) {

                    }finally {
                        apple.Drow(canvas);

                    }

                    try {
                        snake.Move(canvas.getScene());

                    } catch (Game_Over_Exception e) {
                        stop();
                        alart.Game_over_alart(snake.X.size());

                    }finally {
                        snake.Drow(canvas); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast

                    }

                    lastUpdate = now; // sor@

                }

            }
        };
                timer.start();
        }


   }


abstract class B_Part {


    boolean goNorth = true, goSouth = false, goWest = false, goEast = false; ///////////////////////////////////////////////////////

    static int GM = 0 ;

    int Mx , My ;
    static ArrayList<Integer> Mane_x = new ArrayList<>();
    static ArrayList<Integer> Mane_y = new ArrayList<>();

    static int x, y ; // marbut be apple
    static int j = 0;
    //    int gm_ov = 0; // vase game over shodan
    static ArrayList<Integer> X = new ArrayList<>();
    static ArrayList<Integer> Y = new ArrayList<>();

    static int Domx1 =400 , Domy1 =390  ;
    static int Domx2 =400,  Domy2 =400  ;

    abstract public void Drow(Canvas canvas);

    abstract public void Move(Scene scene)throws Game_Over_Exception;

    void Point() {
        if (X.get(0) == x && Y.get(0) == y)
            j = 0;
    }
    void Game_Over() {


        for (int i = 1 ; i < X.size() ; i ++) { // inke mokhtasate sare mar tu mokhtasate tanesh hast ya na
            if (X.get(0).equals(X.get(i)) && Y.get(0).equals(Y.get(i))) {
                GM = 1;
            }
        }


        for (int i = 0 ; i < Mane_x.size() ; i ++) { // inke mokhtasate sare mar be mane hast ya na
            if (X.get(0).equals(Mane_x.get(i)) && Y.get(0).equals(Mane_y.get(i))) {
                GM = 1;

            }
        }


    }

}
class Apple extends B_Part {


    @Override
     public void Move(Scene scene) {
        if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
            do {
                x = (int) ( Math.random() * 390 + 1 );
                y = (int) ( Math.random() * 590 + 1 );
            } while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*
inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
                        y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
                        haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide
*/


            j = 1;
        }
    }

    @Override
     public void Drow(Canvas canvas) {

        DropShadow dd = new DropShadow(20,Color.RED);

        GraphicsContext a = canvas.getGraphicsContext2D();
        a.setFill(Color.RED);
        a.setEffect(dd);
        a.fillRect( x , y , 9 ,9);
        a.setEffect(null);
     }

 }

class Snake extends B_Part {


    Snake() {   //cunstructor

        X.add(400);
        Y.add(300);

        X.add(400);
        Y.add(310);

        X.add(400);
        Y.add(320);

        X.add(400);
        Y.add(330);


        X.add(400);
        Y.add(340);

        X.add(400);
        Y.add(350);

        X.add(400);
        Y.add(360);

        X.add(400);
        Y.add(370);

        X.add(400);
        Y.add(380);

    }

    @Override
    public void Drow(Canvas canvas) {
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(Color.BLACK);

        // keshidane mar (body yeki ezafe tar az adade morabaA mide)
        for (int i = X.size() - 1; i >= 0; i--) {
            gc.fillRect(X.get(i), Y.get(i), 9, 9);
            gc.setStroke(Color.WHITE);
        }

        }

    @Override
    public void Move(Scene scene) throws Game_Over_Exception {


        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent small) {
                switch (small.getText()) {
                    case "W":
                        if (!goSouth) {
                            goNorth = true;
                            goSouth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case "w":
                        if (!goSouth) {
                            goNorth = true;
                            goSouth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case "S":
                        if (!goNorth) {
                            goSouth = true;
                            goNorth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case "s":
                        if (!goNorth) {
                            goSouth = true;
                            goNorth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case "A":
                        if (!goEast) {
                            goWest = true;
                            goEast = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;
                    case "a":
                        if (!goEast) {
                            goWest = true;
                            goEast = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;
                    case "D":
                        if (!goWest) {
                            goEast = true;
                            goWest = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;
                    case "d":
                        if (!goWest) {
                            goEast = true;
                            goWest = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;

                }
            }
        });
     /*  scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent e) {
                switch (e.getCode()) {
                    case UP:
                        if (!goSouth) {
                            goNorth = true;
                            goSouth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case DOWN:
                        if (!goNorth) {
                            goSouth = true;
                            goNorth = false;
                            goWest = false;
                            goEast = false;
                        }
                        break;
                    case LEFT:
                        if (!goEast) {
                            goWest = true;
                            goEast = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;
                    case RIGHT:
                        if (!goWest) {
                            goEast = true;
                            goWest = false;
                            goSouth = false;
                            goNorth = false;
                        }
                        break;

                }
            }
        });
*/

         Domx1 = X.get(X.size() - 1);
         Domy1 = Y.get(Y.size() - 1);

        for (int z = X.size() - 1; z > 0; z--) {
            X.remove(z);
            X.add(z, X.get(z - 1));
            Y.remove(z);
            Y.add(z, Y.get(z - 1));

        }

        if (goNorth) {
            Y.add(0, Y.get(0) - 10);
            Y.remove(1);

        }
        if (goSouth) {
            Y.add(0, Y.get(0) + 10);
            Y.remove(1);

        }
        if (goEast) {
            X.add(0, X.get(0) + 10);
            X.remove(1);

        }
        if (goWest) {
            X.add(0, X.get(0) - 10);
            X.remove(1);

        }

        Point();        // emtiaz gerefte
        if (j == 0) {
            X.add(Domx1);
            Y.add(Domy1);
            X.add(Domx2);
            Y.add(Domy2);
            Domx2 = Domx1;
            Domy2 = Domy1;

            System.out.println();
            System.out.println("size : "+Mane_x.size() );

            System.out.print("  clear :  " );

            Mane_x.clear();
            Mane_y.clear();

            System.out.println("size : "+Mane_x.size() );

        }

        Game_Over();
        if ( GM == 1 ) {
                throw new Game_Over_Exception("Game Over");
            }

        if (X.get(0) > 390) {
            X.remove(0);
            X.add(0, 0);
        }
        if (X.get(0) < 0) {
            X.remove(0);
            X.add(0, 400);
        }
        if (Y.get(0) > 590) {
            Y.remove(0);
            Y.add(0, 0);
        }
        if (Y.get(0) < 0) {
            Y.remove(0);
            Y.add(0, 600);
        }
    }
}

class Mane extends B_Part{


    @Override
    public void Drow(Canvas canvas) {
        GraphicsContext gc = canvas.getGraphicsContext2D();
        for ( int i = 0 ; i < Mane_x.size() ; i++) {
                gc.setFill(Color.GRAY);
                gc.fillRect(Mane_x.get(i), Mane_y.get(i), 9, 9);
            }
            //System.out.println(Mane_x.get(i)+"   "+Mane_y.get(i));}
        }


    @Override
    public void Move(Scene scene) {
        if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
            do {
                Mx = (int) (Math.random() * 390 + 1);
                My = (int) (Math.random() * 590 + 1);

            } while (Mx == x && My == y ||
                     Mane_x.indexOf(Mx) != -1 && Mane_y.get(Mane_x.indexOf(Mx)) == My ||
                     X.indexOf(Mx) != -1 && Y.get(X.indexOf(Mx)) == My ||
                     Mx % 10 != 0 || My % 10 != 0
                   /*  Mx == X.get(0) + 10 && My == Y.get(0)  ||  // yeki joloye saresh nayofte   (vaghti rast mire)
                     Mx == X.get(0) - 10 && My == Y.get(0)  ||   // ( vaghti chap mire)
                     Mx == X.get(0)  && My == Y.get(0) + 10 || // yek ta jolo tar az saresh nayofte vaghtti payi
                     Mx == X.get(0)  && My == Y.get(0) - 10*/);   // vaghti bala
//sharte chek kardane in ke har maneye random rooye mar ya maneye ghablia nayofte ( sib hamintor )
            Mane_x.add(Mx);
            Mane_y.add(My);
        }
    }
}

 class Game_Over_Exception extends Exception{
     public Game_Over_Exception (String s){
         super(s);
     }


 }

1 个答案:

答案 0 :(得分:0)

将重启方法移交给警报处理程序。你可以直接或通过界面,例如。 G:

public interface GameManager {
    public void restart();
}

您的主类必须实现该接口:

public class Main_Snake extends Application implements GameManager {

    public void restart() {
      // TODO: reset playfield & restart game
    }

    public void play() {
                ...
                try {
                    snake.Move(canvas.getScene());

                } catch (Game_Over_Exception e) {
                    stop();
                    alart.Game_over_alart(snake.X.size(), Main_Snake.this);

                }
                ...
    }
}

在您的alart类中,您调用该方法:

class alart {
    public static void Game_over_alart(int dom, GameManager gameManager) {
        ...
        newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {


            @Override
            public void handle(MouseEvent event) {

                // TODO: close dialog

                // restart game
                gameManager.restart();

            }

        });
        ...
    }  
}
相关问题