Tag: java

Game development in progress: Space Invaders clone – update 2

Earlier this year I started developing a Space Invaders inspired game for Android. I started back in March, and have worked on it for a around 20 to 30 hours or so, on and off. Not being an expert in Android development or game development in general, it’s been a learning experience. The book I read back in March, Android Game Development by Example, was a good book to get started. I realize I probably could have got to a playable game quicker if I’d used a game development platform like Unity3d, but I wanted to get to grips with writing a game by from the ground up first. I’ll circle back and probably rewrite it using something like Unity later.

Right now I’m at a point where it’s playable but there’s a few key features I still need to add, like the bases/shields at the bottom of the screen, and the invaders need to shoot missiles at the player. It’s a pretty easy game at this point 🙂 I have a few ideas for some gameplay variations to add too.

I started implementing as a standalone Java app using the Java2d api and the 2d game engine that I’d previously worked on for my first attempt at a game in Java, a version of one of the classic Nintendo Game n Watch games, Turtle Bridge.

I tried to replicate the animation of the invaders moving one at a time, one row at a time and got pretty close:

Compared to current day AAA tier video game development projects which typically have multi-million dollar budgets and teams of artists, story writers, sound engineers, QA, developers, as well as marketing and PR teams, I find it fascinating that Space Invaders was originally developed by a single developer, Tomohiro Nishikado. Not only did he develop the sofware for the game, but he also designed the hardware on which the game runs.

There’s some interesting features of the game that were not part of the original design, but resulted from limitations of the hardware. For example, the invaders speed up as fewer are left remaining on the screen. This is a defining feature of the game, but was a side effect from the 8080 processor being unable to animate a full screen of invaders at the same speed compared to a screen with only 1 or 2 remaining. Rather compensate in software to keep a constant frame rate, this feature was kept.

Other features in the game play logic could easily be overlooked by a casual player:

  • The mystery ship appears on a regular, timed basis, at around each 25 seconds
  • The mystery ship is worth 300 points on the first 23rd shot on each screen, and then 300 on every 15th shot for the remainder of the screen. For all other shots it’s 100 points (if you play for high scores, then this fact is probably very well known to you 🙂 )
  • Missiles from the invaders will not kill the player if fired from the last row on the screen

Here’s a quick video of how far I’ve got so far. This is running on a device simulator, so the frame rate is not as fast as on a real device:

I’ve still got some work to do, but I’m pleased on my progress so far.

Android development: drawing text on a Canvas

I have an Android project bubbling away. More details soon 🙂

I’m using a SurfaceView and needed to draw some text on it. The rest of the app is mostly drawing on the SurfaceView Canvas directly, but I need some text too.

I’ve dabbled with some Android development before, and I have to admit getting the layouts to do what you want them too almost seems to suck up the majority of my development time 🙁 This time round I got sidetracked trying to create a layout that was using a mix of TextView elements and adding my SurfaceView programmatically. This didn’t go too well, didn’t work at all, so I found a few posts like this, and worked out you need to draw directly on the canvas. Something like this does the job:

Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
this.canvas.drawText("Hello world!", 20,50, textPaint);

This code is in the middle of a game display loop, but for completeness, to be able to draw to the Canvas first you need:

SurfaceHolder surfaceHolder = this.getHolder();
if (surfaceHolder.getSurface().isValid()) {
    this.canvas = surfaceHolder.lockCanvas();
   ...
}

And then to release the Canvas after you’ve finished drawing:

this.surfaceHolder.unlockCanvasAndPost(this.canvas);

 

Ok, next up, what about custom TTF fonts? Drop the TTF font you want to use in your assets/fonts folder, and then load it up with:

Typeface typeFace = Typeface.createFromAsset(this.context.getAssets(), 
    "fonts/yourfont.ttf");

To use this font with the text snippet above, just call setTypeface() and pass it in:

textPaint.setTypeface(this.typeFace);

Ok, how about specifying a font size that’s proportional to the resolution of the user’s screen? This is an interesting question. To avoid using fixed pixel size fonts and then having them not scale appropriately for different devices with different screen resolutions, Android uses a concept called ‘scale independent pixels’, or SP. This is described in this post here. In short, defines an SP value in /res/values/dimens.xml/dimens.xml like:

