[英]Java Maze Game Player Movement Not Working
對於我的編碼項目,我必須編寫一個迷宮游戲。 但是,我目前在 JFrame 中顯示了一個迷宮,玩家用紅色方塊表示,結束標記是藍色方塊,牆壁是黑色方塊。 但是無論我嘗試做什么,我似乎都無法讓玩家在迷宮中移動。
package practiceMazeGame;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MazeBoard extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
// Creates the maze board using a 2D array.
public static int[][] maze =
{{3,1,1,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,1,1,0,0,0,1,1,1,0,1,1,1,1},
{1,0,1,1,0,1,0,1,0,1,0,0,0,0,0},
{0,0,0,1,0,1,0,1,0,1,1,1,1,1,1},
{0,1,1,0,0,1,0,1,0,1,0,0,0,0,1},
{0,1,1,0,1,1,0,1,0,1,0,1,1,0,1},
{0,0,0,0,1,1,0,1,0,1,0,1,0,0,1},
{0,1,1,1,1,1,0,1,0,1,0,1,0,1,1},
{0,0,0,1,1,1,0,1,0,1,0,1,0,0,0},
{0,1,0,1,0,0,0,1,0,1,0,1,1,1,0},
{0,1,1,1,0,1,1,1,0,1,0,0,0,1,0},
{0,0,0,1,0,0,0,0,0,1,0,1,1,1,0},
{0,1,1,1,1,1,1,1,0,1,0,1,1,1,0},
{0,0,0,0,0,0,0,1,0,0,0,0,0,1,2},
};
//Sets the output screen information
public MazeBoard() {
// Displays 'Maze Game' in the title bar of the window.
setTitle("Maze Game");
// Sets the size of the output screen.
setSize(640, 640);
// Sets the location of where the window will appear.
setLocationRelativeTo(null);
// Stops the program when the window is closed.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PlayerMovement mySquare = new PlayerMovement(640, 640);
add(mySquare);
}
// The function in charge of the graphics of the maze.
public void paint(Graphics g) {
super.paint(g);
g.translate(50, 50);
// They go through every section of the 2D array to make sure all the blocks are covered.
for (int row =0; row <maze.length; row++) {
for (int col = 0; col < maze[0].length; col++) {
Color color;
switch(maze[row][col]){
// Sets the colour of the blocks of the array with a one to be black.
case 1 : color = Color.black; break;
// Sets the colour villain to be red.
case 2 : color = Color.red; break;
// Sets the colour of the player to be blue.
case 3 : color = Color.blue; break;
// Sets the colour of the rest of the maze to be white.
default : color = Color.white; break;
}
// Sets the screen the for behind the maze.
g.setColor(color);
// Fills the rectangle needed for the maze with the colours previously decided.
g.fillRect(30 * col, 30 * row, 30, 30);
// Sets the colour of the gird lines for the maze.
g.setColor(Color.black);
// Draws the rectangle needed for the maze.
g.drawRect(30 * col, 30 * row, 30, 30);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Outputs the maze.
MazeBoard view = new MazeBoard();
view.setVisible(true);
}
});
}
}
我真的很感激一些幫助,謝謝。
給你的建議:
將玩家的位置存儲在您的數組中(作為 3 值)是糟糕的設計:您應該僅將其用於迷宮設計並將玩家的位置存儲在單獨的變量中
您的着色開關語句可以首先檢查繪制的位置是否與玩家的位置匹配,以確定藍色方塊應該在哪里。 或者你可以在你畫完迷宮后畫那個正方形
移動應該非常簡單:只需在檢查新位置沒有牆后更改玩家的位置變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.