How do load an image into a 2D array element? - arrays

I'm currently doing my A-Level Computing project for which I am making my own version of the classic game Space Invaders.
To create the wave of space invaders I want to use a 2D array of images, where the images are loaded from a disk and then displayed on the form but I am unsure of how load the images into the array and then display the array on a form.
The current arrays are:
ImagePaths:array [1..3] of string =('SpaceInvader1.jpg', 'SpaceInvader2.jpg', 'SpaceInvader3.jpg');
Wave:array[1..11, 1..5] of TImage; x,y:integer;
What I would like to know is: how would I load an image into an array element? eg how would I load 'SpaceInvader1.jpg' to array element [1,1]?
Any help would be greatly appreciated.

If you're going to be coding graphical animations, you probably won't want to do it directly on the form. Trying to move things around can be tricky, especially if you want to animate smoothly and not get a lot of flicker and graphical artifacts.
It would be better to use a rendering library. The workflow goes like this:
Create a rendering context on the form. This is a control that provides a surface for graphical animations to run on.
Load your three images into memory.
Create an array of objects to represent the game data associated with your monsters. (Position, movement direction and speed, etc.) It can be flat or 2D, whichever works better for you.
Set up a render loop that goes like this:
For each monster in the array, draw it at its position.
Draw the player's ship and all projectiles.
Check for collisions and handle appropriately.
Check for player input and handle appropriately.
You can find plenty of information on rendering libraries for Delphi in the forums at Pascal Game Development.

You have the following declarations:
ImagePaths:array [1..3] of string =(
'SpaceInvader1.jpg',
'SpaceInvader2.jpg',
'SpaceInvader3.jpg'
);
Wave: array[1..11, 1..5] of TImage;
You want to know how to populate the array of images. It is quite wasteful to create 55 images when 3 will suffice. So instead of that, use indirection. Store references to the images. And TImage is a visual component, and so not appropriate for a sprite.
I would hold the images in an array like this:
Sprites: array [1..3] of TBitmap;
And populate it
JPEGImage := TJPEGImage.Create;
try
for i := 1 to 3 do
begin
JPEGImage.LoadFromFile(ImagePaths[i]);
Sprites[i] := TBitmap.Create;
Sprites[i].Assign(JPEGImage);
end;
finally
JPEGImage.Free;
end;
Then populate your Wave array like this, for example:
Wave: array[1..11, 1..5] of TBitmap;
....
for i := 1 to 11 do
for j := 1 to 5 do
Wave[i,j] := Sprites[1];// or whichever sprite you want
Of course your sprites may be better with a real name rather than in an array.
Some other comments:
JPEG is a bad format for a game sprite. It is a lossy format. A plain Windows bitmap would be fine, as would a GIF or PNG.
I'd much rather see the images as embedded resources. Then your executable can stand alone.
I'd also far rather see your Waves array holding the state of each invader. And then you would create a function that would render that state onto a canvas.

Related

Swift 3 - Function to create n number of sprites with random x/y coordinates