<dimen name="scoreFontSize">20sp</dimen>

And then reference and set it like this:

int fontSize = getResources().getDimensionPixelSize(R.dimen.scoreFontSize);
textPaint.setTextSize(fontSize);

Done! (I’ll share more on what I’m working on in a few days 🙂

Can you develop code to effectively solve a problem without understanding the problem first?

You shouldn’t have to think too hard to answer this question. In order of most likely answer first, least likely last (I hope), your answer could be one of:

a) No. How can you solve a problem if you don’t understand what it is that you’re trying to solve?

b) Possibly, if your approach to solving a vague or poorly defined problem is to ask clarifying/fact finding questions to investigate and gain an understanding of the problem so you can get to a position where you’re able to solve the problem.

c) Yes. (Really?)

There’s no correct answer to this question although I hope you initially answered (a), but (b) is a valid possibility if you consider the effort to understand a problem is an essential part of solving a problem (which of course it is).

I decided I would have a go at writing a Java app to solve Sudoku puzzles. I’m familiar with the rules of Sudoku and have solved a few puzzles by hand. I’m not an expert by any means, but I know enough about this type of puzzle to realize there’s probably at least a few well understood algorithms for effectively solving them, but as I started out I wasn’t familiar with any particular approach.

So here’s my experiment: I decided I would deliberately avoid doing any background reading on known algorithms or reading any articles or discussions on approaches for how to solve, and would attempt to blindly develop my own approach to solve a puzzle to see how successful (or otherwise) I would be. I know the rules to the puzzle, I understand what the end result must be, so how hard can it be, right?

For those unfamiliar with Sudoku, here’s the 3 rules:

  • each 3×3 square must contain each digit 1 through 9 with no repeated values
  • each column must also contain each digit 1 through 9 with no repeated values
  • and the same rule for each row, 1 through 9, with no repeated values

Here’s my starting puzzle that I used to write my code against:

      | 8 1   | 6 7   
    7 | 4 9   | 2   8 
  6   |   5   | 1   4 
- - - + - - - + - - -
1     |     3 | 9     
4     |   8   |     7 
    6 | 9     |     3 
- - - + - - - + - - -
9   2 |   3   |   6   
6   1 |   7 4 | 3     
  3 4 |   6 9 |       

(Puzzle generated by WebSoduku)

My initial approach for my algorithm was to follow the steps I would go through by hand if I were solve a puzzle on paper. This already set me off at a disadvantage because I don’t think I’m particularly skilled or experienced at solving Sudoku, so I wasted some hours trying to capture these steps in code. Going down this path I realized if you take this approach, you mentally ask several questions as you look for possible values for empty squares, but it’s not not the answer to any one of questions that gets you a correct answer, it’s the combination of answers to multiple questions (because there’s 3 constraints, above, that you need to follow). So following this approach, I wrote code to iterate through the complete grid applying my limited set of questions to find potential values for each empty cell. The result was after a couple of iterations I had inserted values into all empty cells as sets of potential values, but my approach was not complete enough to be able to solve the example puzzle I was using for testing.

This was my point of realization. Clearly I did not understand enough about the problem to be able to write a problem to solve it.

After some debugging and tweaking to my approach, I did reach a point where I could solve my test puzzle in 7 passes through the grid, but when testing the same approach with another easy puzzle, my approach failed to reach a solution. So my approach only partially works when I have a starting point with enough values, or a certain distribution through the grid, but fails to solve all puzzles.

At this point I could have continued blindly in the same direction, but I decided I had already proved to myself my point that you can’t solve a problem if you don’t understand what it is that you’re trying to solve. It was time to read up on the the established algorithms to solving, so I could understand what it was that I was missing.

