-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_gathering.py
269 lines (232 loc) · 8.99 KB
/
resource_gathering.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
from pathlib import Path
import gym
import numpy as np
import pygame
from gym.spaces import Box, Discrete
class ResourceGathering(gym.Env):
"""
Resource Gathering environment
Modified "Barrett, Leon & Narayanan, Srini. (2008). Learning all optimal policies with multiple criteria.
Proceedings of the 25th International Conference on Machine Learning. 41-47. 10.1145/1390156.1390162."
"""
metadata = {"render_modes": ["human", "rgb_array"], "render_fps": 4}
def __init__(self):
"""
size of the grid
"""
self.size = 5
self.window_size = 512
self.window = None
self.clock = None
"""
The map of resource gathering env
"""
self.map = np.array([
[' ', ' ', 'R1', 'E2', ' '],
[' ', ' ', 'E1', ' ', 'R2'],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', 'H', ' ', ' ']
]
)
self.initial_pos = np.array([4, 2], dtype=np.int32)
self.dir = {
0: np.array([-1, 0], dtype=np.int32), # up
1: np.array([1, 0], dtype=np.int32), # down
2: np.array([0, -1], dtype=np.int32), # left
3: np.array([0, 1], dtype=np.int32) # right
}
"""
four dimensions low = [0,0,0,0] high = [5,5,5,5]
encoded observation space
"""
self.observation_space = 1+1*2+1*4+4*20+4*100
"""
action space specification: 1 dimension, 0 up, 1 down, 2 left, 3 right
"""
self.action_space = Discrete(4)
"""
reward space:
"""
self.reward_space = Box(low=-1, high=100, shape=(3,), dtype=np.float32)
def get_map_value(self, pos):
return self.map[pos[0]][pos[1]]
def random_map(self):
"""
Randomly generate a new map with locations of diamond, gold and sword
"""
new_map = np.array([
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', 'H', ' ', ' ']
]
)
r1_x = np.random.randint(4)
r1_y = np.random.randint(4)
r2_x = np.random.randint(4)
r2_y = np.random.randint(4)
e1_x = np.random.randint(4)
e1_y = np.random.randint(4)
new_map[r1_x][r1_y]='R1'
new_map[r2_x][r2_y]='R2'
new_map[e1_x][e1_y]='E1'
return new_map
def is_valid_state(self, state):
"""
Check if the state is valid
Args:
state: the state to be checked
"""
return state[0] >= 0 and state[0] < self.size and state[1] >= 0 and state[1] < self.size
def render(self, mode='human'):
"""
Render the environment
"""
pix_square_size = self.window_size / self.size
if self.window is None:
self.gold_img = pygame.image.load(str(Path(__file__).parent.absolute()) + '/assets/gold.png')
self.gold_img = pygame.transform.scale(self.gold_img, (pix_square_size, pix_square_size))
self.gem_img = pygame.image.load(str(Path(__file__).parent.absolute()) + '/assets/gem.png')
self.gem_img = pygame.transform.scale(self.gem_img, (pix_square_size, pix_square_size))
self.enemy_img = pygame.image.load(str(Path(__file__).parent.absolute()) + '/assets/sword.png')
self.enemy_img = pygame.transform.scale(self.enemy_img, (pix_square_size, pix_square_size))
self.home_img = pygame.image.load(str(Path(__file__).parent.absolute()) + '/assets/home.png')
self.home_img = pygame.transform.scale(self.home_img, (pix_square_size, pix_square_size))
self.agent_img = pygame.image.load(str(Path(__file__).parent.absolute()) + '/assets/stickerman.png')
self.agent_img = pygame.transform.scale(self.agent_img, (pix_square_size, pix_square_size))
if self.window is None and mode == "human":
pygame.init()
pygame.display.init()
self.window = pygame.display.set_mode((self.window_size, self.window_size))
if self.clock is None and mode == "human":
self.clock = pygame.time.Clock()
canvas = pygame.Surface((self.window_size, self.window_size))
canvas.fill((255, 255, 255))
canvas.blit(self.home_img, self.initial_pos[::-1] * pix_square_size)
for i in range(self.map.shape[0]):
for j in range(self.map.shape[1]):
pos = np.array([j,i])
if self.map[i,j] == 'R1' and not self.has_gold:
canvas.blit(self.gold_img, np.array([j,i]) * pix_square_size)
elif self.map[i,j] == 'R2' and not self.has_gem:
canvas.blit(self.gem_img, np.array([j,i]) * pix_square_size)
elif self.map[i,j] == 'E1' or self.map[i,j] == 'E2':
canvas.blit(self.enemy_img, np.array([j,i]) * pix_square_size)
canvas.blit(self.agent_img, self.current_pos[::-1] * pix_square_size)
for x in range(self.size + 1):
pygame.draw.line(
canvas,
0,
(0, pix_square_size * x),
(self.window_size, pix_square_size * x),
width=2,
)
pygame.draw.line(
canvas,
0,
(pix_square_size * x, 0),
(pix_square_size * x, self.window_size),
width=2,
)
if mode == "human":
# The following line copies our drawings from `canvas` to the visible window
self.window.blit(canvas, canvas.get_rect())
pygame.event.pump()
pygame.display.update()
# We need to ensure that human-rendering occurs at the predefined framerate.
# The following line will automatically add a delay to keep the framerate stable.
self.clock.tick(self.metadata["render_fps"])
else: # rgb_array
return np.transpose(
np.array(pygame.surfarray.pixels3d(canvas)), axes=(1, 0, 2)
)
def get_state(self):
"""
Get the current state of the environment
"""
pos = self.current_pos.copy()
# state = np.concatenate((pos, np.array([self.has_gold, self.has_gem, self.has_sword], dtype=np.int32)))
state_id = self.has_gold+ self.has_gem*2+self.has_sword*4+pos[0]*20+pos[1]*100
return state_id
def reset(self, seed=None, return_info=False, **kwargs):
"""
Reset the environment
Args:
seed: the seed to be used for the environment
return_info: whether to return additional information
Generates new map with stochastic probability
"""
super().reset(seed=seed)
self.np_random.seed(seed)
self.current_pos = self.initial_pos
self.has_gem = 0
self.has_gold = 0
self.has_sword = 0
self.step_count = 0.0
state = self.get_state()
self.map = np.array([
[' ', ' ', 'R1', 'E2', ' '],
[' ', ' ', 'E1', ' ', 'R2'],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', 'H', ' ', ' ']
]
)
probs = np.random.random()
if probs>0.9999:
self.map=self.random_map()
print(probs)
return (state, {}) if return_info else state
def step(self, action):
"""
Perform a step in the environment
Args:
action (int): the action to be performed
"""
next_pos = self.current_pos + self.dir[action]
if self.is_valid_state(next_pos):
self.current_pos = next_pos
vec_reward = np.zeros(3, dtype=np.float32)
done = False
cell = self.get_map_value(self.current_pos)
if cell == 'R1':
if np.random.random() < 0.1:
self.has_gold = 0
else:
self.has_gold = 1
vec_reward[0]+=10
elif cell == 'R2':
if np.random.random() < 0.1:
self.has_gem = 0
else:
self.has_gem = 1
vec_reward[1]+=10
elif cell == 'E1' or cell == 'E2':
if np.random.random() < 0.1:
self.has_sword = 0
else:
self.has_sword = 1
vec_reward[2]+=50
elif cell == 'H':
done = True
state = self.get_state()
return state, vec_reward, done, {}
def close(self):
"""
Close the environment
"""
if self.window is not None:
pygame.display.quit()
pygame.quit()
if __name__ == '__main__':
env = ResourceGathering()
done = False
env.reset()
while True:
env.render()
obs, r, done, info = env.step(env.action_space.sample())
print(obs, r, done)
if done:
env.reset()