function hw1_test() hold on global BOT_UP = 1; global BOT_DOWN = 2; global BOT_LEFT = 3; global BOT_RIGHT = 4; agent = struct( "position", [9,9], "direction", BOT_UP ); % world = struct( "agent", agent, "width", 20, "height", 20, "tiles", round(20 * rand(20,2)), "holes", round(20 * rand(20,2)) ); world = struct( "agent", agent, "width", 20, "height", 20, "holes", [], "tiles", round(20 * rand(20,2)) ); for i = 1:20 x = round(world.width * rand(1)); y = round(world.height * rand(1)); life = round(20 * rand(1)) - 10; % life = 10; world.holes = [world.holes,make_hole(x,y,life)]; end steps = 20; for i = 1:steps old_world = world; new_world = world; new_world.agent = move_agent( old_world, old_world.agent ); new_world.holes = update_holes( old_world, old_world.holes ); world = new_world; draw_grid( world ); input('waiting'); end % draw_grid( world ); % input('waiting'); % world.agent.position = [9,10]; % draw_grid( world ); end function all = update_holes( world, holes ) for i = length( holes ) holes( i ).life -= 1; if ( holes( i ).life < 0 ) holes( i ).x = round(world.width * rand(1)); holes( i ).y = round(world.height * rand(1)); holes( i ).life = round(20 * rand(1)) - 10; % tiles( i ).life = 10; end end all = holes; end function hole = make_hole( x, y, life ) hole = struct( "x", x, "y", y, "life", life ); end function value = random_direction() global BOT_UP = 1; global BOT_DOWN = 2; global BOT_LEFT = 3; global BOT_RIGHT = 4; n = round(4 * rand(1) ) switch ( n ) case 1, value = BOT_UP; case 2, value = BOT_DOWN; case 3, value = BOT_LEFT; case 4, value = BOT_RIGHT; otherwise, value = BOT_LEFT; end end function value = move_agent( world, agent ) global BOT_UP = 1; global BOT_DOWN = 2; global BOT_LEFT = 3; global BOT_RIGHT = 4; switch ( agent.direction ) case BOT_UP, agent.position(2) += 1; case BOT_DOWN, agent.position(2) -= 1; case BOT_LEFT, agent.position(1) -= 1; case BOT_RIGHT, agent.position(1) += 1; end agent.direction = random_direction(); if ( agent.position(1) < 1 ) end value = agent; end function draw_hole( hole ) plot(hole.x, hole.y, 'ro' ); end function draw_grid( world ) clf; xs = [0,0,world.width,world.width,world.width/2]; ys = [0,world.height,0,world.height,world.height/2]; hold on; plot(xs,ys,'g+'); for i = 1:length( world.holes ) hole = world.holes( i ); if hole.life > 0 draw_hole( hole ); end end % tiles = world.tiles; % plot(world.tiles(:,1),world.tiles(:,2),'r+'); % plot(world.holes(:,1),world.holes(:,2),'ro'); plot(world.agent.position(1),world.agent.position(2),'px'); % plot( 0, 0, 'g+' ); % plot( world.width, 0, 'g+' ); % plot( 0, world.height, 'g+' ); % plot( world.width, world.height, 'g+' ); grid("on"); end