我正在为我的大学项目开发一个 java 游戏。游戏由用户界面(用于选择播放/操作方法/高分等)和游戏本身组成。UI 和游戏完全分开运行,但我无法将它们结合起来。虽然,我已经能够将两者结合起来。但是当通过 UI 访问游戏时,游戏会丢失所有事件处理(因此卡在“按空格键继续”)
检查以下代码,请帮助:
这是 Game 类(绘制并显示游戏)
package AllPanels;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class BailoutGame extends Core implements MouseListener, MouseMotionListener, KeyListener {
public static void main(String args[]) {
System.out.println("inside main");
new BailoutGame().run();
System.out.println("outside main");
}
private Image map,t1,t2,t3,t4,t5,scope,background,stopwatch,hitmarker,shot;
int x=329,y=30,escapePressCount, xShot,yShot,xMarker,yMarker,xBullet,yBullet,xTargetMedian,yTargetMedian,xMarkerMedian,yMarkerMedian;
int totalBullets=15,bulletsCounter,bulletsLeft,killCounter=1,targetShotCounter=3;
private boolean spaceBar,escapePressed,t1Shot;
String msg="",space="Press Space-Bar To Start";
@Override
public void init(){
System.out.println("inside game init");
super.init();
Window w = s.getFullScreenWindow();
w.addKeyListener(this);
w.addMouseListener(this);
w.addMouseMotionListener(this);
System.out.println("outside game init");
}
@Override
public synchronized void draw(Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Window w = s.getFullScreenWindow();
map = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/Map.png").getImage();
scope = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/Sniper Scope.png").getImage();
t1 = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/Target 1.png").getImage();
t2 = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/t2.png").getImage();
background = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/background.png").getImage();
stopwatch = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/Stopwatch.png").getImage();
hitmarker = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/HitMarker.png").getImage();
shot = new ImageIcon("/home/vivek/Projects/Java/GameRenderingTest/src/ImagesFolder/Shot.png").getImage();
g.drawImage(map, 0, 0, null);
if(t1Shot == false){
g.drawImage(t1,247,255,null);
}
g.drawImage(scope, x-1366,y-768,null);
g.drawImage(stopwatch,1366-200,25,null);
g.drawImage(hitmarker,-7,409,null);
g.setColor(w.getForeground());
g.drawString(PointSystem.displayPoints,50,50);
if(spaceBar){
g.drawString(GameTimer.time, 1250, 125);
}
if(t1Shot){
if(PointSystem.headshot){
xMarkerMedian = (62 + 124) / 2;
yMarkerMedian = (426 + 530) / 2;
}
if(PointSystem.bodyshot){
xMarkerMedian = (2 + 184) / 2;
yMarkerMedian = (530 + 766) / 2;
}
g.drawImage(shot,xMarkerMedian+xMarker,yMarkerMedian+yMarker,null);
}
if(spaceBar == false ){
g.setColor(w.getBackground());
g.fillRect(0, 0, 1366, 768);
g.setColor(w.getForeground());
g.drawString(space, 550, 500);
}
}
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mouseClicked(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
@Override
public void mouseDragged(MouseEvent e) { }
@Override
public void keyTyped(KeyEvent e) { }
@Override
public void keyReleased(KeyEvent e) { }
@Override
public void mousePressed(MouseEvent e) {
PointSystem.headshot = false;
PointSystem.bodyshot = false;
xShot = e.getX();
yShot = e.getY();
bulletsCounter++;
bulletsManager(bulletsCounter);
if((xShot >= 237) && (yShot >=247) && (xShot <= 282) && (yShot <= 298)){
target1(xShot,yShot);
}
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
stop();
if((escapePressCount % 2) != 0 && escapePressCount != 0 )
escapePressed = true;
else
escapePressed = false;
escapePressCount++;
}
if(e.getKeyCode() == KeyEvent.VK_SPACE){
GameTimer.watchStart = System.currentTimeMillis();
GameTimer.chronometer.start();
spaceBar = true;
}
}
public void target1(int xShot, int yShot) {
}
}
PointSystem.TotalPoint(targetShotCounter);
}
public void bulletsManager(int bulletsCounter) {
bulletsLeft = totalBullets - bulletsCounter;
if(bulletsLeft==0){
//GameOver Dialog.
}
}
}
核心类(完成所有后端工作)。
package AllPanels;
import java.awt.*;
public class Core {
private static final DisplayMode modes[] = {
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,24,0),
new DisplayMode(800,600,16,0),
new DisplayMode(1366,768,32,0),
new DisplayMode(1366,768,24,0),
new DisplayMode(1366,768,16,0),
};
private boolean running;
protected ScreenManager s;
public void stop(){
running = false;
}
public void run(){
System.out.println("inside run");
try{
init();
gameLoop();
}finally{
s.restoreScreen();
}
System.out.println("outside run");
}
public void init(){
System.out.println("inside Core init");
s = new ScreenManager();
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullScreen(dm);
Window w = s.getFullScreenWindow();
w.setFont(new Font("ubuntu",Font.PLAIN,20));
w.setBackground(Color.BLACK);
w.setForeground(Color.WHITE);
running = true;
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image cursorImage = toolkit.getImage("Scope.png");
Point cursorHotSpot = new Point(0,0);
Cursor customCursor = toolkit.createCustomCursor(cursorImage, cursorHotSpot, "Cursor");
w.setCursor(customCursor);
GameTimer.watchStart = System.currentTimeMillis();
System.out.println("outside Core init");
}
public void gameLoop(){
System.out.println("inside gameLoop");
long startingTime = System.currentTimeMillis();
long cumTime = startingTime;
while(running){
long timePassed = System.currentTimeMillis() - cumTime;
cumTime += timePassed;
update(timePassed);
Graphics2D g = s.getGraphics();
draw(g);
g.dispose();
s.update();
try{
Thread.sleep(20);
}
catch(Exception ex){}
}
System.out.println("outside gameLoop");
}
public void update(long timePassed) {}
public void draw(Graphics2D g) {};
}
最后一段代码:这是我需要从中访问游戏的 UI 框架中的面板
package AllPanels;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import javax.swing.SwingWorker;
public class LoadingPanel extends javax.swing.JPanel implements PropertyChangeListener {
public static Task task;
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progress = (Integer) evt.getNewValue();
loadingBar.setValue(progress);
}
}
public class Task extends SwingWorker<Void, Void> {
@Override
public Void doInBackground() {
Random random = new Random();
setProgress(0);
for(int progress=0;progress<=100;progress++) {
if(progress==2){
loadingLabel.setEnabled(true);
}
else if(progress==4){
detailsLabel.setEnabled(true);
}
else if(progress==7){
nameLabel.setText(""+MainFrame.playerName.toUpperCase());
nameLabel.setEnabled(true);
}
else if(progress==10){
if(AllPanels.MapPanel.mapNumber==1){
aoLabel.setText("BAILOUT");
}
aoLabel.setEnabled(true);
}
else if(progress==13){
missionLabel.setText("Find and Eliminate the 5 targets silently");
missionLabel.setEnabled(true);
}
else if(progress==16){
etaLabel.setText("03:00 Minutes");
etaLabel.setEnabled(true);
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Objects.png")));
}
else if(progress==31){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Shadows.png")));
}
else if(progress==46){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Sounds.png")));
}
else if(progress==61){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Targets.png")));
}
else if(progress==71){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading AI.png")));
}
else if(progress==91){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Weapons.png")));
}
else if(progress==100){
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Done.png")));
}
try {
Thread.sleep(random.nextInt(500));
} catch (InterruptedException e) {}
setProgress(Math.min(progress, 100));
}
return null;
}
public void done(){
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
startGameButton.setEnabled(true);
}
}
public LoadingPanel() {
initComponents();
}
private void initComponents() {
loadingBarCoverLabel = new javax.swing.JLabel();
loadingBar = new javax.swing.JProgressBar();
loadingStartButton = new javax.swing.JButton();
detailsLabel = new javax.swing.JLabel();
detailsCoverLabel = new javax.swing.JLabel();
nameLabel = new javax.swing.JLabel();
aoLabel = new javax.swing.JLabel();
missionLabel = new javax.swing.JLabel();
etaLabel = new javax.swing.JLabel();
loadingLabel = new javax.swing.JLabel();
startGameButton = new javax.swing.JButton();
bgLabel = new javax.swing.JLabel();
setOpaque(false);
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
loadingBarCoverLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Progress Bar Cover.png")));
add(loadingBarCoverLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 300, 820, 30));
loadingBar.setBackground(new java.awt.Color(255, 255, 255));
loadingBar.setFont(new java.awt.Font("BankGothic Md BT", 0, 24)); // NOI18N
loadingBar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 153, 255), 2));
loadingBar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
loadingBar.setStringPainted(true);
add(loadingBar, new org.netbeans.lib.awtextra.AbsoluteConstraints(25, 300, 820, 30));
loadingStartButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Start Off.png")));
loadingStartButton.setBorder(null);
loadingStartButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Start Disabled.png")));
loadingStartButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Start Pressed.png")));
loadingStartButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Start On.png")));
loadingStartButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadingStartButtonActionPerformed(evt);
}
});
add(loadingStartButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(475, 20, 125, 40));
detailsLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Details.png")));
detailsLabel.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Details disabled.png")));
detailsLabel.setEnabled(false);
add(detailsLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(15, 90, 185, 170));
detailsLabel.getAccessibleContext().setAccessibleDescription("");
detailsCoverLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Text Cover.png")));
add(detailsCoverLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 90, 800, 170));
nameLabel.setFont(new java.awt.Font("BankGothic Md BT", 0, 30));
nameLabel.setForeground(new java.awt.Color(153, 191, 211));
nameLabel.setEnabled(false);
nameLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
add(nameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 85, 800, 40));
aoLabel.setFont(new java.awt.Font("BankGothic Md BT", 0, 30));
aoLabel.setForeground(new java.awt.Color(153, 191, 211));
aoLabel.setToolTipText("");
aoLabel.setEnabled(false);
add(aoLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 130, 800, 40));
missionLabel.setFont(new java.awt.Font("BankGothic Md BT", 0, 30));
missionLabel.setForeground(new java.awt.Color(153, 191, 211));
missionLabel.setEnabled(false);
add(missionLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 175, 800, 40));
etaLabel.setFont(new java.awt.Font("BankGothic Md BT", 0, 30));
etaLabel.setForeground(new java.awt.Color(153, 191, 211));
add(etaLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 220, 800, 40));
loadingLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Buildings.png")));
loadingLabel.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Disabled.png")));
loadingLabel.setEnabled(false);
add(loadingLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(475, 260, 385, 40));
startGameButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/StartGame Off.png")));
startGameButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/StartGame Disabled.png")));
startGameButton.setEnabled(false);
startGameButton.setOpaque(false);
startGameButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/StartGame Pressed.png")));
startGameButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/StartGame On.png")));
startGameButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startGameButtonActionPerformed(evt);
}
});
add(startGameButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(860, 20, 140, 70));
bgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserInterface/Loading Panel/Loading Page.png")));
add(bgLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
}
private void loadingStartButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.remove(loadingBarCoverLabel);
MainFrame.backButton.setEnabled(false);
loadingStartButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
private void startGameButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(MapPanel.mapNumber==1){
new BailoutGame().run();
}
}
public static javax.swing.JLabel aoLabel;
private javax.swing.JLabel bgLabel;
private javax.swing.JLabel detailsCoverLabel;
public static javax.swing.JLabel detailsLabel;
public static javax.swing.JLabel etaLabel;
public static javax.swing.JProgressBar loadingBar;
public static javax.swing.JLabel loadingBarCoverLabel;
public static javax.swing.JLabel loadingLabel;
private javax.swing.JButton loadingStartButton;
public static javax.swing.JLabel missionLabel;
public static javax.swing.JLabel nameLabel;
public static javax.swing.JButton startGameButton;
}