728x90
명품 JAVA Programming 5장 Open Challenge
이 게임에는 Bear의 Fish 객체가 등장하며, 이들은 10행 20열의 격자판에서 각각 정해진 규칙에 의해 움직인다. Bear는 사용자의 키에 의해 왼쪽(a 키), 아래(s 키), 위(d 키), 오른쪽(f 키)으로 한 칸씩 움직이고, Fish는 다섯 번 중 세 번은 제자리에 있고, 나머지 두 번은 4가지 방향 중 랜덤하게 한 칸씩 움직인다. 게임은 Bear가 Fish를 먹으면(Fish의 위치로 이동) 성공으로 끝난다. 다음은 각 객체의 이동을 정의하는 move()와 각 객체의 모양을 정의하는 getShape()을 추상 메소드로 가진 추상 클래스 GameObject이다. GameObject를 상속받아 Bear과 Fish 클래스를 작성하라. 그리고 전체적인 게임을 진행하는 Game 클래스와 main() 함수를 작성하고 프로그램을 완성하라. 키가 입력될 떄마다 Bear와 Fish 객체의 move()가 순서대로 호출된다. 게임이 진행되는 과정은 다음 그림과 같으며, 게임의 종료 조건에 일치하면 게임을 종료한다.
abstract class GameObject { // 추상 클래스
protected int distance; // 한 번 이동 거리
protected int x, y; // 현재 위치(화면 맵 상의 위치)
public GameObject(int startX, int startY, int distance) { // 초기 위치와 이동 거리 설정
this.x = startX;
this.y = startY;
this.distance = distance;
}
public int getX() { return x; }
public int getY() { return y; }
public boolean collide(GameObject p) { // 이 객체가 객체 p와 충돌했으면 true 리턴
if(this.x == p.getX() && this.y == p.getY())
return true;
else
return false;
}
public abstract void move(); // 이동한 후의 새로운 위치로 x, y 변경
public abstract char getShape(); // 객체의 모양을 나타내는 문자 리턴
}
되게 잘 짠 코드는 아니라 생각하지만 성공:)
처음엔 distance를 이해 못해서 distance를 이용하지 않고 해결했지만
만약 참고하시는 분들은 Bear나 Fish를 이동시킬 때(move()함수에서 switch문),
저는 x++을 썼지만 x+=distance 를 써서 한 칸씩 이동시킨다는 느낌으로 쓰시면 됩니다
import java.util.Scanner;
abstract class GameObject {
protected int distance; // 한 번 이동거리
protected int x, y; // 현재 위치
public GameObject(int startX, int startY, int distance) { // 초기 위치와 이동 거리 설정
this.x = startX;
this.y = startY;
this.distance = distance;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean collide(GameObject p) { // 이 객체가 객체 p와 충돌했으면 true로 리턴
if (this.x == p.getX() && this.y == p.getY())
return true;
else
return false;
}
protected abstract void move(); // 이동한 후 새로운 위치로 x, y 변경
protected abstract char getShape(); // 객체의 모양을 나타내는 문자리턴
}
class Bear extends GameObject {
public static Scanner s = new Scanner(System.in);
public Bear(int startX, int startY, int distance) {
super(startX, startY, distance);
}
public void move() {
System.out.print("왼쪽(a), 아래(s), 위(d), 오른쪽(f) >> ");
String key = s.next();
switch (key) {
case "a": // 왼쪽
if (y > 0)
y--;
break;
case "s": // 아래쪽
if (x < 9)
x++;
break;
case "d": // 위쪽
if (x > 0)
x--;
break;
case "f": // 오른쪽
if (y < 19)
y++;
}
}
public char getShape() {
return 'B';
}
}
class Fish extends GameObject {
private int i = 0;
private int j = 0;
private int count = 0;
public Fish(int startX, int startY, int distance) {
super(startX, startY, distance);
}
public void move() {
int n = (int) (Math.random() * 2);
if (i != 3 && n == 0) { // 제자리 정리
i++;
count++;
} else if (j != 2 && n == 1) { // 랜덤이동
j++;
count++;
while (true) {
int r = (int) (Math.random() * 4 + 1);
switch (r) {
case 1: // 왼쪽
if (y > 0)
y--;
return;
case 2: // 아래쪽
if (x < 9)
x++;
return;
case 3: // 위쪽
if (x > 0)
x--;
return;
case 4: // 오른쪽
if (y < 19)
y++;
return;
default:
continue;
}
}
}
if (count == 5) {
i = 0;
j = 0;
count = 0;
}
}
public char getShape() {
return '@';
}
}
public class Game {
public static Scanner s = new Scanner(System.in);
static public char[][] list = new char[10][20];
static Bear bear = new Bear(0, 0, 1);
static Fish fish = new Fish(5, 5, 1);
static void delete() {
list[bear.x][bear.y] = '-';
list[fish.x][fish.y] = '-';
}
static void set_Bear() {
list[bear.x][bear.y] = bear.getShape();
}
static void set_Fish() {
list[fish.x][fish.y] = fish.getShape();
}
static void show() {
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++)
System.out.print(list[i][j]);
System.out.println();
}
}
public static void main(String[] args) {
for (int i = 0; i < list.length; i++)
for (int j = 0; j < list[i].length; j++)
list[i][j] = '-';
System.out.println("** Bear의 Fish 먹기 게임을 시작합니다.**");
while(true) {
if(bear.collide(fish)) {
System.out.println("Bear Wins!");
break;
}
set_Bear();
set_Fish();
show();
delete();
bear.move();
fish.move();
}
}
}
실행결과 >>
728x90
'Language > JAVA' 카테고리의 다른 글
[JAVA] 자바의 접근 지정자(access modifier) (0) | 2023.07.24 |
---|---|
[JAVA] 생성자와 this (0) | 2023.07.24 |
[JAVA] 변수의 기본형 & 참조형 타입의 차이 (0) | 2023.07.24 |
[JAVA] 선언 위치에 따른 변수의 종류 (0) | 2023.07.24 |
[JAVA] 객체, 클래스, 인스턴스의 차이 (0) | 2023.07.17 |