一个迷宫是由许许多多的Mapsite组成,ROOM,Wall,Door是三种Mapsite,每个Wall的两边必有两个ROOM,每个ROOM必有四个Mapsite(可以是Wall,ROOM,Door的任何一种),Mapsite是Room和Door是可以通过的,是Wall则无法通过
[3].[代码] Mapsite.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
6
7
8
|
/**
* 迷宫游戏,面向对象是怎么解决这个问题的
* @author S
*
*/
public
interface
Mapsite {
public
void
Enter();
}
|
[4].[代码] Room.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
class
Room
implements
Mapsite{
private
Mapsite sides[]=
new
Mapsite[
4
];
//每个房间都有4个组件
private
int
roomNo;
public
Room(
int
roomNo){
this
.roomNo=roomNo;
}
@Override
public
void
Enter() {
System.out.println(
"you can pass here"
);
}
public
void
setSide(Direction d,Mapsite site){
System.out.println(
"room"
+
this
.roomNo+
"'s "
+d+
" is a "
+site.getClass().getName());
}
}
|
[5].[代码] Door.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
class
Door
implements
Mapsite{
/**
* 门的两边是两个房间
*/
public
Room room1;
public
Room room2;
//public boolean isOpen;
@Override
public
void
Enter() {
System.out.println(
"you can pass here"
);
}
public
Door(Room room1,Room room2){
this
.room1=room1;
this
.room2=room2;
}
}
|
[6].[代码] Game.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public
class
Game {
public
static
void
main(String[] args) {
Maze m=
new
Maze();
Room r1=
new
Room(
1
);
Room r2=
new
Room(
2
);
Door door1=
new
Door(r1,r2);
m.addRoom(r1);
m.addRoom(r2);
r1.setSide(Direction.NORTH,
new
Wall());
r1.setSide(Direction.SOUTH,
new
Wall());
r1.setSide(Direction.WEST,
new
Wall());
r1.setSide(Direction.EAST, door1);
r2.setSide(Direction.NORTH,
new
Wall());
r2.setSide(Direction.SOUTH,
new
Wall());
r2.setSide(Direction.EAST,
new
Wall());
r2.setSide(Direction.WEST, door1);
}
}
|
[7].[代码] Maze.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
|
public
class
Maze {
public
void
addRoom(Room r){
System.out.println(
"Add one room"
);
}
}
|
[8].[代码] Wall.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
4
5
6
7
8
|
public
class
Wall
implements
Mapsite{
@Override
public
void
Enter() {
System.out.println(
"you can't pass here"
);
}
}
|
[9].[代码] Ditection.class 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9]
1
2
3
|
public
enum
Direction {
NORTH,SOUTH,EAST,WEST
}
|