
% Load the weights and biases. Use your own .mat
% file name here instead of tr03.mat

% load tr03;

% Initialize values.

simul_time = 2000; % The simulation time in seconds.
show_loop = 5; % The time difference between displays in simul. seconds.

[v,pv] = initval;
st = 0;
n = pv(1,2)/pv(1,1)+1;
ind = 1;
crash_count = 0;
show_loop = show_loop/pv(1,1);

% Initialize the history.

for k=1:n,
  histarr(k,1) = v(1,1);
  histarr(k,2) = v(1,2);
  histarr(k,3) = v(1,3);
  histarr(k,4) = v(1,4);
  histarr(k,5) = v(1,5);
  histarr(k,6) = v(1,6);
end

acc_steps=0;
sl=show_loop;

% Loop until the simulation time is full.

while st<simul_time,
  sl = sl-1;
  hlp = histarr(ind,:); % The oldest state vector used by the control.
  % a = ncontrol(W1,W2,B1,B2,hlp,pv); % The neural control function.
  a = rcontrol(pv); % The random control function.
  v(1,6) = a; 
  v = update(v,pv);
  d = distance(v,pv);
  if d<pv(1,7) | d>pv(1,8)-pv(1,7), % The crash condition.
    fprintf('YOU CRASHED!!!\n');
    crash_count = crash_count+1;
    [v,pv]=initval;
  end
  if sl==0,
    sl=show_loop;
    showc(v,st); % Show the cars.
  end
  if acc_steps==0, % Change the control of the car1.
    acc_steps=round(rand*40)+1;
    v(1,3) = (rand-0.5)*pv(1,3);
  end
  acc_steps = acc_steps-1;
  % Update the simulator variables.
  st = st+pv(1,1);
  histarr(ind,:)=v;
  ind = ind+1;
  if ind>n, ind=1; end
end

hold off;
% Display the simulation information.
fprintf('\nTotal %i crashes in %i seconds\n', crash_count, simul_time);
