-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
146 lines (115 loc) · 4.46 KB
/
agent.py
File metadata and controls
146 lines (115 loc) · 4.46 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
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
import torch
import random
import numpy as np
from collections import deque
from QNet import QNet, QTrainer, plot
from snake import SnakeGameAgent, Direction, Point, BLOCK_SIZE
MAX_MEMMORY = 100_000
BATCH_SIZE = 1000
LR = 0.001
class AiAgent:
def __init__(self):
self.n_game = 0
self.epsilon = 0 # randomness
self.gamma = 0.8 #discount-rate
self.memmory = deque(maxlen=MAX_MEMMORY)
self.model = QNet(11, 512, 3)
self.trainer = QTrainer(model=self.model, lr=LR, gamma=self.gamma)
def get_state(self, game):
head = game.snake[0]
lpoint = Point(head.x - BLOCK_SIZE, head.y)
rpoint = Point(head.x + BLOCK_SIZE, head.y)
upoint = Point(head.x, head.y - BLOCK_SIZE)
dpoint = Point(head.x, head.y + BLOCK_SIZE)
ldir = game.direction == Direction.LEFT
rdir = game.direction == Direction.RIGHT
udir = game.direction == Direction.UP
ddir = game.direction == Direction.DOWN
state = [
#straight Danger
(rdir and game.is_collision(rpoint)) or
(ldir and game.is_collision(lpoint)) or
(udir and game.is_collision(upoint)) or
(ddir and game.is_collision(dpoint)),
#right danger
(rdir and game.is_collision(dpoint)) or
(ldir and game.is_collision(upoint)) or
(udir and game.is_collision(rpoint)) or
(ddir and game.is_collision(lpoint)),
#left Danger
(rdir and game.is_collision(upoint)) or
(ldir and game.is_collision(dpoint)) or
(udir and game.is_collision(lpoint)) or
(ddir and game.is_collision(rpoint)),
#move dir
ldir,
rdir,
udir,
ddir,
#food
game.food.x < game.head.x, #food on left
game.food.x > game.head.x, #food on right
game.food.y < game.head.y, #food on top
game.food.y > game.head.y #food on bottom
]
return np.array(state, dtype=int)
def remember(self, state, action, reward, next_state, game_over):
memmory = (state, action, reward, next_state, game_over)
self.memmory.append(memmory)
def train_long_memmory(self):
if len(self.memmory) > BATCH_SIZE:
sample = random.sample(self.memmory, BATCH_SIZE)
else:
sample = self.memmory
states, actions, rewards, next_states, game_overs = zip(*sample)
self.trainer.train_step(states, actions, rewards, next_states, game_overs)
def train_short_memmory(self, state, action, reward, next_state, game_over):
self.trainer.train_step(state, action, reward, next_state, game_over)
def get_action(self, state):
# initially explore the random moves and lateer exploit the models move once the model stabilizes
self.epsilon = 70 - self.n_game
final_move = [0,0,0]
if random.randint(0,200) < self.epsilon:
move = random.randint(0,2)
final_move[move] = 1
else:
state0 = torch.tensor(state, dtype = torch.float)
pred = self.model(state0)
move = torch.argmax(pred).item()
final_move[move] = 1
return final_move
def train():
plot_score = []
plot_ms = []
total_score = 0
highest_score = 0
agent = AiAgent()
snake = SnakeGameAgent()
snake.reset()
while True:
#old state
old_state = agent.get_state(snake)
#action for that
final_move = agent.get_action(old_state)
#do the move and get the new state
reward, game_over, score = snake.play_step(final_move)
new_state = agent.get_state(snake)
#train short memmory
agent.train_short_memmory(old_state, final_move, reward, new_state, game_over)
#remember the values
agent.remember(old_state, final_move, reward, new_state, game_over)
if game_over:
snake.reset()
agent.n_game += 1
agent.train_long_memmory()
if score > highest_score:
highest_score = score
agent.model.save()
print('Game', agent.n_game, 'Score', score)
plot_score.append(score)
total_score += score
mean_score = total_score / agent.n_game
plot_ms.append(mean_score)
plot(plot_score, plot_ms)
if __name__ == "__main__":
train()