我只是想为大学制作一个游戏,这是一个玩家用键盘导航以穿过迷宫的球。我唯一坚持的是我的背景是迷宫的图像,当我添加“球”时,它会重新绘制背景(默认颜色,无图像),当我注释掉油漆和油漆组件时,迷宫背景又回来了,但当然没有球。
我是 java 新手,我已经搜索过这个,但看不到我已经拥有的代码的好灵魂。它是 setOpaque 吗?isOpaque?....不透明甚至是正确的方向吗?
一旦我得到这个......我完全理解使用碰撞检测来检测与迷宫“墙”的碰撞
试图弄清楚这一点,刚接触java,会让一个成年人哭泣。
main.java
public class Main{
public static void main (String[] args){
//System.out.println("Start of the Game");
GameFrame game1 = new GameFrame();
}
JavaGame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.io.File;
import java.io.IOException;
public class GameFrame extends JFrame{
private int frameWidth = 240, frameHeight =315;
int x, y;
private Image dbImage;
private Graphics dbg;
//Below is the constructor
public GameFrame(){
super("OperationMaze!");
addKeyListener(new AL());
setResizable(false);
//setTitle("OperationMaze!2");
//setSize(250, 302);
setSize(frameWidth, frameHeight); //Set height and width
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Because of opening file, there needs to be a try catch just incase there is an error opening.
//Plus java won't let you unless you try catch.
try{
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Documents and Settings/brando/My Documents/NetBeansProjects/GameFrame/src/maze.jpg")))));
} catch (IOException e) {
e.printStackTrace();
}
//Show the frame
setVisible(true);
//setOpaque(false);
y = 35;
x = 15;
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 15, 15);
//g.setOpaque(false);
repaint();
}
// private void setOpaque(boolean b) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT) {
if(x <= 5)
x = 5;
else
x += -5;
}
if(keyCode == e.VK_RIGHT) {
if(x >= 230)
x = 230;
else
x += +5;
}
if(keyCode == e.VK_UP) {
if(y <= 23)
y=23;
else
y += -5;
}
if(keyCode == e.VK_DOWN) {
if(y >= 277)
y = 277;
else
y += +5;
}
}
}
}