【发布时间】:2012-10-02 17:48:11
【问题描述】:
我真的不懂面向对象设计的原理?? 所以我有课
Map 类保存房间并连接所有房间,将所有危险随机放入房间,返回微粒房间,并返回随机房间。
和
玩家类可以轮流玩,将玩家从一个房间移动到另一个房间,射入房间并玩游戏。
还有
房间等级如下。
import java.util.ArrayList;
public class Room
{
private int myRoomID;
private ArrayList<Room> myNeighbours;
private boolean myHasBats;
private boolean myHasPit;
private boolean myHasWumpus;
public Room(int id) {
myRoomID = id;
myNeighbours = new ArrayList<Room>();
}
public int getRoomID() {
return myRoomID;
}
public ArrayList<Room> getNeighbours() {
return myNeighbours;
}
public void connectTo(Room room) {
myNeighbours.add(room);
}
public boolean hasBats() {
return myHasBats;
}
public void setHasBats(boolean flag) {
myHasBats = flag;
}
public boolean hasPit() {
return myHasPit;
}
public void setHasPit(boolean flag) {
myHasPit = flag;
}
public boolean hasWumpus() {
return myHasWumpus;
}
public void setHasWumpus(boolean flag) {
myHasWumpus = flag;
}
public void checkBats() {
boolean bats = false;
for (Room r : myNeighbours) {
if (r.hasBats()) {
bats = true;
}
}
if (bats) {
System.out.println("I hear squeaking!");
}
}
public void checkPit() {
boolean pit = false;
for (Room r : myNeighbours) {
if (r.hasPit()) {
pit = true;
}
}
if (pit) {
System.out.println("I feel a draft!");
}
}
public void checkWumpus() {
boolean wumpus = false;
for (Room r : myNeighbours) {
if (r.hasWumpus()) {
wumpus = true;
}
}
if (wumpus) {
System.out.println("I smell a wumpus!");
}
}
public boolean enter(Player player) {
System.out.println("You are in Room " + myRoomID);
System.out.print("Exits lead to rooms");
for (Room r : myNeighbours) {
System.out.print(" " + r.getRoomID());
}
System.out.println();
checkBats();
checkPit();
checkWumpus();
if (myHasBats) {
System.out.println("A flock of bats picks you up and carries you off to another room!");
return player.moveRandom();
}
else if (myHasPit) {
System.out.println("You fall into a bottomless pit!");
return true;
}
else if (myHasWumpus) {
System.out.println("You have been eaten by a wumpus!");
return true;
}
return false;
}
public boolean shoot()
if (myHasWumpus) {
System.out.println("You killed the Wumpus!");
return true;
}
else {
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
}
我想改变这一点,这样 wumpus 需要被射杀不止一次(你选择多少次)才能被杀死。每次射击它都会跑到一个随机的相邻房间(不是玩家所在的房间)。
我假设我需要将public boolean shoot() 方法更改为循环并调用public Room getRandomRoom(),如下所示。
但我真的不明白如何做到这一点,特别是因为布尔方法的使用让我很困惑。 有谁知道我在哪里可以找到学习面向对象设计基础的信息?
public Room getRandomRoom() {
Random rng = new Random();
int i = rng.nextInt(Map.NUM_ROOMS);
return myRooms.get(i);
}
稍后我们将在类中使用implements 将所有危害划分为类。但不是他们都在地图和房间类。
【问题讨论】:
-
我想我只需要发布
public boolean shoot()方法,但我对此非常感兴趣,以至于我什至不知道从哪里开始...... -
@user1721548 好吧,现在就去做吧。最好让您的问题具有对您有用的最小范围(如有必要,提出更多问题),而不是针对您在完成作业或其他任何事情时发生的每一件事提出一个问题。
-
@user1721548 这样做既可以帮助我们更快地为您提供更好的答案,因为一次需要的内容更少,并且如果您必须将其分解为您遇到的孤立问题。