I am trying to create multiple SKSpriteNodes that each have their own independent variables that I can change/modify. I would like to be able to run a function when the app starts, for example "createSprites(5)" which would create 5 sprites with the image/texture "shape.png" at random x and y coordinates and add all 5 Sprites to an array that I can access and edit different Sprite's positioning based on the index value. I would then like to be able to have another function "addSprite()" which, each time it is called, create a new Sprite with the same "shape.png" texture, place it at another random X and Y coordinate and also add it to the array of all Sprites to, again, be able to access later and change coordinates etc.
I have been looking through so many other Stack Overflow pages and can not seem to find a solution. My ideal solution would simply be the two functions I stated earlier. One to create an "n" number of Sprites and another function to create and add one more sprite to the array each time it is called.
Hope that makes sense, I'm fairly new to Swift and all this Sprite stuff, so simple informative answers would be very much appreciated.
You're not going to find an ideal solution from the past because nobody has likely had exactly the same desire with both Swift and SpriteKit. Having said that, there's likely partial answers you can blend together, and get the result you want or, at least, an understanding of how to do it.
Sprite Positioning in SK is probably the first thing to read up on:
https://developer.apple.com/library/content/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Sprites/Sprites.html
having gotten that figured out, you can move to random positions.
Random positioning of Sprites:
Duplicate Sprite in Random Positions with SpriteKit
Sprite Kit random positions
Both use earlier versions of randomisation that aren't as powerful as what's available now, in GameplayKit. So... Generating random numbers in Swift with GameplayKit:
https://www.hackingwithswift.com/read/35/overview
It's hard to overstate the importance of understanding the various possibilities of game design implications of varying types of randomisation, so probably wise to read this, from Apple:
https://developer.apple.com/library/content/documentation/General/Conceptual/GameplayKit_Guide/RandomSources.html
After that, it's a case of needing to determine what constitutes a time or event at which to create more sprites at more random positions, and how fussy you want to be about proximity to other sprites, and overlaps.

Big SCNGeometry SceneKit for iOS

I am working on a cocoa/iOS projet.
I have a common swift class which manage a Scenekit scene.
I want to draw a big terrain (about 5000x5000 points).
I have 2 triangles per 4 points. I have created a scngeometry object for the whole terrain (is it a good thing ?)
I decided to store those points in a 6-Float structure (x,y,z and r,g,b). I tried to create an empty array or to allocate a big array at the begining : i got the same issue.
I work with Int datatype for indices array.
The project works fine on Cocoa but i get memory errors on iOS. I think this is because of the need to have a big and contigous array for vertex.
I tried to create several chunks of geometry objects but scene kit does not like if we erase a previous buffer.
What is the best practice in this case ?
Is there a way to store vertex on the mass storage instead of memory arrays/buffers ?
Thanks
So...twice as many terrain points as there are pixels on a shiny new 5K display? That's a huge amount of memory to be using at once on iOS. And you won't be able to see that resolution on an iOS device.
So how about:
Break your 25 million pixel terrain into smaller tiles, each in its own SCNNode. Loop through the tiles, create one SCNNode, throw away the 6-Float array for that tile and move to the next.
Use SCNLevelOfDetail to produce much simpler versions of those nodes, for display when they're very far away.
Do the construction work on OS X. Archive your scene (NSSecureCoding). Bundle that scene into the iOS app.
Consider using reference nodes in your main SCNScene, and archive each tile as a separate SCNScene file.
Hopefully you're already using triangle strips, not triangles, to build your geometry.

Simple Multi-Blob Detection of a Binary Image?

If there is a given 2d array of an image, where threshold has been done and now is in binary information.
Is there any particular way to process this image to that I get multiple blob's coordinates on the image?
I can't use openCV because this process needs to run simultaneously on 10+ simulated robots on a custom simulator in C.
I need the blobs xy coordinates, but first I need to find those multiple blobs first.
Simplest criteria of pixel group size should be enough. But I don't have any clue how to start the coding.
PS: Single blob should be no problem. Problem is multiple blobs.
Just a head start ?
Have a look at QuickBlob which is a small, standalone C library that sounds perfectly suited for your needs.
QuickBlob comes with a small command-line tool (csv-blobs) that outputs the position and size of each blob found within the input image:
./csv-blobs white image.png
X,Y,size,color
28.37,10.90,41,white
51.64,10.36,42,white
...
Here's an example (output image is produced thanks to the show-blobs.py tiny Python utility that comes with QuickBlob):
You can go through the binary image labeling the connected parts with an algorithm like the following:
Create a 2D array of ints, labelArray, that will hold the labels of the connected regions and initiate it to all zeros.
Iterate over each binary pixel, p, row by row
A. If p is true and the corresponding value for this position in the labelArray is 0 (unlabeled), assign it to a new label and do a breadth-first search that will add all surrounding binary pixels that are also true to that same label.
The only issue now is if you have multiple blobs that are touching each other. Because you know the size of the blobs, you should be able to figure out how many blobs are in a given connected region. This is the tricky part. You can try doing a k-means clustering at this point. You can also try other methods like using binary dilation.
I know that I am very late to the party, but I am just adding this for the benefipeople who are researching this problem.
Here is a nice description that might fit your needs.
http://www.mcs.csueastbay.edu/~grewe/CS6825/Mat/BinaryImageProcessing/BlobDetection.htm

