Thursday, 18 June 2015

What Google Does Well and NOT!



I recently got a Nexus 6 phone. Set aside my very low end Windows 8 Phone and decided to give Google a Whirl. Well the Nexus 6 is more of a tablet than a phone. Now Google is king of the web to be sure with the most dominant search engine they rule data and revenue. But they do not do appear to do Mobile well.
My impression after week 1 is that Windows 8 Phones for me are better integrated with the functionality of the phone and business functionality of apps also.
Also I notice a lot of negative reviews on the apps that I want to use especially those that manage contacts and groups in particular. Contacts should be should be managed as contacts on the phone itself rather in the Google or Outlook contacts stored in the cloud.
Bluetooth is proving particularly problematic both in terms of management of in car hands free functionality and connectivity.
All this maybe attributable to the hardware or software incompatibility but I have tried the Nexus with a Nokia built in Bluetooth hands free kit and a Parrot plug and go product and it needs constant attention which is not desirable when you are driving. So you never know how it is going to behave. The “Ok Google” function does not recognise half of what I say either which adds to my in car frustration.
Added to that you would think that Google to Google devices would play nice. There are considerable lag and crash issues with the Nexus and the Google Chrome Cast.
I suppose it’s what your used to and having spent the money we’ll have to plug away for a bit more. But I’m tempted to slip the SIM back into the Windows 8 Phone everyday. I’m also tempted to write an Android App to manage Groups and Group Texts on the Phone without having to get all my contacts to signup and download an app. It’s got to be easier than that. SMS is the lowest common denominator for Mobile communication especially in Ireland and it should be handled effectively with the phone’s eco system by default as part of the operating system. That’s the way it used to be before phones got too fancy for their own good.

Friday, 29 November 2013

Game Maker Standard free for limited time only

Game Maker studio Standard edition is free for a limited time at yoyo games hen click on the first download button

downloadButton

Then click on the next download button.

DownloadButton_Final

Then during the install You will be asked to register. You specify your email address and then yoyo games email you a license key. NOTE: You need to do this carefully as it is very difficult to register after the install. Wait for the email and then cut and paste the registration key in the box provided and then continue with the installation. The standard edition is full featured without the restrictions of the free version. GET IT while you can.

Friday, 16 August 2013

Fledgling Games in Ireland

Games Ireland

I attended an event organised by Enterprise Ireland and Games Ireland last Wednesday.

I had a bit of an experience getting from the overflow car park to EI HQ. Suffice to say I am a grown man and I would not walk down that tumble weeded lane way at any time of day. We are where we are. I presume everyone else was from Dublin and got public transport directly to the building or walked. The idea was that a few successful Canadian’s from a thriving Quebec Games scene would talk about their experiences growing a gaming industry and give their insights into how Ireland might replicate their success. Also some interested parties from the local games scene. Those Present were

Guest Speakers

- Gary Leyden - Director at NDRC LaunchPad

- Serge Landry - CEO Canadian Interactive Alliance, CEO Miralupa, Gen Sec Alliance Numerique

- Emmanuel Wall - Director at Strategy First - Indie Publisher

- Jean-Francois Arseneau - Business Development - Hibernum Creations

- Richard Barnwell - CEO Digit Game Studio


- Moderator: Paul Hayes - Games Ireland

Pity about Serge I like what they are doing in augmented reality games at Miralupa

Topics for discussion ranged from

How and when to show your game to a publisher?

Consensus was sooner rather than later. But read the small print and don’t marry the first one that comes along just cause they asked.

Which should you do free to play or one of the pay first models?

Richard  Barnwell was of the opinion that free to play was the only way with the larger games companies adopting the model and relying on DLC for revenue. Emmanuel leaned towards the other side of the fence but if he pays for it it had better be good. But opinions and developments in the crowd were 50/50. Personally I think that Games are a unique software artefact. What makes them unique is that they are entertainment, art and stimulation rolled into one and you can either chase the buck or produce something interesting and see if “they will come”. What makes games development interesting to me is that it is a visual embodiment of the interaction of code. The ultimate UX experience. The matrix. Free to play or not lead to a discussion of advantages and disadvantages of the free versus the paid model and in the wider context of software. There is a saturation of the market with free stuff, so much so that if you create anything of note, how would anyone find it free or otherwise. Gary Leyden interjected that this why from the outset young games companies need to have their business processes in place. Being in the software business myself I’d have to say I agree but it such a “suit” thing to say Gary Smile

I asked has the educational landscape adapted in the Canada to the new industry? This lead onto a brief discussion, well more like a lecture from Richard Barnwell, on what is wrong with education.

It would seem not as quickly as the games companies would like. Richard Barnwell of Digit thought that those teaching games were not really qualified to do so. He may have a point but I would counter that and maybe say that those who work in games are not necessarily the best to teach or preach for that matter. It’s one thing lecturing to a room full of top quality people who are hanging on your every word. It’s another to take an aspirational 17 year old adolescent and produce the “Final Product” from him or her. Now Richard only wants the best and he wants it now. Which is fair enough and Digit’s (nice website by the way) ideal’s are highly ambitious. I would like to take a moment to reply to Richards brash attitude to education. It’s a typical opinion held by those who don’t understand where education fits into the picture with respect to the needs of the software and by extension the games industry. I have over 23 years of experience in producing graduates most of which have gone on to have great careers in software development of all facets (games being one of them). It takes a while to produce the “final product” that Richard and others want to employ and it depends on the raw materials you have to work with. Some get it straight off the bat others as I like to say are “slow burners”. But patients and effort gets them there in the end. I suggested that maybe some project work instigated by a company would be beneficial. Not enough for Richard. I think the Canadians, quite on this point, might support the same view. The Canadians also expressed the view that educational institutes in Canada are struggling to keep up.

