How do I randomly spawn 10 different "enemies" in a 30x30 rectangle
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (2)
Walter Roberson
el 25 de Jul. de 2015
enemy_idx = randperm(900,10);
the values are guaranteed to be different.
3 comentarios
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
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 ) ;
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
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!