simpleGameEngine
simpleGameEngine
methods
function obj = simpleGameEngine(sprites_fname, sprite_height,
sprite_width, zoom, background_color)
% simpleGameEngine
% Input:
% 1. File name of sprite sheet as a character array
% 2. Height of the sprites in pixels
% 3. Width of the sprites in pixels
% 4. (Optional) Zoom factor to multiply image by in final
figure (Default: 1)
1
% 5. (Optional) Background color in RGB format as a 3
element vector (Default: [0,0,0] i.e. black)
% Output: an SGE scene variable
% Note: In RGB format, colors are specified as a mixture
of red, green, and blue on a scale of 0 to 255. [0,0,0] is black,
[255,255,255] is white, [255,0,0] is red, etc.
% Example:
% my_scene =
simpleGameEngine('tictactoe.png',16,16,5,[0,150,0]);
% loop over the image and load the individual sprite data
into
% the object
for r=1:sprite_row_max
for c=1:sprite_col_max
r_min = sprite_height*(r-1)+r;
r_max = sprite_height*r+r-1;
c_min = sprite_width*(c-1)+c;
c_max = sprite_width*c+c-1;
obj.sprites{end+1} =
sprites_image(r_min:r_max,c_min:c_max,:);
obj.sprites_transparency{end+1} =
transparency(r_min:r_max,c_min:c_max,:);
2
end
end
end
scene_size = size(background_sprites);
num_rows = scene_size(1);
num_cols = scene_size(2);
% loop over the rows and colums of the tiles in the scene
to
% draw the sprites in the correct locations
for tile_row=1:num_rows
for tile_col=1:num_cols
3
% Build the tile layer by layer, starting with the
% background color
tile_data =
zeros(obj.sprite_height,obj.sprite_width,3,'uint8');
for rgb_idx = 1:3
tile_data(:,:,rgb_idx) =
obj.background_color(rgb_idx);
end
% handle zooming
big_scene_data = imresize(scene_data,obj.zoom,'nearest');
4
% set guidata to the key press and release functions,
% this allows keeping track of what key has been
pressed
obj.my_figure.KeyPressFcn =
@(src,event)guidata(src,event.Key);
obj.my_figure.KeyReleaseFcn =
@(src,event)guidata(src,0);
elseif isempty(obj.my_image) ||
~isprop(obj.my_image, 'CData') || ~isequal(size(big_scene_data),
size(obj.my_image.CData))
% Re-display the image if its size changed
figure(obj.my_figure);
obj.my_image =
imshow(big_scene_data,'InitialMagnification', 100);
else
% otherwise just update the image data
obj.my_image.CData = big_scene_data;
end
end
5
% Output:
% 1. The row of the tile clicked by the user
% 2. The column of the tile clicked by the user
% 3. (Optional) the button of the mouse used to click
(1,2, or 3 for left, middle, and right, respectively)
%
% Notes: A set of “crosshairs” appear in the scene’s
figure,
% and the program will pause until the user clicks on the
% figure. It is possible to click outside the area of the
% scene, in which case, the closest row and/or column is
% returned.
%
% Example:
% [row,col,button] = getMouseInput (my_scene);
6
Published with MATLAB® R2020b