대학 프로젝트 용 Java 게임을 개발 중입니다. 게임은 UI (플레이/하우투/하이 스코어 등 선택)와 게임 자체로 구성됩니다. UI와 게임은 완벽하게 분리되어 실행되지만 결합하는 데 문제가 있습니다. 비록, 나는이 두 가지를 결합 할 수있었습니다. 게임이 UI를 통해 액세스 할 때하지만, 게임은 손실 모든 이벤트 처리 (따라서 "계속 눌러 스페이스 바를"에 붙어있다)초기 UI 시작 프레임과 결합하면 게임 클래스 프레임 이벤트 처리가 손실된다
코드의 다음 조각을 검사하고 도와주세요 :
이 게임 클래스는
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) {};
}
코드의 마지막 조각이 : 내가 어디를이 내가 소스를 통해 게임을
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;
}
소스를 검색하면서 여러 부분을 찾지 못했지만 볼 수 없었습니다. 그러나 설명하는 현상은 여러 스레드를 필요로하는 응용 프로그램이 대신 단일 스레드이므로 스레드를 실행하거나 장치를 폴링하거나 일부 원본에서 입력을 읽는 것과 같은 일부 작업에서 스레드 실행이 중지되는 고전적인 동작입니다. –
정말 코어가 스레드를 확장해야하는 것처럼 보입니다. 동시성 및 멀티 스레딩에 대한이 기사를 살펴보십시오. http://docs.oracle.com/javase/tutorial/essential/concurrency/ –
Richard에게 감사드립니다. 스레딩이 그랬다. 그것을 보지 않는 것은 내 바보 같았습니다. 어쨌든 고마워!! –