File size: 1,992 Bytes
fe446ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import numpy as np
import pygame
import tensorflow as tf
from .fyp_simulation import GameEnv
from .fyp_simulation.ddqn_keras import DDQNAgent

# model_path = "ddqn_model.keras"
model_path = os.path.join(os.path.dirname(__file__), 'fyp_simulation', 'ddqn_model.keras')

try:
    model = tf.keras.models.load_model(model_path)
    print("Model loaded successfully!")
except Exception as e:
    print(f" Failed to load model: {e}")

TOTAL_GAMETIME = 10000
N_EPISODES = 10000
REPLACE_TARGET = 10

game = GameEnv.RacingEnv()
game.fps = 60

ddqn_agent = DDQNAgent(alpha=0.0005, gamma=0.99, n_actions=5, epsilon=0.02, 
                        epsilon_end=0.01, epsilon_dec=0.999, replace_target=REPLACE_TARGET, 
                        batch_size=64, input_dims=19, fname=model_path)

ddqn_agent.load_model()
ddqn_agent.update_network_parameters()

def run():
    for e in range(N_EPISODES):
        game.reset()
        done = False
        score = 0
        counter = 0
        gtime = 0
        observation_, reward, done = game.step(0)
        observation = np.array(observation_)

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return

            action = ddqn_agent.choose_action(observation)
            observation_, reward, done = game.step(action)
            observation_ = np.array(observation_)

            if reward == 0:
                counter += 1
                if counter > 100:
                    done = True
            else:
                counter = 0

            score += reward
            observation = observation_
            gtime += 1
            if gtime >= TOTAL_GAMETIME:
                done = True
            game.render(action)
            #  if score > best_score:
            # best_score = score
            # ddqn_agent.save_model()
            # print(f" New best score {best_score}! Model saved.")

        print(f"Episode: {e}, Reward: {score}")

run()