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

1 Ansicht (letzte 30 Tage)
w wa
w wa am 25 Jul. 2015
Kommentiert: Cedric am 25 Jul. 2015
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.

Antworten (2)

Walter Roberson
Walter Roberson am 25 Jul. 2015
enemy_idx = randperm(900,10);
the values are guaranteed to be different.
  3 Kommentare
Cedric
Cedric am 25 Jul. 2015
Bearbeitet: Cedric am 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 am 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 ) ;

Melden Sie sich an, um zu kommentieren.


Brian Hannan
Brian Hannan am 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

Kategorien

Mehr zu Just for fun finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by