xMin = 0; xMax = 100;
yMin = 0; yMax = 100;
particles = 10;
minVelocity = -5;
maxVelocity = 5;

% Create particle starting positions.
positionsX = zeros(particles,1); positionsY = zeros(particles,1);
for i = 1:particles
    positionsX(i) = xMax*rand();
    positionsY(i) = yMax*rand();
end

% Create particle initial velocities.
velocitiesX = zeros(particles,1); velocitiesY = zeros(particles,1);
for i = 1:particles
    velocitiesX(i) = (maxVelocity - minVelocity) * rand() + minVelocity;
    velocitiesY(i) = (maxVelocity - minVelocity) * rand() + minVelocity;
end

plot(positionsX, positionsY, 'o');

for t = 1:200
    for i = 1:particles
        
        for j = 1:particles
            if i ~= j % if not comparing position of same particle
                if abs(positionsX(i) - positionsX(j)) <= 1 && abs(positionsY(i) - positionsY(j)) <= 1
                    fprintf('collision: %i\n', t)
                    tempX = velocitiesX(i);
                    tempY = velocitiesY(i);
                    velocitiesX(i) = velocitiesX(j);
                    velocitiesY(i) = velocitiesY(j);
                    velocitiesX(j) = tempX;
                    velocitiesY(j) = tempY;
                    break
                end
            end
        end
        
        positionsX(i) = positionsX(i) + velocitiesX(i);
        positionsY(i) = positionsY(i) + velocitiesY(i);
        
        if positionsX(i) < 0
            velocitiesX(i) = velocitiesX(i) * -1;
            positionsX(i) = positionsX(i) * -1;
        elseif positionsX(i) > xMax
            velocitiesX(i) = velocitiesX(i) * -1;
            positionsX(i) = xMax - (positionsX(i) - xMax);
        end
        if positionsY(i) < 0
            velocitiesY(i) = velocitiesY(i) * -1;
            positionsY(i) = positionsY(i) * -1;
        elseif positionsY(i) > yMax
            velocitiesY(i) = velocitiesY(i) * -1;
            positionsY(i) = yMax - (positionsY(i) - yMax);
        end
        plot(positionsX, positionsY, 'o');
        xlim([xMin xMax]); ylim([yMin yMax]);
        %pause(0.0001)
    end
    saveas(gcf, ['gas_',sprintf('%03d',t),'.png'])
end