Quick screen grab from my first big project, more details coming soon!
Follow the learning and progress of a waiter who wants to make games. Java, Android and Game Development. Includes code snippets, book reviews and recommendations, game analysis and concept sketches!
Tuesday, 12 January 2016
Monday, 14 September 2015
Making Audio go private
Today I have been working on getting my Audio system implemented, mostly in order to keep the Activity Lifecycle happy- ie ensuring that media is paused, resumed and released appropriately. The initial implementation I made was an Audio class which was built up of static methods, each able to do a specific function, and if necessary call each other to use pre-existing functionality. The class worked, and is in a small project not a bad model, but I have been reading up on ways to setup a game View and it seems that the Audio class needs to be less public.
Honestly, my first reason for making methods static was that I read that using getters and setters was potentially heavy on resources, but in further reading I have found that for my audio needs this won't be an issue.
The main root of my game framework is now a base activity which is able to create and switch between views, the views themselves after a little experimentation are now extensions of the SurfaceView, and are able to take a pre-initialised Audio instance as a parameter. What this does is allow the main activity to set up the audio environment in one place, passing in itself for context rather than having the Audio being setup in the beginning of a new "screen".
The audio environment is now also much more encapsulated, and as such should only be passed to one screen and any reference will be lost as that screen dies. The activity itself can also ensure that the correct settings are in place for the audio-stream, should the app framework be used for other app types.
The project I have been working on is a soundboard which emulates the character select screen of Mortal Kombat 3, a childhood favourite of mine. So far I have been able to load the 15 game characters names and corresponding "introduction" speech files from the game, and I have it set up to play a random one from this list and display the name on each touch event.
The names themselves exist in an array which is organised in the order that the game presents them on the screen, however it may be necessary at a later date to have them sorted alphabetically- which we will do if needed. One string array (in the strings.xml resource) holds these names, and another array holds the filenames for the audio files in the same order. The reason I have kept the two seperate instead of trying to parse one array into an audio filename, is that I am able to localize the name strings and they will still line up with the sound files whose names are written in english. While the game characters names are the same in any language, it may not be the same in character based languages, and if I ever work on supporting those it would be great to not have to rewrite my audio file loading.
There are probably many other ways to link the names in an array to specific sound files but for now this seems to be the simplest and works well for this project.
The next step will be to load in a music track to loop in the background and then I can begin working on graphics!
Monday, 7 September 2015
MediaPlayer experiments
My experiments with the media player began with finding a question on the learnandroid subreddit, which asked about pausing media with a touchevent. From my reading I could see that the poster had not prepared the media track after stopping it, something which is unique to that circumstance but not the pause method. The poster also had a bit of confusion about the touch event itself and where to trigger the media playing. After posting a quick suggestion I decided that I should try to implement a music player in a test app too to get to grips with the little things that might be confusing for a beginner.
Following on from my blank screen SurfaceView test, I used VLC to convert a ripped mp3 into the OGGVorbis format with reduced sound quality (to save on memory) and added that into a new assets folder. From my previous experiemnts with Soundpool (An app with pikachu on it that says pikachu when you touch the screen, and plays a computer booting up sfx from pokemon firered on launch), I knew that sound files can be retrieved using the AssetManager in android. I made the first mistake in not putting the new directory in the right place in the file structure, but that didn't become apparent until it was fully set up.
My first set up was to have all of the media player implemented in the SurfaceView class itself, which is a Runnable in a class called Screen. The implementation included instantiating an asset manager, trying to get the file i wanted an AssetFileDescriptor which I could pass into a new instance of MediaPlayer. The process itself was all set up and the data source set and media started, but the app itself didn't work. After adding some Log notes and an exception message for the try-catch block I found that the asset manager wasn't retrieving the files in the folder, and looked back to my original pikachu app to find the structure difference.
Once the file was able to load and play I ran the app and lo and behold, the music played, (Nine Inchnails- Satellites for those who need to know!). I was elated, then I closed the app and hmm.. still music.
I knew this had something to do with releasing the resources and the activity life cycle so I started to look there for ways to control my music. I started with onStop, onPause and onResume methods inside my SurfaceView which were called from the main activity, and implemented checks for if the media player was valid and playing etc, and stopped the music and restarted it as I expected. This did not work. The app was happy enough to stop the music but not to restart it when the app was loaded up again. I understood that the app was saved in temporary memory when the app was minimized or obscured, so the app was going through the onPause method, but I didn't realize the onStop method was being called also!
Going back I was able to debug my app and place appropriate boolean flags to control the music playing. In the onPause method, the music is (if it is not already) paused, and on resume the music is (if not null such as on initial bootup of the app) started again. The call to onStop was moved into an if block which checked that the app was not being closed fully (isFinishing()) and if so, stopped playback and also released the media player.
With my experiment finally performing the way I wanted it to, I was finally able to begin abstracting the audio into a seperate class. I created an Audio class that could handle music using static methods, which would mean it is accessible throughout my app. Instead of using a default constructor to set up the Audio environment, I opted instead to use static methods that only initialize variables if they are going to be used. I currently have a method that is needed to pass in a context for use in attaining the assets, but later on I will access this statically from a core class that handles the game.
The Audio class also has onPause, onResume and onStop methods which can be called to ensure that any active media, be it sound FX from the soundPool or music from MediaPlayer are paused and resumed correctly, and destroyed on closing the app.
I am really quite happy with the progress I am making in understanding these (albeit simple) aspects of app development. I want to be able to say not only that I understand the theory, but that I can put code on paper to describe the processes and show that I understand the way these systems work together on a more holistic level.
The code for my Audio and Screen app are linked below for viewing.
MainActivity Class
Audio Class
SurfaceView Class
Thursday, 27 August 2015
Return to Game Development
While working through the examples, I have been playing around with the code and finding out the OTHER methods that some of the classes do. While I had made a game on Android following a "For Dummies" book in the past, this time I actually understand the process, the effect that the Activity Life Cycle has, and can see where the ideas I have fit into the code.
To help me keep notes and have an "in my own words" reference, I have been typing up notes into Google Keep, an app I have had on my phone for a long time and rarely used. Being able to type quickly has always prevented me from note-taking on my phone. I am a terrible touch screen typist! Using the in-browser version of Google Keep has been a lifesaver- actual keyboard typing, and sync to my phone for on the go note revision. I have found myself memorizing key concepts quicker with these notes, and can now comfortably say that an extremely basic framework in a regular View can flow pretty quickly from my fingers. I do enjoy making notes and even updating them to make them more precise, but I can't always be at my laptop- for this reason I have contemplated buying a bluetooth for a while. (I have planned to buy a tablet for myself for quite a while now and really wanted a keyboard for it- so I have been watching Amazon and Bestbuy for a deal daily!) I finally ordered myself a keyboard last night, and hopefully that gives me more opportunities to be productive- either in writing up ideas, taking notes or coding when I am not limited by the amount of time I can comfortably sit at the computer.
As an example of the notes I have been keeping, here is my first entry!
Soundpool is a RAM based storage for small soundFX files, ideally in .ogg format and shorter than about 5 seconds. Setting up a SoundPool requires the parameters indicating how many sounds can play simultaneously (20 is a good default), which sound stream is being used (AudioManager.STREAM_MUSIC for media of any type), and a final unused parameter, default 0.
SoundPool sp = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
The SoundPool default constructor has been deprecated with the release of Lollipop, and now utilises a Builder for instantiating a SoundPool object.
SoundPool sp = SoundPool.Builder()
.setUsage(audioAttributes)
.setStream()
.build();
To load a soundFX file to the Pool, you have to get an AssetFileDescriptor from the Asset file.
AssetManager assetManager = context.getAssets();
AssetFileDescriptor asset1 = assetManager.openFD("dir/filename.extension");
When adding the descriptor to the soundpool, it will return an integer which identifies the sound loaded, which can be used as a parameter later. It is vital therefore that any files loaded be done so in an integer expression. the load method itself will take in the AssetFileDescriptor and a sound priority int as parameters. The sound priority is currently unused as is default as 1 (similar I guess to the weight attribute in xml layouts, having them all at 1 gives uniform importance).
int asset1IdNum = sp.load(asset1, 1);
This asset can later be played using the SoundPool instance, by referencing the identifier for the resource, as well as some other parameters.
sp.play(identifierInt, float leftChannelVolume, float rightChannelVolume, int priority, int looping, float playbackSpeed)
The channelVolume parameters allow a sound to be set on one ear or the other. The priority again is unused and is defaulted to 0. Looping is often not a good idea for a sound effect and is thus set to 0, and playback speed will be 1 by default, less for slow play and more for fast playback.
When all use of the SoundPool is done, it is best practice to release the resources directly by using either specific calls to soundPool.unload(identifierInt) or to all resources using soundPool.release();
I have made notes on MusicStream, working with the View and onDraw() method (invalidating as a method of continuous graphics rendering), setting the application to keep the screen on, go fullscreen and hide the notification bar and working in SurfaceView and Threads.
I'm hoping that my notes will not only enable me to retain information better, but also that they may help me to guide others if they ask me for advice on starting on a similar path!
There are notes I have to include after todays coding to describe how to set a listener for loading files, as I wanted to have a specific sound effect play as my testing app opens (computer booting up sound effect from a monster catching game you may have heard of!)
Sunday, 28 June 2015
A bit of background
Self learning ain't easy
- Codecademy: My first look at coding was the Javascript track which I began playing with just from curiosity. While this is not the best track to learn programming, at the time this was the only one available. Ruby and Python came later with redesigned tracks to support the programming route as a whole.
- CS106A Stanford Programming Methodology: Lectures by Professor Mehran Sahami
This series of lectures is available on Youtube and has assignment material available via the Stanford website. This course first introduced me to Java with Karel, the little robot. - Java - An introduction to Problem Solving and Programming: Walter Savitch (5th Edition)
This textbook was donated to me by a work colleague who had taken the course as part of her university education but had no interest in pursuing it further. The book helped me to move away from the safe environment of Stanford's custom Java work space and onto making my own applications within Eclipse. I am currently using Eclipse Luna version 4.4.1 - TheCherno: Youtube Game Programming series
This series was a love/hate one, I enjoyed the coding and following along with a project and being able to tinker was very fun, but I think while the aim was for newer programmers to use this series as an introduction to game programming, it sometimes left me wondering what the heck I was doing. I stopped following this series after about 60 episodes but it definitely contributed to inspiring my continuation of studies. - After a period of stagnation and loss of direction, I finally found Head First Java, which took a couple of attempts for me to work with. At first I found the quirky sense of humor to be annoying and tired of it. It took another couple of months before I gave it another try (following some reddit advice) and got through my brick wall.
Simulations
Starting simulation: Number of Combatants per army = 500
Ending simulation: Number of Skirmishes = 2806
Time taken: 0.279sec
Moving forward
My intention with this blog is to create a place for new programmers to look to see my trials and tribulations. If anyone can gather any knowledge, resources or inspiration from me then this blog will have served a purpose. For my own needs, I want to use this as a place to summarize my studies, hold myself accountable, and also to see where I was at a particular stage of my journey. Please feel free to get in touch if you have any questions or comments. Thanks for reading!Saturday, 22 November 2014
Github, the Git and The Table State
While unfinished work is probably the biggest time waste for many programmers, I have taken the view that any time spent working on my project is constructive. Any ideas that make it into the program are successes and the failed ones are lessons.
So, this week I have been working a lot IRL so my time has been spent planning the Table Service aspect of my game. Working with time in Java was an initial hurdle but didn't require too much googling to ensure I was getting the numbers I needed in the format that worked for me. Each guest will be able to generate a set of times which state how long an aspect of their stay will take. John might take two minutes to eat, but Sally might take twenty five. Using this knowledge, the game is able to check for an "all ready" like state, by comparing the state of each guest and acting when all of them match. Using this system requires a set of enum types for the Guest and also for the Table to use as state markers which can be looked at by the other Entities. States in this way happen to be far more effective for the long list of possible states than boolean values had been, as rather than turning one value to true and another to false, the overall state simply switches. This makes a list of instructions much more safe to run as the state can only be one at a time, and no accidentally crosslined booleans will throw me off.
if(!isActive){
return;
}
elapsedTime = timeSat + System.currentTimeMillis();
if(state == guestState.sat){
if(startOrderTimer <= 0) startOrderTimer = System.currentTimeMillis();
if(startDrinkOrderTimer <= 0){
startDrinkOrderTimer = System.currentTimeMillis();
}
if(System.currentTimeMillis() - startDrinkOrderTimer > drinkOrderTime){
state = guestState.drinkOrderReady;
}
} else {
return;
}
if(state == guestState.drinkOrderReady){
// when Orders system implemented, fill in order creation here
}
if(state == guestState.drinkOrderTaken){
if(startOrderTimer <= 0){
startOrderTimer = System.currentTimeMillis();
}
if(System.currentTimeMillis() - startOrderTimer >= orderTime){
state = guestState.foodOrderReady;
}
}
In this early example of a guests update method you can see that the state is modified when criteria are met such as an elapsed time and manage progression through a typical service by acting as flags that the table can look for in each guest to create a Task that can then be acted upon by a Staff entity.The table itself is able to scan through any number of occupying guests in order to check that all guests are in the same state, as shown here.
private void getGuestStates() {
if(guests[0].getState() == guestState.sat){
return;
}
Guest.guestState[] states = new Guest.guestState[guests.length];
for (int i = 0; i < guests.length; i++) {
states[i] = guests[i].getState();
}
Guest.guestState temp1 = guests[0].getState();
for (Guest.guestState state : states) {
Guest.guestState temp = state;
if (temp1 == temp) {
temp1 = temp;
} else {
return;
}
System.out.println("Table has determined that all guests' states match: " + state);
}
}
The initial state of guestState.sat will progress from within the Guest so if this state is in place then we save cpu time by exiting the getGuestStates() method. Checking against a fixed array index guests[0] is not a problem as a guests array is not able to have fewer than 1 entry, as 1 is the minimum number of guests in a group (which seems redundant to have a group of 1, but this is simply a container for the guests to proceed into the restaurant queuing system).Once the basic framework for the states is finished I will make all new table placeholder sprites to help show the state visually. This may be a layered approach using the base table and then an "items on table" type layer such as is used in RPGMaker, but that will come in its own time. I have 3 days booked off this coming week and hope to spend a good chunk of them coding. Until then!
Sunday, 16 November 2014
Mouse Input and UI Ideas
An issue I was having was that as the update method for each table is run at 60 Updates per second, the actions taken when the mouse is clicked were also happening 60 times. To avoid this I added a clickLock, which disables a table from being clicked again for a second. The update method then decreases the lock each cycle until it hits zero.
if(Mouse.getButton() == 1 && clickLock <= 0){
if(Mouse.getX() + Screen.getxOffset() >= x
&& Mouse.getX() + Screen.getxOffset() < x + sprite.SIZE
&& Mouse.getY() + Screen.getyOffset() >= y
&& Mouse.getY() + Screen.getyOffset() < y + sprite.SIZE){
timer += 300;
clickLock += 60;
}
} This snippet is my way of debug adding a state change to the table that is clicked. At the moment the tables update based on an increment per update and switched based on time passed in this manner. In future the tables cycle will update state based on the time and the personal preferences of the guests.
Each guest will be created with a set of randomly generated times such as how long it takes them to make an order, to eat and any "sitting and chilling" time after the service ends. These numbers will create some variation between tables as they will not all sit and end in a predictable pattern. If your group consists of two guests and one takes longer to order, they will both have to wait for an order to be placed. If you have a table of four people and they all decide quickly, the amount of time before an order can be made could be much shorter. In many games based on "cafe" or "restaurant" settings, the guests are very copy paste and fall into guest "types". I would rather have a guest be defined by their own set of preferences and also variables such as cash on hand and time available. A guest who is trying to get a quick bite should be seen to be ordering, eating and leaving quicker than a guest who is in for a social meal.
![]() |
| My noteboook, ideas on UI and button themes |
Thursday, 13 November 2014
Thinking about input
My game design is based on creating a world as interactive as Rollercoaster Tycoon was, with access to menus to control prices, individual guest dialogs, construction and also access to things like staff lists and skills. The restaurant world is not necessarily a fun environment that people aspire to be a part of from afar, in all fairness it is a stressful and tiresome, but managing one and having influence on design, staffing and item names etc will make the experience more engaging.
While the player controlled aspects of the game will ultimately be on the simpler, more holistic side, I would like to have a much beefier simulation running under the hood that advanced players can tap into at will, without having it interfere too much with the core gameplay. The game will hopefully be a good blend of time-management style point and click gameplay, with a rich economic engine that doesn't bog it all down. I have picked up a small notebook for writing down ideas on the go, whenever possible I will try to add pagescans so that you can see my thought processes and doodles!
Tuesday, 11 November 2014
Implementing graphics
The next step involved creating a "map" from pixels, where the colors represented tiles of different types that the program could read in and create the full map from. Using hexadecimal colors and a small (64px X 64px) "map", I was able to feed this into the level loader and move around the screen with the avatar. Lining my tables up was a second issue which meant I had to rethink and refactor my code to take the tables from an Array and build an Arraylist instead. Once the level loader read my map and encountered a "table" tile, it added a new Table instance to my ArrayList and set its x and y variables to match the tile.
Here the dark lines represent walls and the orange pixels are Tables
Wednesday, 5 November 2014
Helping the binman out
Luckily there are some great summaries of the Java garbage collector that didnt get too science heavy for me. When a reference to a variable is lost, either through scope, reassignment or to lack of use, Java checks the programs memory for any variables or methods that may still have access to that memory address. Those suffering from abandonment are removed from memory by a low priority thread in the jvm. My problem was then, are my guests being deleted when they leave or were they living on. In order to figure it out I had to have my guest class increment a static counter each time its Constructor was called, and my Hostess class keep a tab on the number of guests at active tables. The first revelation found was that the hostess was creating groups even when the queue was full, and discarding them when they were rejected. While this wouldnt have been a huge memory problem, it was a simple fix to ensure the groupGenerator was not called unless the queue had room for more groups. After that I went about cutting ties to any groups that were done eating and had 'paid'. To do this I created a method in the Guest class to null any modified variables. This method was probably overkill! After any guests were gutted, the Group itself breaks ties with the Guest array, and the table breaks ties with the Group by disbanding. While any performance changes are probably negligible, it was good to think about the data being stored and how I want any large objects to kill their data before disconnecting from use in the game.
Monday, 3 November 2014
Working with the Hostess, queues and delta time
Tuesday, 13 May 2014
Design Concept Notebook
After reading an interesting post via reddit recently, i started defining my game concept in terms of its main mechanic, secondary mechanics and the progression which will dictate my games direction. Thinking about my game idea in this way helped me to understand where I needed to concentrate in order to make an experience fun and engaging. As a simulation, I originally wanted the program to not even be about fun, but rather a realistic representation of a restaurant. An exercise in designing and implementing an eco-system, where input is random but the outputs represent the realities of a small business.
The future may lead to me implementing more features from this original vein, but narrowing the scope is for now a better route for me to see through and finish the project.
Today I have been working on writing up a description of the main view, what a "level" should look like and what is interactive. The game will be at first a player directed "time management" style game. Think Diner Dash or Barrr. As I learn more about programming I'd like to be able to implement an automatic mode where the agents are able to act independently, allowing the player to switch between agents.
I'll be working on my own art for the game so I've been doodling little sketches, which help me to think about the way I want to implement things such as menus, game state indicators and of course the layout and style of art.
Next step, continue learning from the Cherno and get a Level up and running, and put some alpha art tiles in this blog!





