JAVA大作業匯總1


JAVA大作業

代碼

package thegreatwork;

import javafx.application.*;
import javafx.scene.control.*;
import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.event.*;
import javafx.scene.input.*;
import javafx.scene.text.*;
import javafx.geometry.*;

import java.util.*;
import java.io.*;

/*Gui2048
 *目的:顯示分數和2048游戲,
 *顏色伴隨着分數的改變而改變*/

public class Gui2048 extends Application {

    private String outputBoard;
    private Board board;

    private static final int TILE_WIDTH = 106;
    // 這是為了未來不同位數的數字提供不同的字體以便看起來美觀?
    private static final int TEXT_SIZE_LOW = 55;
    private static final int TEXT_SIZE_MID = 45;

    private static final int TEXT_SIZE_HIGH = 35;

    // 不同的數字對應不同的顏色(改變的是方塊的顏色的填充色)
    private static final Color COLOR_EMPTY = Color.rgb(238, 228, 218, 0.35);
    private static final Color COLOR_2 = Color.rgb(238, 228, 218);
    private static final Color COLOR_4 = Color.rgb(237, 224, 200);
    private static final Color COLOR_8 = Color.rgb(242, 177, 121);
    private static final Color COLOR_16 = Color.rgb(245, 149, 99);
    private static final Color COLOR_32 = Color.rgb(246, 124, 95);
    private static final Color COLOR_64 = Color.rgb(246, 94, 59);
    private static final Color COLOR_128 = Color.rgb(237, 207, 114);
    private static final Color COLOR_256 = Color.rgb(237, 204, 97);
    private static final Color COLOR_512 = Color.rgb(237, 200, 80);
    private static final Color COLOR_1024 = Color.rgb(237, 197, 63);
    private static final Color COLOR_2048 = Color.rgb(237, 194, 46);
    private static final Color COLOR_OTHER = Color.BLACK;
    private static final Color COLOR_GAME_OVER = Color.rgb(238, 228, 218, 0.5);
    // 數字大小的差異可以用數字顏色的填充色來使其明顯
    private static final Color COLOR_VALUE_LIGHT = Color.rgb(249, 246, 242);


    private static final Color COLOR_VALUE_DARK = Color.rgb(119, 110, 101);

    private GridPane pane;

    private int tile;
    private Rectangle[][] rectangle;
    private Text[][] text;
    private Text txt0;
    private Text txtScore;
    private int[][] grid;
    private StackPane pane0;
    private double title;

    /*start
     *初始化頁面框
     */
    @Override
    public void start(Stage primaryStage) {
        // 界面的初始化
        processArgs(getParameters().getRaw().toArray(new String[0]));


        pane = new GridPane();
        pane.setAlignment(Pos.CENTER);//全部居中
        pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));//設置頁邊距
        pane.setStyle("-fx-background-color: rgb(187, 173, 160)");
        //間距的設定
        pane.setHgap(15);
        pane.setVgap(15);

        int size = board.GRID_SIZE;
        grid = new int[size][size];
        grid = board.getGrid();//把數字粘過來

        //2048
        txt0 = new Text();
        txt0.setText("2048");
        txt0.setFont(Font.font("Times New Roman", FontWeight.BOLD, 50));
        txt0.setFill(Color.BLACK);
        //分數
        txtScore = new Text();
        txtScore.setText("score: " + this.board.getScore());
        txtScore.setFont(Font.font("Times New Roman", FontWeight.BOLD, 30));
        txtScore.setFill(Color.BLACK);

        //把“2048”和分數框放到相應的位置上
        pane.add(txt0, 0, 0,2, 1);
        pane.add(txtScore, 2, 0, size - 2, 1);
        //居中
        GridPane.setHalignment(txt0, HPos.CENTER);
        GridPane.setHalignment(txtScore, HPos.CENTER);

        //初始化網格的各種屬性
        rectangle = new Rectangle[size][size];
        text = new Text[size][size];


        //把數字所在的框和數字進行初始化
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                tile = grid[row][col];//把grid里面的數字取出來

                //每一個數字所在的框
                rectangle[row][col] = new Rectangle();
                rectangle[row][col].setWidth(TILE_WIDTH);
                rectangle[row][col].setHeight(TILE_WIDTH);
                rectangle[row][col].setFill(getColor(tile));
                //把畫好的方格放到頁面框上
                pane.add(rectangle[row][col], col, row + 1);


                //初始化數字的各種
                text[row][col] = new Text();
                if (tile == 0) {
                    text[row][col].setText("");//0為空
                } else {
                    text[row][col].setText(Integer.toString(tile));
                }
                int txt = getSize(tile);//根據數字大小來決定字體大小,在最下面
                text[row][col].setFont(Font.font("Times New Roman", FontWeight.BOLD, txt));//bold:粗體
                text[row][col].setFill(getTextColor(tile));
                pane.add(text[row][col], col, row+1 );
                GridPane.setHalignment(text[row][col], HPos.CENTER);


            }
        }
