Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
w wa
w wa el 25 de Jul. de 2015
Comentada: Cedric el 25 de Jul. de 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.

Respuestas (2)

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

Iniciar sesión para comentar.


Brian Hannan
Brian Hannan el 25 de Jul. de 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!

Translated by