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

1 次查看(过去 30 天)
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.

回答(2 个)

Walter Roberson
Walter Roberson 2015-7-25
enemy_idx = randperm(900,10);
the values are guaranteed to be different.
  3 个评论
Cedric
Cedric 2015-7-25
编辑:Cedric 2015-7-25
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 2015-7-25
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
Brian Hannan 2015-7-25
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

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by