Industry wants education to produce graduates to meet their (usual immediate and changing )needs. Every company has different needs. How can education cater for every need? Technology moves fast, and yes it is true that a lot of educators don’t move with it, some are lazy, some are not. There are many reasons why educators may be slow to move with a technology. The process of changing a syllabus is slow and resistant to rapid change. It takes a lot of time to explore new technologies and then package it in a way that can be clearly understood by a wide audience. Education is for everybody not just the gifted and elite.

I personally spend a lot of time researching and exploring new technologies. The educational system imposes restrictions on what I can change and I cannot change mid stream. You can respond rapidly to change if you have complete control of your business process. There are quality criteria to be met when making changes in syllabi. It’s hard to keep up when you are teaching several technologies to learners with different needs and abilities. But we do try. In summary if education was driven by the latest technology needed by the various software companies then it would be in a constant state of flux and that would not be maintainable for educators or learners.

OK. Well here are some suggestions as to how we might Improve matters.

  1. We write our computing courses to technology agnostic. We do this at the moment, but the underlying principles change also. Let me give an example. I teach 2D games programming. I teach it to year 2 games students. They have one year of Game design and introductory programming behind them. They barely know what an object or a class is. There is a shift from single platform to multi-platform. So I’m looking at mono this summer for multiple platform deployment. We’ll still develop a 2D theme and concepts in c# (our language of choice for all our programming – rationale being that more than one language can confuse weaker students) but we’ll want to cover more than one platform with the same code base. Not everyone writes their modules technology agnostic. Resistance to change is everywhere.
  2. If (the games) Industry want specialisation that suites their needs then they need to have a stronger real input in terms of time, imparting skills back into education and even possibly finance. Especially when education is under such financial strain with increased numbers of students and less resources. The model for funding education is also changing towards bums on seats. This impacts on quality. I know the likes of the Khan academy, UDK, Unity video libraries are out there. But these tools are for highly motivated, intelligent and experienced learners. So as well as chasing the buck lets spend some time to build and sustain.
  3. Industry needs to lobby the government more effectively. The government do not respond to educational lobbies in the same way. The Canadians made it clear that the Quebec government made a conscious decision to court and attract development companies. These are the manufacturing sector of the Games industry. The government here are hiding behind the term “Knowledge Economy”, when really large multi-national games and software companies are only moving their support services jobs here to Ireland. The numbers and name dropping announcements look great for the press, but these services  jobs will not grow a games manufacturing industry.  

Gary Leyden announced that as part of their new Launchpad (if I’m reading the announcement right?) initiative, 5 of the companies will be game based.

Applause. This is a small attempt by some dedicated individuals who can see benefit of as they say in Australia, “giving someone a go”. The only problem I have is that as usual it’s based in Dublin. Surely in this digital connective age we can see an even bigger picture. There should be incubation initiatives supported by government funding springing up all over the country. We provide this option to work placement for those games people who want to follow their dream in year 3 of the Games Development Degree. It would be nice if they could get paid while doing it. Actually they probably can but Social Welfare rules are unbelievably complex at a glance

So what did the Canadians bring to the discussion and how will their advice affect those in the room? Jet lagged as they were. 

Emmanuel Wall will publish your game. JF won’t. They have been successful, but no clear indications as to how or why really. As with a lot of things, hard work, fail early, get lucky, don’t be despondent, follow your dream, adaptability, be careful of ruthless business people (publishers, VCs, other suits) seem to be the themes. Oh yes and get the Government on board. Adaptability is very important for me. In Games development at IT Sligo we try to ensure that every graduate can program business applications as well as pursue their dream of being in the games industry. The dream isn’t facilitated by the industry yet. The Canadians indicated that they were making a living but not getting rich quick. JF of Hibernum Creations mentioned that they do a combination of in-house developed games and work for others, but mainly people that they have worked with previously. Emmanuel Wall of Strategy First seemed to be approachable and have a love for the creative nature of Game Development. JF of Hibernum Creations came from a more artistic animation background (I hope I’m not doing a disservice there) and his company is more in the social games, casual games, animation and digital art arena. But I think everyone is advocating cross/multi platform development.

What was refreshing was to see the young Irish gaming entrepreneurs in the room. Would be nice to hear successful stories from them in a few years time. I envy them their youth and I wish them well.

Saturday, 18 August 2012

Running Windows phone 7 (mango) emulator in an emulator

I'm using a VMware emulator for Windows 7 on my Mac book Pro. Soon to be dumped for a Native Windows 7 machine. Now the WP7 emulator is a VM also and generally VM into VM does not go. SL will deploy to the WP7 emulator unless you are using anything to do with WDDM 1.1 (which is not supported by the ghost graphics Direct X 9 card emulated by VMware) which discounts all XNA deployment. I recently reduced the amount of memory allocated to the VM as I was getting warnings from VMware for something. This caused a problem in VS 2010. When I went to deploy to the WP7 emulator I got the following error "visual studio error the interface is unknown" which as usual means something totally different! It means that there is  not enough memory to support the WP7 emulator. I read around and it can happen on a native (non-VM) machine also. I have come to this conclusion VMs are not a solution for Windows 7 production machine on a MAC. Hence the MAC has to go!

Friday, 18 May 2012

Level Manager revisited–residual objects from deleted levels

 

In a previous post I went through a level manager. This post picks up were that one left off.

If you create objects in the sub class levels, then when you set the level to null, thus not activating it next time around the Array. Then the objects contained within the Level 1 for example will still exist. For this reason we could implement Idisposable and a destructor to cleanup after the Level 1 object is deleted (see here) but that is beyond the scope of what we know here. I will cover this technique at a later date. Another more simple is reported here.

say we play Sounds and a backing track within a level Level 1. Thus in the constructor assuming the appropriate Sound and Song variables are declared

