forked from monokim/framework_tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
63 lines (49 loc) · 1.83 KB
/
Copy pathmain.py
File metadata and controls
63 lines (49 loc) · 1.83 KB
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
import sys
import numpy as np
import math
import random
import gym
import gym_game
def simulate():
global epsilon, epsilon_decay
for episode in range(MAX_EPISODES):
# Init environment
state = env.reset()
total_reward = 0
# AI tries up to MAX_TRY times
for t in range(MAX_TRY):
# In the beginning, do random action to learn
if random.uniform(0, 1) < epsilon:
action = env.action_space.sample()
else:
action = np.argmax(q_table[state])
# Do action and get result
next_state, reward, done, _ = env.step(action)
total_reward += reward
# Get correspond q value from state, action pair
q_value = q_table[state][action]
best_q = np.max(q_table[next_state])
# Q(state, action) <- (1 - a)Q(state, action) + a(reward + rmaxQ(next state, all actions))
q_table[state][action] = (1 - learning_rate) * q_value + learning_rate * (reward + gamma * best_q)
# Set up for the next iteration
state = next_state
# Draw games
env.render()
# When episode is done, print reward
if done or t >= MAX_TRY - 1:
print("Episode %d finished after %i time steps with total reward = %f." % (episode, t, total_reward))
break
# exploring rate decay
if epsilon >= 0.005:
epsilon *= epsilon_decay
if __name__ == "__main__":
env = gym.make("Pygame-v0")
MAX_EPISODES = 9999
MAX_TRY = 1000
epsilon = 1
epsilon_decay = 0.999
learning_rate = 0.1
gamma = 0.6
num_box = tuple((env.observation_space.high + np.ones(env.observation_space.shape)).astype(int))
q_table = np.zeros(num_box + (env.action_space.n,))
simulate()