검색결과 리스트
프로그래밍에 해당되는 글 84건
- 2012.12.28 [java] swing을 이용하여 baseball 게임 구현하기
글
* 학창시절 틈틈히 재미로 했던 baseball 게임을 java의 swing을 이용하여 구현해봤습니다. 서로 자신만 아는 숫자를 정한 뒤 정해진 자리수 만큼 숫자를 불러 맞힌 수의 자리나 수에 따라 strike, ball 을 체크하여 상대방의 숫자를 맞히는 게임입니다.
--------------------------------------------------------------프로그램 다운로드
1. MainClass.java
main 메서드가 있는 클래스입니다. 이 클래스의 main 메서드에서 MainScreen 클래스의 객체를 생성하면서 프로그램이 시작됩니다.
MainClass.java------------------------------------------------------------------
public class MainClass {
public static void main(String[] args) {
new MainScreen();
}
}
2. MainScreen.java
JFrame을 상속받은 클래스입니다. 주 화면을 구성하는 클래스이며 여러 동작들을 포함하고 있습니다. 또한 ActionListener와 KeyListener 인터페이스를 상속받아 이벤트 처리도 구현하였습니다.
MainScreen.java--------------------------------------------------------------
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MainScreen extends JFrame implements ActionListener, KeyListener {
// 레벨
final int EASY = 2;
final int NORMAL = 3;
final int HARD = 4;
final int HELL = 5;
int LEVEL;
// 시도 횟수
int easyNumber = 0;
int normalNumber = 0;
int hardNumber = 0;
int hellNumber = 0;
// 점수
int score = 0;
int accrueScore = 0;
// 텍스트아레아 내용
StringBuffer textArea = new StringBuffer();
int textAreaRow = 0;
// 컴퓨터와 유저의 패
StringBuffer comNumber = new StringBuffer();
StringBuffer userNumber = new StringBuffer();
// 패널 부분
JPanel panelView = new JPanel();
JPanel panelProgress = new JPanel();
JPanel panelButton = new JPanel();
// 메뉴 부분
JMenuBar menubar = new JMenuBar();
JMenu menuOption = new JMenu("Option");
JMenu menuHelp = new JMenu("Help");
JMenu mItemLevel = new JMenu("Level");
JMenuItem mItemMenual = new JMenuItem("Menual");
JMenuItem mItemMade = new JMenuItem("about program..");
JMenuItem mItemEasy = new JMenuItem("Easy");
JMenuItem mItemNormal = new JMenuItem("Normal");
JMenuItem mItemScore = new JMenuItem("Score");
JMenuItem mItemHard = new JMenuItem("Hard");
JMenuItem mItemHell = new JMenuItem("Hell");
// 텍스트필드 부분
JTextField tfieldView = new JTextField(8);
// 텍스트아레아 부분
JTextArea tAreaView = new JTextArea(10, 20);
// 스크롤 부분
JScrollPane scroll = new JScrollPane(tAreaView);
// 버튼 부분
JButton button0 = new JButton("0");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton buttonBack = new JButton("←");
JButton buttonRandom = new JButton("R");
JButton buttonGo = new JButton("Go");
JButton buttonReset = new JButton("Reset");
public MainScreen() {
super("Hi! Baseball game!");
// 기본 레벨 NORMAL 설정
LEVEL = NORMAL;
// 컴퓨터 패 생성
comNumberCreation();
// 레이아웃 설정
setLayout(new BorderLayout());
panelButton.setLayout(new GridLayout(3, 4, 5, 5));
// 색깔 설정
menubar.setBackground(Color.orange);
// 텍스트 편집 설정
tfieldView.setEditable(false);
tAreaView.setEditable(false);
// 메뉴 추가
menubar.add(menuOption);
menubar.add(menuHelp);
menuOption.add(mItemLevel);
menuOption.add(mItemScore);
menuHelp.add(mItemMenual);
menuHelp.add(mItemMade);
mItemLevel.add(mItemEasy);
mItemLevel.add(mItemNormal);
mItemLevel.add(mItemHard);
mItemLevel.add(mItemHell);
setJMenuBar(menubar);
// 패널에 컨테이너 추가
panelView.add(tfieldView);
panelView.add(buttonGo);
panelView.add(buttonReset);
panelButton.add(button7);
panelButton.add(button8);
panelButton.add(button9);
panelButton.add(buttonBack);
panelButton.add(button4);
panelButton.add(button5);
panelButton.add(button6);
panelButton.add(buttonRandom);
panelButton.add(button1);
panelButton.add(button2);
panelButton.add(button3);
panelButton.add(button0);
panelProgress.add(scroll);
// 버튼 액션리스너 추가
button0.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
buttonBack.addActionListener(this);
buttonRandom.addActionListener(this);
buttonGo.addActionListener(this);
buttonReset.addActionListener(this);
mItemEasy.addActionListener(this);
mItemNormal.addActionListener(this);
mItemHard.addActionListener(this);
mItemHell.addActionListener(this);
mItemScore.addActionListener(this);
mItemMenual.addActionListener(this);
mItemMade.addActionListener(this);
// 프레임에 패널 추가
add(panelView, "North");
add(panelProgress, "Center");
add(panelButton, "South");
// 프레임 설정
setBounds(200, 100, 250, 380);
setResizable(false);
setVisible(true);
// tfieldView 에 포커스 및 키리스너 등록
tfieldView.requestFocus();
tfieldView.addKeyListener(this);
}
// actionEvent 처리
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Easy")) {
LEVEL = EASY;
reset();
comNumberCreation();
JOptionPane.showMessageDialog(this, "Easy mode.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("Normal")) {
LEVEL = NORMAL;
reset();
comNumberCreation();
JOptionPane.showMessageDialog(this, "Normal mode.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("Hard")) {
LEVEL = HARD;
reset();
comNumberCreation();
JOptionPane.showMessageDialog(this, "Hard mode.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("Hell")) {
LEVEL = HELL;
reset();
comNumberCreation();
JOptionPane.showMessageDialog(this, "Hell mode.", "Information",
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("Score")) {
JOptionPane.showMessageDialog(this, "Your score is " + accrueScore
+ " points.\n----- try -----\nEasy: " + easyNumber + "\nNormal: " + normalNumber + "\nHard: " + hardNumber + "\nHell: " + hellNumber, "Score", JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("Menual")) {
JOptionPane
.showMessageDialog(
this,
"This is Baseball Game. To win in this game, should the 3-digit number of the computer.\n\n* Game rules are as follows\n1. Does not allow duplication of the digits.\n2. The biggest digit 0 is not allowed.\n3. Ball a strike, if the digits match the digits are wrong, but if we hit the numbers count.\n4. Numbers accurately aligning 3strike the game ends.\n\n* Difficulty is as follows.\nEasy: 2 digit\nNormal: 3 digit\nHard: 4 digit\nHell: 5 digits",
"Instruction Manual",
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("about program..")) {
JOptionPane
.showMessageDialog(
this,
"* Baseball Game *\nMade by Jo Jae-Hyeok.\nKakao Talk ID: zealot71\ne-mail: zealot71@naver.com\n^-'",
"Information", JOptionPane.INFORMATION_MESSAGE);
}
if (e.getActionCommand().equals("0")) {
if (userNumber.length() < LEVEL) {
userNumber.append("0");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("1")) {
if (userNumber.length() < LEVEL) {
userNumber.append("1");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("2")) {
if (userNumber.length() < LEVEL) {
userNumber.append("2");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("3")) {
if (userNumber.length() < LEVEL) {
userNumber.append("3");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("4")) {
if (userNumber.length() < LEVEL) {
userNumber.append("4");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("5")) {
if (userNumber.length() < LEVEL) {
userNumber.append("5");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("6")) {
if (userNumber.length() < LEVEL) {
userNumber.append("6");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("7")) {
if (userNumber.length() < LEVEL) {
userNumber.append("7");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("8")) {
if (userNumber.length() < LEVEL) {
userNumber.append("8");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("9")) {
if (userNumber.length() < LEVEL) {
userNumber.append("9");
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("←")) {
tfieldView.setText(userNumber.reverse().delete(0, 1).reverse()
.toString());
}
if (e.getActionCommand().equals("R")) {
if (userNumber.toString().isEmpty())
userNumber.append((int) (Math.random() * 9 + 1));
else {
userNumber.append((int) (Math.random() * 10));
}
tfieldView.setText(userNumber.toString());
}
if (e.getActionCommand().equals("Go")) {
if (tfieldView.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "The number is not exists.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else if (userNumber.length() != LEVEL) {
JOptionPane.showMessageDialog(this, "Entered is not a " + LEVEL + " digit number.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else if (overlap(tfieldView.getText())) {
JOptionPane.showMessageDialog(this, "The same number exists.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else {
Versus();
userNumber.delete(0, userNumber.length());
tfieldView.setText(userNumber.toString());
}
}
if (e.getActionCommand().equals("Reset")) {
reset();
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == '0') {
userNumber.append("0");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '1') {
userNumber.append("1");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '2') {
userNumber.append("2");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '3') {
userNumber.append("3");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '4') {
userNumber.append("4");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '5') {
userNumber.append("5");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '6') {
userNumber.append("6");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '7') {
userNumber.append("7");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '8') {
userNumber.append("8");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyChar() == '9') {
userNumber.append("9");
tfieldView.setText(userNumber.toString());
}
if (e.getKeyCode() == KeyEvent.VK_R) {
if (userNumber.toString().isEmpty())
userNumber.append((int) (Math.random() * 9 + 1));
else {
userNumber.append((int) (Math.random() * 10));
}
tfieldView.setText(userNumber.toString());
}
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
tfieldView.setText(userNumber.reverse().delete(0, 1).reverse()
.toString());
}
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (tfieldView.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "The number is not exists.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else if (userNumber.length() != LEVEL) {
JOptionPane.showMessageDialog(this, "Entered is not a " + LEVEL + " digit number.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else if (overlap(tfieldView.getText())) {
JOptionPane.showMessageDialog(this, "The same number exists.",
"Warning", JOptionPane.WARNING_MESSAGE);
} else {
Versus();
userNumber.delete(0, userNumber.length());
tfieldView.setText(userNumber.toString());
}
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
// 컴퓨터 패 생성 메서드
public void comNumberCreation() {
comNumber.append((int) (Math.random() * 9 + 1));
for (int i = 0; i < LEVEL - 1; i++) {
comNumber.append((int) (Math.random() * 10));
}
while (overlap(comNumber.toString())) {
comNumber.append((int) (Math.random() * 9 + 1));
for (int i = 0; i < LEVEL - 1; i++) {
comNumber.append((int) (Math.random() * 10));
}
}
}
// 중복 숫자 체크 메서드
public boolean overlap(String str) {
boolean over = false;
for (int i = 0; i < LEVEL - 1; i++) {
for (int j = i + 1; j < LEVEL; j++) {
if (str.charAt(i) == str.charAt(j)) {
over = true;
}
}
}
return over;
}
// 컴퓨터와 사용자 패 확인 메서드
public void Versus() {
int strike = 0;
int ball = 0;
for (int i = 0; i < LEVEL; i++) {
if (comNumber.charAt(i) == userNumber.charAt(i)) {
strike++;
}
}
for (int i = 0; i < LEVEL; i++) {
for (int j = 0; j < LEVEL; j++) {
if (comNumber.charAt(i) == userNumber.charAt(j)) {
ball++;
}
}
}
textAreaRow++;
textArea.append(textAreaRow + " | " + strike + " strike, "
+ (ball - strike) + " ball. --- " + tfieldView.getText() + "\n");
tAreaView.setText(textArea.toString());
if (strike == LEVEL) {
switch (LEVEL) {
case EASY:
score = 11 - textAreaRow;
easyNumber++;
break;
case NORMAL:
score = 21 - textAreaRow;
normalNumber++;
break;
case HARD:
score = 31 - textAreaRow;
hardNumber++;
break;
case HELL:
score = 41 - textAreaRow;
hellNumber++;
break;
}
JOptionPane.showMessageDialog(this, strike
+ " strike!\nGame over. You win.\n+" + score + " points.",
"Success", JOptionPane.INFORMATION_MESSAGE);
reset();
comNumberCreation();
} else if (textAreaRow == 10) {
switch (LEVEL) {
case EASY:
score = -5;
easyNumber++;
break;
case NORMAL:
score = -20;
normalNumber++;
break;
case HARD:
score = -40;
hardNumber++;
break;
case HELL:
score = -60;
hellNumber++;
break;
}
JOptionPane.showMessageDialog(this, "Game over. You lose.\nComputer Number: " + comNumber + "\n" +
+ score + " points.", "Failure",
JOptionPane.INFORMATION_MESSAGE);
reset();
comNumberCreation();
}
accrueScore += score;
score = 0;
}
public void reset() {
userNumber.delete(0, userNumber.length());
comNumber.delete(0, comNumber.length());
textArea.delete(0, textArea.length());
textAreaRow = 0;
tfieldView.setText("");
tAreaView.setText("");
}
}
프로그램 실행시 첫 화면 모습.
Option 메뉴 모습.
Help - Menual 의 프로그램 사용법.
게임에서 졌을 때 화면.
게임에서 이겼을 때 화면.
Option - Score 메뉴에서 점수 확인 모습.
'프로그래밍 > ㆍC/C++/Java' 카테고리의 다른 글
[java] jsmooth로 java의 exe(실행파일) 만들기 (0) | 2012.12.28 |
---|---|
[java] swing을 이용한 승률 계산기/측정기 (4) | 2012.12.24 |
[C] 유효한 주민번호인지 검사하기 (0) | 2012.11.18 |
[C++] static, stack, heap 배열 함수호출 요구시간 비교 (0) | 2012.11.16 |
RECENT COMMENT