sound = g.Content.Load<SoundEffect>("Tank-Moving");
backtrack = g.Content.Load<Song>("Sleep Away");
soundInst = sound.CreateInstance();
soundInst.IsLooped = true;
soundInst.Play();
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(backtrack);




we must cleanup after ourselves before the level is set to null. Otherwise the objects using the external resources (media player) may not be disposed of as they are still active.



public void cleanup()
{
soundInst.Stop();
if (MediaPlayer.State == MediaState.Playing)
MediaPlayer.Stop();
player = null;

}


It would be better put the cleanup routine in the Level class along with all the possible content objects and actually the player object should be there also. But as some objects are declared in the subclass the level manager must call the cleanup method of each Sub Class Level as when you delete a sub level the objects may not be decommissioned by the .NET garbage collector until they are no longer needed. The media player will continue to play as it is repeating and will definitely not be released.



The Level manager must be able to distinguish the type of the Level to call methods appropriate to that Level. So when we are iterating through the Level objects we check what type the level object is and call it’s appropriate clean up method. This method can be used to specialize actions (method calls) for levels also. So in the update for the level manager (look for the if (l.LevelState == LEVELSTATE.FINISHED)) statement when we are checking to see if the Level is finished we call the cleanup method thus



// if the current level has finished
if (l.LevelState == LEVELSTATE.FINISHED)
{ // Get rid of the level
if (l.GetType() == typeof(Level1))
{
Level1 current = (Level1)l;
current.cleanup();
}

Levels[CurrentLevel] = null;
etc..


What we do here is we check to see what type of level object we are dealing with. You can do this with any object using the GetType() function to return the Object type (you cannot use a switch statement with though). Then we cast the Level object as a Level1 object so we can call the cleanup routine for the appropriate level. You would need an if block for every level object that requires cleaning up.

Saturday, 5 May 2012

A conveyor belt of Spawning a horizontal Sprite

A Horizontal spawning Sprite is similar to a patrolling platform sprite in it’s behavior and also similar to a falling sprite. But simpler.

A simple algorithm for a collection of Spawning sprites is as follows.

  1. Set up a timer to control when to Spawn the next sprite. The class that creates the Spawning sprite collection (Game1 here) controls this timer.
  2. The Spawning Sprite object has a simple state that is either Spawned or not. So that is Boolean.
  3. An Un-spawned sprite will not be updated or drawn.
  4. The objects are spawned off screen to the left and have a target off screen to the right.
  5. While they are spawned they just move to the target position at a certain speed.
  6. When they get to the target position Spawned is set to false and they return to the starting position waiting to be Spawned again when the timer goes off.

So in a new Game Class we create an array to hold our Spawning Objects. Our Base classes are as we previously used

image

 


The Spawning enemy class variables and constructor is as follows


class Spawn : Enemy
{
Vector2 EndPosition;
public bool Spawned;
public Spawn(Game g, Texture2D texture,
Vector2 Position1, Vector2 Position2,
int framecount) : base(g,texture,Position1,framecount)
{
// start, Target and End positions are defined in Enemy
// as most if not all enemies will have them
startPosition = Position1;
TargetPosition = EndPosition = Position2;
Spawned = false;
}

public override void Update(GameTime gt)
{
if (Spawned)
{
// Move X * Velocity as we are moving Horizontally
position += new Vector2(1, 0) * Velocity;
if (Vector2.Distance(position, EndPosition) < Velocity)
{
position = startPosition;
TargetPosition = EndPosition;
Spawned = false;
}
}
base.Update(gt);

}


When a Spawn is created it is initially false and it is activated by the timer in the Game1 class. The update of the Spawn just moves it horizontally. You could do the same vertically. When it reaches the target. It is reset to the start position Spawned is set to false this will cause it to be activated when the timer next goes off in Game1.



Now to Game1



The class variables



Arrays are used here as other collections have not been covered in First year programming



const float MAXSPWAN = 1000;
float SpawnTime = MAXSPWAN; // milliseconds
Spawn[] cokeBottles;


protected override void Initialize()
{
// TODO: Add your initialization logic here
cokeBottles = new Spawn[5];
base.Initialize();
}


We fill the array in the Load Content method. The start Vector is off to the left of the viewport. The End and target position are off the right of the viewport



for(int i = 0; i < 5;i++)
cokeBottles[i] = new Spawn(this,
Content.Load<Texture2D>("CokeBottle"),
new Vector2(-30, 300),
new Vector2(GraphicsDevice.Viewport.Width + 100, 300),1);


So now we have an array of 5 Spawn objects. The Update of Game1 controls the Spawning of a sprite based on the Timer.




if (SpawnTime > 0)
//Count down the spawn time
SpawnTime -= gameTime.ElapsedGameTime.Milliseconds;
else
{
// reset the spawn time
SpawnTime = MAXSPWAN;
// if any of the Spawn reach the target
// which is off to the right of the viewport
// then the Spawn will set it's
// Spawned property to False
foreach (Spawn s in cokeBottles)
if (!s.Spawned)
{
s.Spawned = true;
break; // This is Key only one spawned at a time
}
}
// Normal Update Spawned or not
foreach (Spawn s in cokeBottles)
s.Update(gameTime);



The Draw for Game1 just draws the sprite collection



foreach (Spawn s in cokeBottles)
s.Draw(spriteBatch);


and that’s it

Monday, 30 April 2012

A simple State based level manager in XNA

This post is to explain a simple level manager that will handle the transition between levels of a simple sprite based game based on simple state management of a sequence of levels. It assumes linear progression from one level to the next

A level consists of a set of items (Sprite based items in this case) that you want to interact with or get them to interact independently, during game play. The key to level management is to have a parent class for each level that you want in your game and that will contain references to collections that you may have in each level of your game.

The level manager manages the transition between the levels based on the outcome of a particular level. Failure and re-doing a level is not dealt with here but could be easily accommodated by extending the state model for the Level Class and coding the Level Manager accordingly.

To keep it simple here and concentrate on the Level class and the Level Manager class I will create two levels of a game that will just transit through states based on a Timer. These two classes will be level1 and level2 respectively. I will also only have static (non-animated and non interactive) content in the Level class which can then be filled in the two sub classes (level1 and level2).

The level Manager is created, updated and drawn in the Game1 class. The Draw is implemented just to call the Draw methods of the level1 and level2 classes which in turn pass the draw message on to the components that they contain.

All the classes here only implement or override  a common Update or Draw method, which are most fundamental in Game programming.

So the Game creates the Game Manager.

image

The Level manager creates the Game Levels.

image

The Levels create instances of the level contents Sprites, sound, textures.

There are a couple of Key issues about the structure and control of the levels.

  1. As Level1 and Level2 inherit from Level they can be treated as being the general Level class in some instances. Such as iteration over the collection of Level Objects.
  2. The Sate of a level is kept in the parent class Level and is chosen from the enumerated type LEVELSTATE

image

 

So to the actual State Management and transition of the individual levels. The Level Manager maintains a collection of levels that are created and assigned in the constructor.

class LevelManager
{
// Indicate the last level is complete
bool gameOver = false;

public bool GameOver
{
get { return gameOver; }
set { gameOver = value; }
}
// Counter for the current level
int CurrentLevel = 0;
// Maximum amount of levels

const int MAXLEVEL = 2;

// Collection of levels which are created as subclasses of Level
Level[] Levels;


public LevelManager(Game g)
{
Levels = new Level[MAXLEVEL];
Levels[0] = new Level1(g);
Levels[1] = new Level2(g);

Levels[0].LevelState = LEVELSTATE.PLAYING;

}


Level1 is put into playing mode. It is up to Level1 to transit itself into Finished Mode when it’s end condition is met. In this case a timer is used to time down the fairly static levels. The levels here just show a collection of Chasing Sprites in a location and a player in Level1 that the Chasing sprites will chase.



The transition from playing for a Level is monitored in the Update method of the Level Manager class



 



public void Update(GameTime t)
{
if (!gameOver)
{
foreach (Level l in Levels)
{
if (l != null && l.LevelState == LEVELSTATE.PLAYING)
{ // Update the current playing level
l.Update(t);
// if the current level has finished
if (l.LevelState == LEVELSTATE.FINISHED)
{ // Get rid of the level should
Levels[CurrentLevel] = null;
// and if the not the last level finished
if (++CurrentLevel < MAXLEVEL)
// then play the next level
Levels[CurrentLevel].LevelState = LEVELSTATE.PLAYING;
//Or else we are finished
else gameOver = true;
}
}
}
}

}


The key thing here is that although level1 and level2 are objects in their own right they have a LevelState variable that can be monitored. The Level class definition is shown below



class Level
{

private LEVELSTATE levelState;
public LEVELSTATE LevelState
{
get { return levelState; }
set { levelState = value; }
}
protected ChasingEnemy[] enemies;
protected Sprite[] collectables;
protected Sprite BackGround;
protected Player player;

public virtual void Update(GameTime t)
{

}

public virtual void Draw(SpriteBatch sp)
{

}


The virtual methods are provided in case the methods need to be overridden in the future. Any collections of object that you want to have in levels are added as class variables here and can be populated in the constructor for the sub class for example here is the constructor for the Level1 class



class Level1 : Level
{
float Timer = 5000; // milliseconds

public Level1(Game g)
{
player = new Player(g, g.Content.Load<Texture2D>("FullTank"), new Vector2(400, 600), 1);
enemies = new ChasingEnemy[3];
enemies[0] = new ChasingEnemy(g, g.Content.Load<Texture2D>("EnemyDot"), new Vector2(100, 200), 1);
enemies[1] = new ChasingEnemy(g, g.Content.Load<Texture2D>("EnemyDot"), new Vector2(300, 200), 1);
enemies[2] = new ChasingEnemy(g, g.Content.Load<Texture2D>("EnemyDot"), new Vector2(300, 400), 1);
LevelState = LEVELSTATE.CREATED;
}


NOTE the sub-classing of the Level class is Key as it contains the exposed LevelState and allows all levels to iterated over using for each and treating them all as Level objects for the purposes of this iteration



Here is the state transition in the Level1 update method



public override void Update(GameTime t)
{
if (Timer > 0)
Timer -= t.ElapsedGameTime.Milliseconds;
else
LevelState = LEVELSTATE.FINISHED;

player.Update(t);

foreach (ChasingEnemy c in enemies)
c.follow(player);

foreach (ChasingEnemy c in enemies)
c.Update(t);

}

the full code listing can be found here

Wednesday, 21 March 2012

Allowing for One Time collisions of sprites

This post is specifically for 1st Game Design students in IT Sligo 2012. We have two animated sprites in a game. One is an enemy moving around randomly by itself – the randomEnemy, one is controlled by a player – the player. Both have common attributes and methods (they are both animated and Drawn at their position) hence we have a sprite class to handle this. This is all placed in the Sprite class (sometimes called the base class). For convenience as we have other types of Enemies to be used later that share attributes we have an Enemy class in between RandomEnemy and the Sprite class.

Now the Sprite, Enemy, Player, randomEnemy classes are pre-written and can be found here.

In order to use them in a new game don’t forget to use the name space which in which all these objects reside

using AnimatedSprite;


Now I’m using the default Game1 class here for speed. But the example that the current assignment is based on uses a chase engine class that I have written. All actions happen in the Update of the Game and would happen in the Update of the Chase Engine.



Here are the classes involved in this post.



image



So onto the problem to be solved



The sprite class has a method called CollisionDetect which will check if one sprite collides with another.



public bool collisionDetect(Sprite otherSprite)
{
Rectangle myBound = new Rectangle((int)this.position.X,
(int)this.position.Y, this.spriteWidth, this.spriteHeight);
Rectangle otherBound = new Rectangle((int)otherSprite.position.X,
(int)otherSprite.position.Y, otherSprite.spriteWidth, this.spriteHeight);
if (myBound.Intersects(otherBound))
return true;
return false;
}


 



As it’s in the Sprite Class the Player and all the subclasses inherit it. So when the player object collides with the Random Enemy object we want to update a score for the player. The problem is that the score keeps increasing during the collision event which will happen 60 times a second while colliding. This gives unpredictable scoring. So we need 2  Boolean variables to make sure we only update the score one collision at a time.



So to the Variables to represent the score, the player, the random enemy, a Boolean variable to record if there is currently a collision and if there was a collision on the previous call to the update



int score = 0;
Player player;
RandomEnemy randomEnemy;
bool colliding = false;
SpriteFont scoreFont;



The player,enemy and font to draw the score can then be created in the Load Content method.



player = new Player(this, 
Content.Load<Texture2D>("PlayerDot"), new Vector2(10, 10), 2);
randomEnemy = new RandomEnemy(this,
Content.Load<Texture2D>("EnemyDot"), new Vector2(200, 200), 1);
scoreFont = Content.Load<SpriteFont>("scoreFont");


and so to the Update logic



protected override void Update(GameTime gameTime)
{
player.Update(gameTime);
randomEnemy.Update(gameTime);
if (player.collisionDetect(randomEnemy) && !colliding)
{
score += 10;
colliding = true;
}
else if(!player.collisionDetect(randomEnemy))
colliding = false;

base.Update(gameTime);
}


colliding protects the score from being updated many times in the one collision. colliding is false to begin so !colliding will be true and so if the player successfully detects a collision then we update the score but we set the colliding value to true. This makes !colliding false on the next Update call and hence it will not update the score.



colliding is set to false if the player is not colliding which will happen quite a bit actually.



Then it just remains to draw the score and update the new positions of the player and the Random Enemy



 


protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
player.Draw(spriteBatch);
randomEnemy.Draw(spriteBatch);


            spriteBatch.Begin();
spriteBatch.DrawString(scoreFont, "Score: " + score.ToString(),
new Vector2(10, 10), Color.White);
spriteBatch.End();

base.Draw(gameTime);
}


and that’s it. The same would apply for a decrease in the Lives of a player and you would need an additional different Boolean variable to protect the lives variable. Until next time.



The final coded solution is here. Any problems give me a shout.

Thursday, 5 January 2012

First View of Android app structure behind the Scenes





Well I thought XAML and c# could be complicated, but the pattern that holds the Android UI together is no simple walk through the park either. And having not looked at Java in years, I presume it is similar for other Google Apps? Cryptic is not the word. The basis for the elements to be rendered is fair enough. It's XML and I like the render tool that is built into the the eclipse plugin for Android. But the model for linking it to the Java code behind the form is not intuitive and requires you to burrow down through resources to see how it all comes together and all this from a resource reference in the default Activity stub called R??

We go from this

public class Project1Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

which is fair enough to this which is the equivalent of .g.s.cs hidden code generated file in VS

package com.appsolo.adnroid;

public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

which is not

and then we are down to the resources which I know XAML can rely heavily on as well

here is the XML for the form which is rendered in the tool

xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello" />

LinearLayout>


The XML is rendered nicely in the Graphical Tool of the Android plugin






















Although there is a Android Resources values tool for keeping track of values














But there are a lot of Dots to join up here!!!



First Steps in Android

Ok. I Got the Android development kit installed on a Mac. Thats a plus for a start. It runs native, raw and wriggly on the Mac. The Mac book pro being a fine piece of hardware and the Apple software including the OS being lovely to use but awkward to work with and find your way around for Windows head like myself.

For the life of me I cannot fully remember the process as I never can when installing downloaded software, some you do yourself and some comes down as a result of what you do. Suffice to say the standard installation instructions are for installation on a Linux or Windows machine. I had to follow another few links to get the proper tools for OSX 10. Here is the gist of what was needed.

You need

The JDK 7 for OSX from Oracle. When you unbundle this and install it. It runs an may pull down additional updates for the Mac.

Download and install a suitable version of eclipse. I took the Mac version from HEANET in Ireland.

Then its over to the Android SDK download page for the the Android SDK and AVD Manager. Which when unzipped have to be added to the eclipse environment.

Eclipse is the SDE of choice. First impressions of eclipse are it's not bad for free, but shows all the signs of it. VS 2010 is miles ahead and I have always said MS should push this more. However when I installed as per instructions the Android SDK Manager plugin for eclipse it did have a download manager that fixed a lot of interdependencies that were missing.

I then had to set up a AVD Android Virtual Device and attach it to the currently open Workspace.

AVD manager

It did not register with eclipse and the Hello World App did not deploy to it until I shut down eclipse and started it up again. But following a reboot of eclipse (on intuition) up came the emulator. The AVD is very slow to load and I'm using a SDD and Macbook Pro with 8gigs of memory.

Next challenge was to figure out the structure of a Java project (as it has been a while since I have seen eclipse and how to load an existing sample Android app that comes with the Android SDK.

Cmd + n creates a new project. You then choose what type of project you want The basis for eclipse is a workspace that is a enclosing folder that holds the project folders. A project must have a Package name otherwise it will not create. Which is similar to a name space in c# but is represented as a directory structure of the project folder in the workspace. The workspace contains a collection of project folders.

Project setup window

Once the Android SDK plugin is installed you you have access to the sample projects which you can then base a new project on. Right click on the project window



Followed two screens later by your Android sample template



Well thats the development environment  set up and ready to go. Now on to look at the Android in more detail.

Tuesday, 17 May 2011

Incomplete Federation of Live accounts

I have four Windows Live accounts linked together. But a word of warning. If you want to access files in folders you must give permission on the folder to the linked live accounts. You can edit in the browser from Linked account that you have switched to when initially logged in as another account which would seem to suggest that federation across the accounts works to a certain extent. Sometimes you get an HTTP access error 403 when accessing locations belonging to another Live account that is linked but not directly logged in. This I think is due to improper federation between the Live accounts.

If you are using the office live plug in locally on your PC to download and open a Live sky drive hosted office document for editing, then the account that Office live plug in is setup for needs to have edit permission on the folder and hence the file to be downloaded and opened so all the Live accounts need to have access to folders owned by the other in order for navigation to run smoothly.

Also worth a NOTE: Folder access is inherited from the parent, so if you give access to the account at the top most level then it will be granted for sub folders always.

Friday, 29 April 2011

Jeff Prosise's Blog : Silverlight 4's New Local File System Support and Problems with My Documents in Windows 7

While looking at the new restricted capabilities of Silverlight to deal with Files I came across this post Jeff Prosise's Blog : Silverlight 4's New Local File System Support. I downloaded the sample code an went to run it. It worked impressively in fact for the My Picture example. But I need to access folders in My Documents. So I tried that and oops it broke. The problem is that

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

in windows 7 maps onto "C:\\Users\\name\\Documents" and the sub folders of that location have My Music, My Pictures and My Videos contained within and you cannot chain through these folders as you do not have permission to do so. So you have to skip over these thus

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

foreach (string dir in Directory.EnumerateDirectories(path))
{
if (!dir.Contains("My Music") && !dir.Contains("My Pictures") && !dir.Contains("My Videos"))
etc

Another Gotcha in Windows 7 and file permissions is that if you download a zip file from the web is that certain files will be blocked and you have to unblock each one before you can process the files programmatically.

Tuesday, 12 April 2011

A conveyor belt of sprites

This is an example of a set of wrap around (or Conveyor belt) sprites that can be used in a frogger type game. It is inspired by a problem that a student was having with the technique. It is an example of using a list to hold a list of sprites. It also demonstrates the idea of sub classing as it uses a sprite class that we developed previously. The key to the technique is that the original random spacing of conveyor sprites is maintained once they start moving and once they go off the lefthand side of the viewport you just need to reposition them at their width extent to the right of the viewport. The original random spacing is preserved. The ConveyorSprite class subclasses the Sprite Class which is a Drawable Game component and as such draws itself. The Update method is overridden to update the position of the Conveyor sprite so that it moves across the screen and if it goes off the left then it is repositioned to the right of the viewport. As the new Conveyor sprites are being added to List of Conveyor Sprites in the main game class, the start relative position of each off screen to the right is calculated.

The code can be downloaded at


Wednesday, 6 April 2011

Managing Complex Groups in Windows Live - Group Work for students

The Windows Live Group feature allows you to easily manage Group work for students. I have a group of about 70 students from 4 different courses in First year. These Groups are further split into groups for a game that they are designing and developing in Game Maker. I got them to set up groups with one person hosting the Group on their Sky Drive. I set up a new Windows Live ID to manage the group from my side. The Group owner invites the other members to the newly created group along with myself.

I manage the group by setting up Hotmail folders for each Course and then place the invites from each Game Group into these folders. 

Games_Groups

This enables me to keep track of the groups within groups via the Email Invite which has a

Group_Invite

Everyone in the Group has read write privileges on the folders in the group. This gives them a means to share content that they are developing for the game. It also allows me to keep an eye on the Progress of the group and comment or advice on the on going work.

Group_Page

There is a One Note web file that the group can use to document the sources of content and keep a group and individual schedule of tasks to be done and completed.

The group can contact me and each other using Instant messenger or by Emailing the group.

Video

Monday, 21 February 2011

XNA Challenge starter Kit 2011 – Getting started

Ok the first thing to note is that the starter kit is only deployable for a Windows 7 Mobile solution developed in VS 2010 under XNA 4.0 on a Windows 7 machine. If you want to run this version in the Windows 7 mobile emulator or deploy it on an actual WM7 phone I recommend you.

  1. Have Windows 7 installed on your PC.
  2. Download the XNA Windows Phone Developer Tools RTW
  3. This has a a bundle of stuff including the emulator needed to run the starter kit as is.
  4. You will also need VS 2010 express or upwards that you can get from Dreamspark.
  5. If you have Vista you may have driver issues with wddm 1.1 driver which the emulator needs along with Direct X 10. At the time of writing I’m installing updates for my NVIDIA 8600M Graphics card. But I’m not sure how this will go so…

If you want to develop the starter kit to deploy a windows and/or XBOX solution you need to

  1. The first thing to do is create a copy of the project for Windows.
  2. Then unload the Win 7 project from the solution.
  3. The solution has been developed on a Windows 7 machine and as such if you compile it you will get an error on the long file name of the project name. So change the name to something shorter.
  4. If it still complains about running because of D3D problems, then edit the properties of the windows version and make sure the HiDef settings are off.

windows_game_properties

The input manager is also only wired up for gesture input from the Windows Mobile. So you have to figure out what controls you are going to use on the XBOX controller and then have a look at the Input Manager and then edit the input manager to allow for these. The engine is well coded in general with State maintained quite well. Input enum values give rise to changes in game state in the game engine.

Here is an alternative Keyboard manager function – only up and space are programmed to react here. Space changes the game engine state represented by

public enum GameState { Splash, Play, Win, TryAgain, Loading }


see Engine.cs



private Input HandleKeyInput(Game.Engine.GameState gameState)
{

Input input = Input.None;
keyboardStateCurrent = Keyboard.GetState();
if(KeyJustPressed(Keys.Up))
input = Input.Up;
if(KeyJustPressed(Keys.Space))
input = Input.Select;
keyboardStatePrevious = keyboardStateCurrent;
return input;
}


 



and here is the appropriate change to the PlayerInput to switch from the gesture managed code to keyboard managed



public Input PlayerInput(Microsoft.Xna.Framework.GameTime gameTime)
{
Input input = Input.None;
//#if !WINDOWS || !XBOX
//input = HandleTouchInput(XNAGameStudioIrelandChallenge.Engine.Game.Engine.GameState.TryAgain);
//#endif
input = HandleKeyInput(XNAGameStudioIrelandChallenge.Engine.Game.Engine.GameState.TryAgain);
return input;
}


This game engine and scene manager are well written. The tile editor concept you have covered with Neil. With minor changes you should be able to load your own content and change the behaviour of the game.



An amended copy of the engine code with the changes detailed above can be found in XNAGameChallange2011ModifiedByPPVS2010.zip here. You will have to logged in to windows Live and a member of the year 2 Games Group to access this folder.



There is nothing in this project that you cannot do in XNA 3.1 I think. To import it you’ll need to open up a new project and import all the folders and code into the VS 2008 project with XNA 3.1. It’s a pain but doable.



I will blog more on the structure of the Game in a later post.

Thursday, 17 February 2011

Understanding GameTime - Shawn Hargreaves Blog - Site Home - MSDN Blogs

 

Understanding GameTime - Shawn Hargreaves Blog - Site Home - MSDN Blogs

Shawn Hargreaves explains how the timing of the Game Loop in XNA works and how it can be affected.

Monday, 14 February 2011

XNA A common Sprite Batch as a Game service

In a previous Post it was pointed out that using game components can lead to multiple sprite batches in each component. A solution to this was presented to me by Neil Gannon and I am applying it here to multiple components were each component just has a sprite batch draw event and each component

public class Game1 : Microsoft.Xna.Framework.Game
{
MovingCircle myCircle;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;


.



.



Then in the game initialize function we create the sprite batch as a service and we set up the moving service components. The Constructor for the Moving Circle Component accesses the Game Components and adds itself. Hence the commented out line  below. Again Neil’s style.



protected override void Initialize()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
this.Services.AddService(typeof(SpriteBatch), spriteBatch);
for (int i = 0; i < 9; i++)
{
myCircle = new MovingCircle(this);
//this.Components.Add(myCircle);
}
base.Initialize();
}



Now to the Game Draw event.



protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
base.Draw(gameTime);
spriteBatch.End();
}


Note: The base.Draw(gameTime);  call before the End() call allows all the Draw() events of the components to be marshalled before the sprite batch End() call commits the draws to the graphics device.



The Code for the Moving Circle Class is thus….



 



public class MovingCircle : Microsoft.Xna.Framework.DrawableGameComponent
{
SpriteBatch spriteBatch;
Texture2D movingCircle;
Vector2 movingCirclePosition;
Vector2 Target;


.



.



public MovingCircle(Game game)


            : base(game)


        {


            spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));


            game.Components.Add(this); // Add yourself

       
}



// The component adds its own content


protected override void LoadContent()
{
movingCircle = Game.Content.Load<Texture2D>("MovingCircle");
movingCirclePosition = new Vector2(LocalRand.RMinMax(0,600), LocalRand.RMinMax(0,400));
Target = new Vector2(LocalRand.RMinMax(0, 600), LocalRand.RMinMax(0, 400));
}


// Update the moving Circle    
public override void Update(GameTime gameTime)
{
movingCirclePosition = Vector2.Lerp(movingCirclePosition, Target, 0.1f);
if (Vector2.Distance(movingCirclePosition, Target) < 0.2)
{
Random r = new Random();
movingCirclePosition = Target;
Target = new Vector2(r.Next(600), r.Next(400));
}
base.Update(gameTime);
}
// Line up the Draw() for this component
public override void Draw(GameTime gameTime)
{
spriteBatch.Draw(movingCircle, movingCirclePosition, Color.Red);
base.Draw(gameTime);
}
The Result


MovingComponents


The Code is here

Thursday, 10 February 2011

Searching through a Game component collection

Generally you access the game component collection or the services to find a game component. But what if you want to find a collection within a collection. And what if you only wanted to find the components within a range of the player.

We will look at the Game components collection here. We can use generics and the fact that the Components are a collection using Linq to find the relevant components. Say we have a player class and we want to see all the moving circles around it.

Firstly a generic method in the player class to return a collection of specified components

List<T> FindComponent<T>()
{
return Game.Components.OfType<T>().ToList<T>();
}


NOTE: 


1. This code is called from a game component or you could put it in a static class that can be accessed from anywhere in the game, that has access to the Game object.


Then you can have another method to return the appropriate List of objects.


 


public List<MovingImage> AroundPlayerPos()
{

return FindComponent<MovingImage>();
}


This method can then be further modified to search through the collection using Linq to further qualify what is returned to the calling method.


XNA Game services

I read a good analogy recently explaining the concepts of Game Components and Game services. Game components are like the plumbing (or sewage depending on how good your code is) system underneath a city that is your game. The components are interconnected through the Game class, but can exist independently to certain extent. Game Services are like have a Large Zeppelin over the city with rope ladders that can you can use to grab elements that you need to reference in your game objects. You climb up the rope ladder and grab the type of object that you want. Game services allow you to share objects registered as Game services across Game components. It is reserved for items that a Game Component might need to preform a function


Here is how to use game services. You set up your objects in the main game


Say you want to use a common sprite batch that is set up in your main Game class

spriteBatch = new SpriteBatch(GraphicsDevice);


this.Services.AddService(typeof(SpriteBatch), spriteBatch);


the typeof function says what kind of ladder you will be using to access the service later.

then in the class that you want to retrieve it from (in this case a game drawable component) 

public ChaseImage(Game game, Texture2D CircleImage)
: base(game)
{
sp = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
image = CircleImage;
spriteFrame = new Rectangle(0,0, image.Width/4, image.Height/4);
imagePosition = new Vector2(LocalRand.RMinMix(0, 40), LocalRand.RMinMix(0, 40));
}



then you can use the shared sprite batch to draw the all components thus



public override void Draw(GameTime gameTime)
{
sp.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise,null, SpriteScale);


sp.Draw(image, spriteFrame, null, new Color(new Vector4(1,1,1,0.02f)),1.0f,Vector2.Zero,SpriteEffects.None,1);


sp.End();


base.Draw(gameTime);
}


Note:




  1. If you have a collection of similar services all with the same typeof you could use the generic search code presented in the previous post to retrieve each of the services.


  2. This method only uses one sprite batch but still has multiple calls to the sprite batch for each component drawn.





Tuesday, 8 February 2011

Converting a class to a DrawableGameComponent

Given the original code for a sprite class the source of which is provide here was provided by Neil Gannon.

   1: class Sprite



   2: {



   3: public Sprite(Texture2D texture,Vector2 userPosition, int framecount)



   4:         {



   5:             spriteImage = texture;



   6:             position = userPosition;



   7:             numberOfFrames = framecount;



   8:             spriteHeight = spriteImage.Height;



   9:             spriteWidth = spriteImage.Width / framecount;



  10:  



  11:         }



  12: public void UpdateAnimation(GameTime gametime) {}



  13: public void Draw(SpriteBatch spriteBatch) {}



  14:  



  15: }




image



We need to sub class the class off DrawableGameComponent and then add an override for update and draw. These must be public overrides to match the method declarations in the the DrawableGameComponent Class. The game component needs it’s own sprite batch to draw to the graphics card and hence it needs to see the Games Graphics Device. But thankfully this is exposed in the component model for the game class. The Class becomes





   1: class Sprite : DrawableGameComponent



   2:     {



   3:         //sprite texture and position



   4:         Texture2D spriteImage;



   5:         Vector2 position;



   6:         SpriteBatch spriteBatch;



   7:         //the number of frames in the sprite sheet



   8:         //the current fram in the animation



   9:         //the time between frames



  10:         int numberOfFrames = 0;



  11:         int currentFrame = 0;



  12:         int mililsecindsBetweenFrames = 100;



  13:  



  14:         //the width and height of our texture



  15:         int spriteWidth = 0;



  16:         int spriteHeight = 0;



  17:  



  18:         //the source of our image within the sprite sheet to draw



  19:         Rectangle sourceRectangle;



  20:  



  21:         float timer = 0f;



  22:         



  23:         public Sprite(Game G, Texture2D texture,Vector2 userPosition, int framecount) :base(G)



  24:         {



  25:             spriteBatch = new SpriteBatch(G.GraphicsDevice);



  26:             spriteImage = texture;



  27:             position = userPosition;



  28:             numberOfFrames = framecount;



  29:             spriteHeight = spriteImage.Height;



  30:             spriteWidth = spriteImage.Width / framecount;



  31:             



  32:         }



  33:         



  34:         public override void Update(GameTime gametime)



  35:         {



  36:             timer += (float)gametime.ElapsedGameTime.Milliseconds;



  37:  



  38:             //if the timer is greater then the time between frames, then animate



  39:                     if (timer > mililsecindsBetweenFrames)



  40:                     {



  41:                         //moce to the next frame



  42:                         currentFrame++;



  43:  



  44:                         //if we have exceed the number of frames



  45:                         if (currentFrame > numberOfFrames – 1)



  46:                         {



  47:                             currentFrame = 0;



  48:                         }



  49:                         //reset our timer



  50:                         timer = 0f;



  51:                     }



  52:             //set the source to be the current frame in our animation



  53:                     sourceRectangle = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);



  54:                     base.Update(gametime);



  55:             }



  56:  



  57:  



  58:  



  59:         public override void Draw(GameTime gameTime)



  60:         {



  61:             //draw the sprite , specify the postion and source for the image withtin the sprite sheet



  62:             spriteBatch.Begin(SpriteBlendMode.AlphaBlend);



  63:             spriteBatch.Draw(spriteImage, position,sourceRectangle, Color.White);



  64:             spriteBatch.End();



  65:             base.Draw(gameTime);



  66:         }



  67: }




Notes




  1. The constructor has to have a reference to the game that creates it and must pass it on to the Super class.


  2. We can use this reference in the constructor to access the Graphics device reference to create the sprite batch. We can alternatively access the publicly exposed Game property Game.GraphicsDevice and indeed you can reference the public exposed properties of the Game class from anywhere in the game components.


  3. You must remember to add the created sprites as components in the Game class when we create the sprite





   1: rollingImage = Content.Load<Texture2D>(@"Images\rolling");



   2: rolling = new Sprite(this,rollingImage, new Vector2(500, 50), 4);



   3: this.Components.Add(rolling);




Now we can subclass the Sprite Class and create two different types of Sprite game components. The player Sprite class will have an update method that will override the sprite update and deal with the input from the input device and the CGC Sprite Class will move around the screen.



We’ll look at those classes next time.



Postscript



It’s worth looking at the forum discussion here about the ins and outs of using multiple sprite batches or a single sprite batch for drawing components. So it would seem from the comments made by Shaun Hargreaves in the forum discussion referenced above that although components give good modularity and structure to games, but at the cost of efficiency in committing to the graphics device as multiple sprite batches in components seem not to be a good idea from a performance perspective!! So for multiple instances a Drawable game component may not be a good idea?? So back to the drawing  board eh? It would be a good idea to change the XNA framework so that it batches sprite batch (yeah I know – a bit of a recursive definition) and have a common end() method for them. The solution suggested is to have a Sprite Manager. But I thought that’s what a sprite batch should do!!



At that stage we might consider making the Sprite Class abstract as we would probably not want to create instances of it after that subclass action.