Optimal referential 2d array?

So, I'm creating a fairly basic overhead 2d game where users can "draw" a map. (Actually, they dont draw it, the manually input a list of x/y's, but the design aspect isnt important just now.)
When a new tile is added, that tile goes into an array of all tiles ingame.
The centrepoint is 0,0. Tiles can be added in all directions, so may be at 1,1 or 100,100 or -50,-50.
Sometimes I want to determine what tile is at a location. One (imho bad) way of doing this would be to get the x/y and loop through all tiles and check if they are that location.
The way I'm currently doing it is to have a seperate 2d array of null elements, and when a tile is added, its set at that array. (ie tilemap[10][10] = tile[100])
Of course, because the values can go negative, tilemap [0][0] is actually the -1000/-1000 tile. (chosen as an arbitrary limit)
Is there a better way of doing this? I feel like using a massive array of mostly empty objects could be more optimal.
Many thanks.
One possible solution would be to keep an Object or Dictionary where the key is the x/y location.
So if you're adding a tile at 10,20, you can store it in the Object like:
this.m_objs[tileX + "_" + tileY] = new Tile;
So if you want to check if something's at position 10,20 you can by using something like:
public function checkIfExists( x:int, y:int ):void
{
return ( this.m_objs[x + "_" + y] != undefined );
}
I recomend using Dictionary, as searching in it much more faster then searching array. Judhing by possible coords -1000/-1000 it would be a great advantage!

Recognizing tetris pieces in C

I have to make an application that recognizes inside an black and white image a piece of tetris given by the user. I read the image to analyze into an array.
How can I do something like this using C?
Assuming that you already loaded the images into arrays, what about using regular expressions?
You don't need exact shape matching but approximately, so why not give it a try!
Edit: I downloaded your doc file. You must identify a random pattern among random figures on a 2D array so regex isn't suitable for this problem, lets say that's the bad news. The good news is that your homework is not exactly image processing, and it's much easier.
It's your homework so I won't create the code for you but I can give you directions.
You need a routine that can create a new piece from the original pattern/piece rotated. (note: with piece I mean the 4x4 square - all the cells of it)
You need a routine that checks if a piece matches an area from the 2D image at position x,y - the matching area would have corners (x-2, y-2, x+1, y+1).
You search by checking every image position (x,y) for a match.
Since you must use parallelism you can create 4 threads and assign to each thread a different rotation to search.
You might not want to implement that from scratch (unless required, of course) ... I'd recommend looking for a suitable library. I've heard that OpenCV is good, but never done any work with machine vision myself so I haven't tested it.
Search for connected components (i.e. using depth-first search; you might want to avoid recursion if efficiency is an issue; use your own stack instead). The largest connected component should be your tetris piece. You can then further analyze it (using the shape, the size or some kind of border description)
Looking at the shapes given for tetris pieces in Wikipedia, called "I,J,L,O,S,T,Z", it seems that the ratios of the sides of the bounding box (easy to find given a binary image and C) reveal whether you have I (4:1) or O (1:1); the other shapes are 2:3.
To detect which of the remaining shapes you have (J,L,S,T, or Z), it looks like you could collect the length and position of the shape's edges that fall on the bounding box's edges. Thus, T would show 3 and 1 along the 3-sides, and 1 and 1 along the 2 sides. Keeping track of the positions helps distinguish J from L, S from Z.

Resources