//有了下面這一段才能把界面顯示出來,基本上少一行界面就不能顯示。然而每句話是什么含義我並不是非常的清楚
        pane0 = new StackPane();//堆棧面板
        pane0.getChildren().add(pane);
        Scene scene = new Scene(pane0);

        scene.setOnKeyPressed(new myKeyHandler());//接收山下左右的按鍵

        primaryStage.setTitle("Gui2048");//界面的名稱
        primaryStage.setScene(scene);
        primaryStage.show();


    }

    /*EventHandler.java
     *目的:根據玩家輸入不同的指令進行不同的操作
     *鍵盤輸入*/
    private class myKeyHandler implements EventHandler<KeyEvent> {
        public void handle(KeyEvent e) {
            if (e.getCode().equals(KeyCode.UP)) {
                if (board.canMove(Direction.UP)) {
                    board.move(Direction.UP);
                    System.out.println("Moving Up");
                    board.addRandomTile();
                }
                if (board.isGameOver()) {
                    gameOver();
                }
            } else if (e.getCode().equals(KeyCode.DOWN)) {
                if (board.canMove(Direction.DOWN)) {
                    board.move(Direction.DOWN);
                    System.out.println("Moving Down");
                    board.addRandomTile();
                }
                if (board.isGameOver()) {
                    gameOver();
                }
            } else if (e.getCode().equals(KeyCode.LEFT)) {
                if (board.canMove(Direction.LEFT)) {
                    board.move(Direction.LEFT);
                    System.out.println("Moving Left");
                    board.addRandomTile();
                }
                if (board.isGameOver()) {
                    gameOver();
                }
            } else if (e.getCode().equals(KeyCode.RIGHT)) {
                if (board.canMove(Direction.RIGHT)) {
                    board.move(Direction.RIGHT);
                    System.out.println("Moving Right");
                    board.addRandomTile();
                }
                if (board.isGameOver()) {
                    gameOver();
                }
                //按R的話頁面順時針方向旋轉90度
            } else if (e.getCode().equals(KeyCode.R)) {
                board.rotate(true);
                System.out.println("Rotate 90 degrees clockwise");
                //按S的話這個界面就會被保存下來
            } else if (e.getCode().equals(KeyCode.S)) {
                System.out.println("Saving Board to " + outputBoard);
                try {
                    board.saveBoard(outputBoard);
                } catch (IOException yingjun) {
                    System.out.println("saveBoard throw an Exception");
                }
            }

            paint();//更新畫面

        }
    }


    /*gameOver
     *用來表示這個游戲已經結束了
     */
    private void gameOver() {
        //創建一個矩形,和之前那個游戲界面一樣大小
        Rectangle rec = new Rectangle();
        rec.setFill(COLOR_GAME_OVER);
        rec.setWidth(pane.getWidth());
        rec.setHeight(pane.getHeight());

        //打印出來"gameover"
        Text over = new Text();
        over.setText("Game Over!");
        over.setFont(Font.font("Impact", FontWeight.BOLD, 50));
        over.setFill(Color.BLACK);

        //把這兩個元素添加到界面上
        pane0.getChildren().add(rec);
        pane0.getChildren().add(over);

    }


    /*paint
     * 移動之后重新畫這個頁面
     */
    private void paint() {
        int size = board.GRID_SIZE;
        grid = board.getGrid();

        txtScore.setText("score: " + this.board.getScore());

        //在移動以后重新打印16個數字框
        for (int row = 0; row < size; row++) {
            for (int col = 0; col < size; col++) {
                tile = grid[row][col];
                rectangle[row][col].setFill(getColor(tile));
                if (tile == 0) {
                    text[row][col].setText("");
                } else {
                    text[row][col].setText(Integer.toString(tile));//把數字變成字符串                }
                    int txt = getSize(tile);
                    text[row][col].setFont(Font.font("Times New Roman", FontWeight.BOLD, txt));
                    text[row][col].setFill(getTextColor(tile));

                }
            }

        }
    }


    /*getColor
     *讓矩形框有顏色
     *每一個數字對應一個背景顏色
     */
    private Color getColor(int num) {
        if (num == 0)
            return COLOR_EMPTY;
        if (num == 2)
            return COLOR_2;
        if (num == 4)
            return COLOR_4;
        if (num == 8)
            return COLOR_8;
        if (num == 16)
            return COLOR_16;
        if (num == 32)
            return COLOR_32;
        if (num == 64)
            return COLOR_64;
        if (num == 128)
            return COLOR_128;
        if (num == 256)
            return COLOR_256;
        if (num == 512)
            return COLOR_512;
        if (num == 1024)
            return COLOR_1024;
        if (num == 2048)
            return COLOR_2048;

        return COLOR_OTHER;
    }

    /*getTextColor
     *每一串文字對應一個顏色
     *數字大小決定顏色
     */
    private Color getTextColor(int num) {
        if (num < 8) {
            return COLOR_VALUE_DARK;
        } else {
            return COLOR_VALUE_LIGHT;
        }
    }

    /*getSize
     *決定一串文字的大小
     *數字大小決定字體大小
     */
    private int getSize(int num) {
        if (num < 128) {
            return TEXT_SIZE_LOW;
        } else if (num < 1024) {
            return TEXT_SIZE_MID;
        } else {
            return TEXT_SIZE_HIGH;
        }
    }


    // 用於高級用戶,命令行輸入
    private void processArgs(String[] args) {
        String inputBoard = null;
        int boardSize = 0;

        //參數必須成對出現
        if ((args.length % 2) != 0) {
            printUsage();
            System.exit(-1);
        }

        //加工參數
        for (int i = 0; i < args.length; i += 2) {
            if (args[i].equals("-i")) {
                //設置初始的界面,也可以載入其他的存檔
                inputBoard = args[i + 1];
            } else if (args[i].equals("-o")) {
                //確定保存的時候輸出文件的名字
                outputBoard = args[i + 1];
            } else if (args[i].equals("-s")) {
                //設置界面大小
                boardSize = Integer.parseInt(args[i + 1]);
            } else {   //錯誤的內容
                printUsage();
                System.exit(-1);
            }
        }

        //對應-o
        if (outputBoard == null)
            outputBoard = "2048.board";
        //對應-s
        if (boardSize < 2)
            boardSize = 4;

        //對應-i
        try {
            if (inputBoard != null)
                board = new Board(inputBoard, new Random());
            else
                board = new Board(boardSize, new Random());
        } catch (Exception e) {
            System.out.println(e.getClass().getName() +
                    " was thrown while creating a " +
                    "Board from file " + inputBoard);
            System.out.println("Either your Board(String, Random) " +
                    "Constructor is broken or the file isn't " +
                    "formated correctly");
            System.exit(-1);
        }
    }

    //幫助文檔
    private static void printUsage() {
        System.out.println("Gui2048");
        System.out.println("Usage:  Gui2048 [-i|o file ...]");
        System.out.println();
        System.out.println("  Command line arguments come in pairs of the " +
                "form: <command> <argument>");
        System.out.println();
        System.out.println("  -i [file]  -> Specifies a 2048 board that " +
                "should be loaded");
        System.out.println();
        System.out.println("  -o [file]  -> Specifies a file that should be " +
                "used to save the 2048 board");
        System.out.println("                If none specified then the " +
                "default \"2048.board\" file will be used");
        System.out.println("  -s [size]  -> Specifies the size of the 2048" +
                "board if an input file hasn't been");
        System.out.println("                specified.  If both -s and -i" +
                "are used, then the size of the board");
        System.out.println("                will be determined by the input" +
                " file. The default size is 4.");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM