function love.load() --Call external sources require 'graphics'; --Run the Game demo_robots(); end function robots() --Game Constants _H = 24; --height of game world _W = 32; --width of game world _N = 10; --number of robots --Define movement keys directions = { q = -_W - 1, w = -_W, e = -_W +1, a = -1, s = 0, d = 1, z = _W - 1, x = _W, c = _W+1}; --Shake the dice math.randomseed(os.time()); --Fresh Start all relavant paramters new_start(); end function new_start() --Init Game Parameters POS = math.random(_W*_H); --player's position R = {}; --robot's position game_status = "no news"; --Hook for win/lose/not text --Set the Robots at random locations for i=1, _N do table.insert(R, math.random(_H * _W)); end end function is_all_scrapped() --Determines if all robots are scrapped for i, v in ipairs(R) do if not (count(R, v) > 1) then return false; end end return true; --can only get here if all are scrapped end function count(list, item) --Count number of imatching tems in this list cnt = 0; for k = 1, _N do if (list[k] == item) then cnt = cnt + 1; end end return cnt; end function largest_fixnum() return 999999999; --return really big number end function choose_direction(robot, player) --Try each direction and choose the one with minimal distance to the player lowest = largest_fixnum(); for i,v in pairs(directions) do dist = manhattan_distance(robot + v, player); if (dist < lowest) then lowest = dist; dir = i; end end return dir; end function love.keypressed(key, unicode) if not (game_status == bad_news_string) then --Movement Keys if not (directions[key] == nil) then POS = POS + directions[key]; --Teleport Key elseif key == 't' then POS = math.random(_W*_H); end --Robots take a move robots_move(); --Check Win Condition if (is_all_scrapped()) then game_status = "good news"; end --Check Lose Condition if (count(R, POS) > 0) then game_status = "bad news"; end else --Restart Key if key == 'r' then new_start(); end --Leave Key if key == 'l' then player_exit(); end end --Restart Key if key == 'r' then new_start(); end --Leave Key if key == 'l' then player_exit(); end end function player_exit() os.exit(); end function robots_move() --Robots move towards the player for i,v in ipairs(R) do --Ignore scrap if not (count(R, v) > 1) then R[i] = R[i] + directions[choose_direction(v, POS)]; end end end function manhattan_distance(p, q) --Calculates manhattan distance between two locations A = convert(p); B = convert(q); return math.abs(A.x- B.x) + math.abs(A.y - B.y); end function convert(i) --Convert single integer location to 2d-coordinates D = {}; D.x = math.mod(i, _W); D.y = ((i - D.x)/_W) + 1; return D; end function demo_robots() load_images(); robots(); end