자바 화면 전환 (창 전환)
조회수 1785회
제가 지금 Breakout이라고 벽돌깨기 게임을 만드는 과제를 하고 있는데 기본적인 요구사항은 다 충족시켜서 만들어 놨거든요
근데 게임 시작 전, 스타트 버튼을 누르면 게임 화면으로 전환되어서 게임이 시작될 수 있게끔 하고 싶은 욕심이 생겨서 그걸 구현해보려고 하다가 지금 막혀버린 상태입니다ㅠㅠ
클래스를 따로 만들어서 1번째 클래스가 게임 로비화면 이고 2번째 클래스가 게임 실행 화면 입니다. 이 둘을 어떻게 연결해줘야 할지 정말 막막합니다... 아직 자바 한 달 째라 뭐가 뭔지도 모르겠고... 도와주신다면 정말 감사하겠습니다. 밑에 코드 첨부합니다.
import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Main extends JFrame{
public static void main(String[] args) {
Breakout breakout = new Breakout();
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(Breakout.APPLICATION_WIDTH, Breakout.APPLICATION_HEIGHT);
frame.setTitle("게임 로비");
// 프레임을 닫았을 때 프로그램이 종료되도록 설정
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( null );
//JLabel gameTitle = new JLabel("BREAK OUT");
//gameTitle.setLocation((frame.getWidth()-gameTitle.getWidth())/2, 100);
// gameTitle.setBounds(150, 100, 100, 50);
// gameTitle.setHorizontalAlignment(JLabel.CENTER);
// frame.add(gameTitle);
JButton startButton = new JButton("Game Start");
//JButton exitButton = new JButton("Exit");
startButton.setBounds(frame.getWidth()/2 - 100, frame.getHeight()/2 - 150, 200, 100);
//exitButton.setBounds(frame.getWidth()/2 - 100, frame.getHeight()/2 - 50, 200, 100);
frame.add(startButton);
//frame.add(exitButton);
startButton.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("버튼이 클릭되었습니다.");
frame.setVisible(false);
breakout.start();
breakout.run();
}
});
}
}
/*
* File: Breakout.java
* -------------------
* This file will eventually implement the game of Breakout.
*/
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JFrame;
import acm.graphics.GLabel;
import acm.graphics.GObject;
import acm.graphics.GOval;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
import acm.util.MediaTools;
import acm.util.RandomGenerator;
public class Breakout extends GraphicsProgram {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
/** Number of bricks per row */
private static final int NBRICKS_PER_ROW = 10;
/** Number of rows of bricks */
private static final int NBRICK_ROWS = 10;
/** Separation between bricks */
private static final int BRICK_SEP = 4;
/** Width of a brick */
private static final int BRICK_WIDTH =
(WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Number of turns */
private static final int NTURNS = 3;
/** 볼이 떨어질 때의 Pause */
private static final int Pause = 5;
/* 변수 생성부 */
Color color[] = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN};
public GRect brick, paddle;
public GOval ball;
public GLabel youWin, youLose, turn, scoreLabel;
private double vx, vy;
private RandomGenerator rgen = new RandomGenerator();
public GObject collider;
int brickCount = NBRICKS_PER_ROW * NBRICK_ROWS;
int nTurns = NTURNS; int score = 0;
AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
File file, file2; AudioInputStream inGame, fail;Clip clip, clip2;
boolean leftTop, leftBottom, rightTop, rightBottom;
JFrame frame;
/* Method: run() */
/** Runs the Breakout program. */
public void run() {
playMusic();
while(true) {
play();
if(nTurns ==0 || brickCount == 0) {
break;
}
}
}
public void init(){
this.removeAll();
drawObjects();
addMouseListeners();
drawScoreLabel();
drawBall();
brickCount = NBRICKS_PER_ROW * NBRICK_ROWS;
}
public void play() {
bounceBall(); moveBall();
pause(Pause); getCollidingObject();
removeBrick();remove(scoreLabel);drawScoreLabel();
WinLose();
}
public void playMusic() {
file = new File("/Users/jeong-gahyeon/Downloads/ingame.au");
file2 = new File("/Users/jeong-gahyeon/Downloads/fail.au");
System.out.println(file2.exists());
try {
inGame = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(inGame); clip.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void drawBrick(double x, double y, int c) {
brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
brick.setFilled(true);
brick.setFillColor(color[c]);
add(brick);
}
public void drawObjects() {
paddle = new GRect(PADDLE_WIDTH,PADDLE_HEIGHT);
paddle.setFilled(true);
turn = new GLabel("Turn : " + nTurns);
add(turn, 0, HEIGHT - 100);
int c = 0;
for(int j = 0; j < NBRICK_ROWS; j++) {
double brick_startY = (BRICK_HEIGHT + BRICK_SEP) * (j+1);
if(j == 0) {
c = 0;
}else if (j % 2 == 0) {
c += 1;
}
for(int i = 0; i < NBRICKS_PER_ROW; i++) {
double brick_startX = 1.5 + (BRICK_WIDTH + BRICK_SEP) * i;
drawBrick(brick_startX, brick_startY, c);
}
}
}
public void drawScoreLabel() {
scoreLabel = new GLabel("Score : " + score);
add(scoreLabel, 0, turn.getY() - turn.getAscent() * 2);
}
/** MouseEvent : 마우스 포인터 움직임에 따라 paddle이 움직이게끔 함 */
// 만약 paddle이 벽 밖 (화면 사이즈 밖)으로 나가려고 하면,paddle의 좌표를 다시 조정해줌으로써 넘어가지 않도록 함
public void mouseMoved(MouseEvent e) {
double paddleX= e.getX()-PADDLE_WIDTH/2;
if (paddleX>(WIDTH - PADDLE_WIDTH)) {
paddleX=(WIDTH - PADDLE_WIDTH);
}else if (paddleX<0) {
paddleX=0;
}
add(paddle,paddleX,HEIGHT - PADDLE_Y_OFFSET*2);
}
public void drawBall() {
waitForClick();
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5)) vx = -vx;
vy = 3.0;
//랜덤의 x좌표에서 공이 아래로 떨어지게끔 함.
double x = rgen.nextDouble(0, (double)WIDTH);
ball = new GOval(x,HEIGHT/2,BALL_RADIUS,BALL_RADIUS);
ball.setFilled(true);
add(ball);
}
public void moveBall() {
ball.move(vx, vy);
}
public void bounceBall() {
if(ball.getY() - BALL_RADIUS <= 0 ) {
vy = -vy;
bounceClip.play();
}
//if(ball.getY() + BALL_RADIUS >= HEIGHT) vy = -vy;
if(ball.getX()+BALL_RADIUS >= WIDTH) {
vx = -vx;
bounceClip.play();
}
if(ball.getX()-BALL_RADIUS <= 0) {
vx = -vx;
bounceClip.play();
}
if(getCollidingObject() == paddle) {
//빠르게 움직이면 glued 되는 현상을 해결하기 위함.
vy = -1 * Math.abs(vy);
bounceClip.play();
}else if (getCollidingObject() == brick) {
removeBrick();
}
}
public GObject getCollidingObject() {
leftTop = false; rightTop = false; leftBottom = false; rightBottom = false;
if (getElementAt(ball.getX(), ball.getY()) != null) {
collider = getElementAt(ball.getX(), ball.getY());
leftTop = true;
}else if(getElementAt(ball.getX()+ 2 * BALL_RADIUS, ball.getY()) != null){
collider = getElementAt(ball.getX()+ 2 * BALL_RADIUS, ball.getY());
rightTop = true;
}else if(getElementAt(ball.getX(), ball.getY() + 2 * BALL_RADIUS) != null){
collider = getElementAt(ball.getX(), ball.getY()+ 2 * BALL_RADIUS);
leftBottom = true;
}else if(getElementAt(ball.getX()+ 2 * BALL_RADIUS, ball.getY() + 2 * BALL_RADIUS) != null){
collider = getElementAt(ball.getX()+ 2 * BALL_RADIUS, ball.getY() + 2 * BALL_RADIUS);
rightBottom = true;
}else {
collider = null;
}
return collider;
}
public void removeBrick() {
if (getCollidingObject() != null && getCollidingObject() != paddle && getCollidingObject() != turn && getCollidingObject() != scoreLabel) {
remove(getCollidingObject());
vy = -vy;
bounceClip.play();
brickCount--;
score += 5;
System.out.println(brickCount + " " + score);
}
}
public void WinLose() {
youWin = new GLabel("You Win!");
youLose = new GLabel("You Lose!");
GLabel finScore = new GLabel("Your Final Score : " + score);
if(brickCount == 0) {
removeAll();
add(youWin, (WIDTH - youWin.getWidth())/2, HEIGHT/2);
add(finScore,(WIDTH - finScore.getWidth())/2, youWin.getY() + youWin.getAscent()*2);
}else if(ball.getY() + BALL_RADIUS*2 >= HEIGHT) {
nTurns--;
if(nTurns > 0) {
pause(30);
this.init();
}else if (nTurns == 0) {
removeAll();
clip.stop();
try {
fail = AudioSystem.getAudioInputStream(file2);
clip2 = AudioSystem.getClip();
clip2.open(fail); clip2.start();
} catch(Exception e) {
e.printStackTrace();
}
add(youLose,(WIDTH - youLose.getWidth())/2, HEIGHT/2 - youLose.getAscent());
add(finScore,(WIDTH - finScore.getWidth())/2, youLose.getY() + youLose.getAscent()*2);
}
}
}
public void mouseClicked(MouseEvent e) {
if(nTurns == 0) {
removeAll();
playMusic();
brickCount = 100; nTurns = NTURNS;
while(true) {
play();
if(nTurns ==0 || brickCount == 0) {
break;
}
}
}
}
}
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력