There are a number of established algorithms for solving Sudoku, and I won’t describe or cover them all there, but there’s a good summary on this wikipedia page. The approaches range from brute force (sequentially testing each value 1 through 9 in each cell, with backtracking to prior cells if chosen values fail to find a solution, to variations such as Donald Knuth’s Dancing Links algorithm.

My conclusion to my original question though is clear: had I recognized the problem as an example of an exact cover problem, I would have known that there are established algorithms for solving this type of problem.

You can’t solve a problem if you don’t understand what it is that you’re trying to solve.

If you’re interested in taking a look at my partial solution you can find it here on my Github.

JavaOne 2016: Oracle’s ‘refocusing’ of the EE8 proposal

Oracle’s planned Java EE ‘announcement‘ at JavaOne 2016 turned out to be (based on the announcement from the Sunday keynote and the Java EE 8 roadmap session by Linda Demichiel, EE spec lead for EE JSRs) a ‘refocusing’, a realignment to bring Java EE more in line with current trends, particularly to support deploying EE applications to the cloud and the development of microservices.

So what exactly is going to change? For the new EE8 spec proposal, with finalization now planned for 2017,  some previously proposed features for inclusion are now going to be dropped, namely:

  • MVC 1.0
  • JMS 2.1
  • EE Management apis 2.0

Given than MVC 1.0 was a new EE web framework as an alternative to JSF (not adding new technology but built on top of what we already have with a Reference Implementation already built out), this is perhaps the most surprising removal. Given the new focus of cloud and microservices however, this makes sense, as it doesn’t really add anything towards supporting the new goals.

Everything else in the original EE8 JSR 366 is going to remain in the new EE8 proposal.

New features to be added include a new feature for supporting Health Checks, and a new Configuration proposal to standardize external configuration of deployments – both of which will be useful to support deployments to the cloud.

Is this ‘refocusing’ enough? Is it going to be finalized soon enough? For an EE8 target of 2017, and EE9 of 2018, is it too little, too late?

Given that you can use current EE features today with frameworks like Spring Boot and Dropwizard to build and deploy microservices, is a standardized cloud/microservice focused EE platform still relevant?

Alternative runtimes like WildFly Swarm and IBM’s Liberty Profile are giving runtime flexibility and allow you to pick just the features your app needs at runtime (and are available today). Rather than an all-in-one EE runtime container, is a ‘pick n mix’ type approach more relevant to support the current popularity of microservices?

Notes from Raspberry Pi with Java 9 session – CON6210 – JavaOne 2016

A few interesting notes from the Java 9 Embedded on Raspberry Pi, session CON6210, presented by Stephen Chin.

Currently streaming live on YouTube: https://www.youtube.com/watch?v=v95y5CzvcZ4&feature=youtu.be

Full live stream schedule is here: https://community.oracle.com/docs/DOC-1005786

  • SE9 Embedded will be available in a ARM build for the Raspberry Pi
  • This ARM specific build will only be available for Pi 2 and 3 (not the original Pi 1 A/B and + models, as it’s been compiled for ARM Thumb-2 instructions, and these are only supported on Pi 2 ARM CPU and above
  • AWT, Swing and JavaFX will all be supported on SE9 Embedded on the Pi
  • Interesting side note about modular Jigsaw in SE9 – apparently the module file packaging and compression is moving away from zip based Jars, to another format that’s more efficient for class lookup/retrieval

Oracle have something to announce re. Java EE 8 at JavaOne this year?

Oracle have been quiet on the Java EE front since around November 2015 according to public minutes from recent JCP Executive Committee meetings,  which has led to the forming of the Java EE Guardians group forming to rally community awareness and promote the future of Java EE.

This story on The Register just popped up in my feed this evening, with an interesting quote from ‘Oracle spokesman’ Mike Moeller, stating:

“Oracle is committed to Java and has a very well defined proposal for the next version of the Java EE specification – Java EE 8 – that will support developers as they seek to build new applications that are designed using micro-services on large-scale distributed computing and container-based environments on the Cloud … Oracle is working closely with key partners in the Java community to finalize the proposal and will share the full details with the broader Java community at JavaOne in September.”

So there you go. Given that there is already an EE8 JSR in flight (JSR 366) encompassing many other JSRs that were planned to be included in EE8, this statement sounds suspiciously like Oracle has “something else” planned for EE8 that is not the EE8 JSR (“a very well defined proposal for the next version of the Java EE specification”).

In a thread on the Java EE Guardians Google Group, seems like no-one over there has any other insight into this news at this point.

Interestingly, microservices, large-scale distributed computing and containers… this is all very much on target for where EE needs to be heading.

If this is all Oracle is willing (or able) to share at this point, then it will definitely be interesting to hear what they have to share at this year’s JavaOne conference.

MongoDB Java api: using a sequence collection with findAndModify()

MongoDB doesn’t have an equivalent of sequences typically used in relational databases, since documents are automatically given a unique ObjectId value for the “_id” property when inserted.

To return data from documents via a REST api, it may be more useful to use a sequential unique key. The MongoDB docs have an example of how you could use a Collection to hold a document per sequence that you need, and increment a value property each time you retrieve it with findAndModify().

There’s a number of questions on StackOverflow related to this approach, most seem related to the approach doc linked above (e.g. here, here, and articles elsewhere, like here).

To implement this approach using the Java api, using findAndModify() seems to be key, as you need to ensure you are querying and incrementing the sequence value in a document in a single, atomic step. After that point once you have the updated/next value from your document holding your sequence, the fact that you use that value in a subsequent atomic insert to another document seems to be safe (please leave me a comment if this assumption is not correct!), as every call to findAndModify() to increment the sequence value is atomic (making an assumption here based on my limited MongoDB knowledge, but I think this is correct!).

Here’s how I implemented the approach using the Java api:

public int getNextSequence() throws Exception {
    DB db = MongoConnection.getMongoDB();

    DBCollection sequences = db.getCollection("sequences");

    // fields to return
    DBObject fields = BasicDBObjectBuilder.start()
        .append("_id", 1)
        .append("value", 1).get();
		
    DBObject result = sequences.findAndModify(
      new BasicDBObject("_id", "addressId"), //query 
      fields, // what fields to return
      null, // no sorting
      false, //we don't remove selected document
      new BasicDBObject("$inc", new BasicDBObject("value", 1)), //increment value
      true, //true = return modified document
      true); //true = upsert, insert if no matching document

      return (int)result.get("value");
}

 

The future of Java EE as discussed at recent JCP Executive Committee meetings

If you’ve been following Java EE related news over the past few months, you’ll know that Oracle cut back on a number of its Java Evangelist employees, others such as Reza Rahman appear to have left of their own accord, and there’s a general concern than Oracle appears to have slowed down input on any Java EE JSR. Rahman has formed a group called the Java EE Guardians to drive community activity to support future development of Java EE and EE JSRs.

If you want more of an inside view to what’s going on, there’s some interesting reading in the form of the JCP Executive Committee meeting minutes which are public record. The minutes for June 2016 and May 2016 both had agenda items to discuss the future of Java EE. The minutes from the May meeting are very interesting, including comments such as :

“…concern that Oracle, despite its role as steward of Java, has not made any public statements or explanations for the apparent lack of activity on Java EE”

and recording of a statement to Oracle from the JCP Executive Committee formally voicing their concern:

“EC members expressed their serious concerns about the lack of progress on Java EE. They believe that Java EE is critical to the Java ecosystem and to their organizations and customers. They fully accept Oracle’s right to direct its investment where it wishes, but expressed the hope that they and other members of the Java community be permitted to step in and help with the ongoing development of the platform, particularly in areas where Oracle wishes to reduce its investment. They therefore requested a dialog with Oracle about how to make such a transition.”

Other concern recorded in the minutes was that Oracle holds IP rights for the majority of the JSRs that are in progress, and so passing responsibility on to other parties requires Oracle’s involvement to pass on ownership of this IP… something which they may agree to, or may not.

Minutes from April 2016 note:

“Martijn Verburg reported on behalf of the London Java Community that it now seems clear that little if any progress is being made on Oracle-led Java EE JSRs. (Some Oracle Spec Leads have admitted publicly that they are unable to spend any time on their JSRs, having been directed to work elsewhere.) He estimated that work on Java EE seems to have stopped around November 2015.”

So, it’s clear there is industry concern that Oracle has backed off from involvement with development of JSRs for Java EE8. The question is, what happens now?

Lightweight docker images for Java apps

There’s a number of posts (e.g. here) talking about the official Java docker images being on the large side – in Docker terms, the standard images at > 600MB before you even build your image containing you app are … pretty big.

Suggestions are to use a smaller image as a starting point, like Alpine Linux. It looks like at some point the official Java images have been updates to include a number of Alpine based images too.

Pulling down an OpenJDK 8 image, java:openjdk-8-jdk and then java:openjdk-8-alpine, there’s a massive size difference between the size of the two:

If you’re planning on running something lightweight like a Spring Boot app, looks like the provided Alpine images are a good starting point.