How do I randomly spawn 10 different "enemies" in a 30x30 rectangle

2 views (last 30 days)
I'm making a game as a practice exercise in which you, the player, spawn as a circle and 10 other enemies (# of enemies increase with level in increments of 10) spawn as rectangles along with you in different positions in a 30x30 rectangle/window. How do I ensure that all enemies are spawned randomly in separate locations? I was using randperm(900) but realized that there was the potential that all enemies would spawn in the same spot.

Answers (2)

Walter Roberson
Walter Roberson on 25 Jul 2015
enemy_idx = randperm(900,10);
the values are guaranteed to be different.
  3 Comments
Cedric
Cedric on 25 Jul 2015
Edited: Cedric on 25 Jul 2015
Well, I played even more (instead of sleeping!):
clf ; grid on ; hold on ;
pacman = @(x,y) plot( bsxfun(@plus, x(:)', 0.5*[0,cos(-3*pi/4:0.1:3*pi/4),0]'), bsxfun(@plus, y(:)', 0.5*[0,sin(-3*pi/4:0.1:3*pi/4),0]'), 'r' ) ;
pacman( colId, rowId )
set( gca, 'XTick', 0.5:1:30.5, 'XTickLabel', [], 'XLim', [0,31], 'YTick', 0.5:1:30.5, 'YTickLabel', [], 'YLim', [0,31] ) ;
text( 1:30, -ones(1,30), arrayfun(@(x)sprintf('%d', x), 1:30, 'UniformOutput', false ), 'Rotation', 90, 'HorizontalAlignment', 'right' ) ;
text( -ones(1,30), 1:30, arrayfun(@(x)sprintf('%d', x), 1:30, 'UniformOutput', false ), 'HorizontalAlignment', 'right' ) ;
Sorry Walter for having .. pacman-ized your answer!
Cedric
Cedric on 25 Jul 2015
I just made pacman more versatile, for purely scientific reasons..
pacman = @(x, y, varargin) plot( bsxfun( @plus, x(:)', 0.5*[0,cos(-3*pi/4:0.1:3*pi/4),0]' ), bsxfun( @plus, y(:)', 0.5*[0,sin(-3*pi/4:0.1:3*pi/4),0]' ), varargin{:} ) ;
so we can "call pacman" with PLOT name/value pairs ..
pacman( colId, rowId, 'LineWidth', 2 ) ;

Sign in to comment.


Brian Hannan
Brian Hannan on 25 Jul 2015
How about something like this?
locations = zeros(1, 30);
numBadGuysCreated = 0;
while numBadGuysCreated < 30
badGuyLocationNow = randi(900, 1);
if ~any(locations == badGuyLocationNow)
locations(numBadGuysCreated + 1) = badGuyLocationNow;
end
numBadGuysCreated = numBadGuysCreated + 1;
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!