Xamarin TextChanged Event on Two Fields That Change Each Other

In the new version of the Cashflow Calculator I am making with Xamarin, I wanted to create the ability to input most of the expenses as both exact money values if you knew them or percentages of the monthly rent. This is a very common method of estimating repairs, vacancies, and property management fees.

I Change You, You Change Me

The idea was to have the percentage get set whenever the cash value was changed and the cash value get set whenever the percentage was changed.

But if you just create a normal TextChanged event on both of them, as soon as you make a change to one, it fires its TextChanged event which changes the other field and fires the other field’s TextChanged event which sets the one you are working on.

This does not work.

Stop Listening For a Sec

The solution to this is to disconnect the field you are about to change from its TextChanged listener and reconnect it when you are done changing it. We will use the event for calculating our rent percentage from the price of the property as an example.


async void CalculateRentCash(object sender, TextChangedEventArgs e)
{
    monthly_rent_cash.TextChanged -= CalculateRentPercent;
    await Task.Yield();
    var percent_val = GetFloat(monthly_rent_percent.Text);
    var new_rent_cash = GetFloat(property_value.Text) * (percent_val/100.0);
    monthly_rent_cash.Text = new_rent_cash.ToString();
    monthly_rent_cash.TextChanged += CalculateRentPercent;
}

The important parts of this function are the async in the function definition and the await Task.Yield() after removing CalculateRentPercent from the monthly_rent_cash.TextChanged listener.

Without the await Task.Yield() the function would tell the app that it needs to remove the listener but it would not do it right away. The task would be queued up but put on hold until the current task finished. It would then proceed through the function and the monthly_rent_cash field would still fire CalculateRentPercent.

With the await Task.Yield() line, the app pauses its execution of the current function and lets the Task we just created to remove the TextChanged listener finish before it continues.

If you are new to C# or Xamarin, remember that anytime you have a line that uses await in your function definition, you need async as part of the function description.

There may be other solutions to this problem, but this is the easiest one I came across so far. If you know a better solution, email me at travis at evolvingdeveloper.com and let me know.

Found the solution on the Xamarin forums.

Xamarin Forms Entry

I am rewriting the Cashflow calculator app that I made last fall from Java to a Xamarin Forms app. If I ever decide to release to iOS this will make it much easier.

One of the workhorses for this app is the Entry form element. This is your standard input field from the keyboard.

There are two features that I want to talk about today. Setting the keyboard type and Completed and TextChanged events.

Setting the Keyboard

The Entry element lets you specify the keyboard type like you would expect. There is the Default – the standard keyboard on your device, Numeric – number only entry for things like calculators and money (the one I am using the most), also Telephone, Url, Email, and Chat.

If you have done any sort of UI programming before, you know that limiting the characters that your user can put in significantly reduces the number of potential errors.

XAML Example:


<Entry Keyboard="Numeric" />

The Completed Event

Whenever the user finishes filling out the field and hits the enter or next key, the Completed event gets fired. You can hook up your Entry field to call a function whenever this happens.

For me whenever the user changes one of the values in my form, I recalculate the cashflow value of the property they are putting in. This way they get instant feedback on what one value has to the overall calculation.

XAML Example:


<Entry Completed="CalculateCashflow" />

Where CalculateCashflow is a function in the XAML’s code behind file.

TextChanged Event

This allows you to call a function as soon as the text in a field gets changed, not just when you are done changing it. It might seem like an odd thing to have since we already have a Completed event, but I will give you an instance I plan on using it for.

A couple of my form fields will be connected and be different representations of the same value. For instance, when estimating cashflow of a property it is common to estimate the repair and vacancy costs as percents of the rent.

In this case I will have a pair of split fields that are related. A repair_cash Entry and a repair_percent Entry. Whenever one of them changes, I want the other one to be updated.

XAML Example:


<Entry x:Name="repair_cash" TextChanged="SetRepairPercent" />
<Entry x:Name="repair_percent" TextChanged="SetRepairCash" />

Where SetRepairPercent and SetRepairCash are functions in the XAML’s code behind file.

Note that the Completed event callback function takes a sender object and an EventArgs object while the TextChanged event callback function takes a sender object and a TextChangedEventArgs object.

Really enjoying Xamarin so far. Looking forward to releasing a couple apps with it this year.

Getting Started with Xamarin: Gathering Resources

One of the first steps with learning anything is finding available learning resources for it. So today I am just finding a list of various tutorials, blogs, podcasts, books, and video to use for self teaching.

Note: I did not thoroughly inspect any of the resources in this list. Just basic searches and brief scan of the site to come back to later if it looks like it might be useful.

Books

Some people hate reading. If thats you, go ahead and skip this category. I for one love reading, though I definitely prefer good fiction to technical books.

A quick Amazon search will give you books like:

  1. Xamarin Mobile Application Development: Cross-Platform C# and Xamarin.Forms Fundamentals 1st ed. Edition
  2. Xamarin: Cross-Platform Mobile Application Development
  3. Mastering Xamarin.Forms

I would encourage you to go to amazon and search for Xamarin and see what comes up.

Blogs

Podcasts

Written Tutorials

Video Tutorials/ Youtube

There’s More

There are other resources out there but this is just to get started with. Also some of these links are to another list of link.

After getting an understanding of the breadth and scope of what learning Xamarin will cover, I will be picking a more narrow topic and exploring it further.

Cross Platform Development

The last 2 years of writing has been primarily focused on making games with Monkey-X. While I will continue to make games, the focus of my writing will be changing a little.

Last fall as I was getting ready to try to release games to mobile, I built my first Android app. It is a little rental property cashflow estimation calculator and I had a lot of fun making it and figuring out some of the Android development basics. But I didn’t write about it because the focus of this blog was about making games.

This is going to change.

New Focus

I am a web developer by day, and one of the reasons I like the web and web development is because you can write an application one time and as long as someone has a web browser they can use it. Not only that, but most of the logic can be kept on your server so you are really in charge of the environment the code is hosted in. Client heavy web apps using various Javascript libraries have changed some of this but for the most part it is true. And it has gotten even better as web browsers are converging better on standards.

One of my strong dislikes is having to do the same work twice. If I can find a way to do it only once I will. If I can build a system that does it for me so I never have to do it again I will.

This is one of the reasons I chose Monkey-X as I started making games. It deploys cross platform. Whether you want to put it on the web, on a phone, or on the desktop you can write your game logic in a single code base with usually some small tweaks per platform. The basic game logic remains the same.

Starting this month I will be adjusting the overall focus of the blog to cross platform development in general, no longer just games. The primary focus will be on the Xamarin platform.

Xamarin

Xamarin is a company and the name of their framework or toolset. It is a .NET based framework for allowing you to write apps that share as much code as possible between Windows 10, iOS, and Android.

Microsoft bought Xamarin last year (2016) and at time of this writing it is free for solo developers to get started with them.

The reason I am choosing it is the same reason I chose Monkey-X. Giving me the ability to write something once and then use that multiple times is exactly what I am looking for. And I want to create apps that work well on the phone. Their are some hybrid web solutions using things like Cordova where you write your app in Javascript, HTML, CSS and build it for the phone but that is not what I am looking for right now.

Bonus, Xamarin has a platform for making games with it called CocosSharp (part of the Cocos2D family) that I may utilize.

So look for coming updates on making cross platform apps and games.

Guide to Building a Monkey-X Game to Android

Step 1: Import the project to Android Studio

You will need to import the project to Android Studio as a Eclipse project. File – New – Import Project and select the folder with your Monkey-X android build. This is usually ../appname/main.buildv86e/android_new although your main.build folder may be named differently depending on which version of Monkey you are compiling against.

Step 2: Rename the package

The default package name is “com.monkeycoder.monkeygame”. This must be renamed as that is already taken on the Play store.

You will need to rename this in the Android Manifest, the main Java file, the res – layout – main.xml file, and the gradle build script. In the Java file you will need to rename the package at the top as well as the ANDROID_APP_PACKAGE variable (constant?).

I also recommend renaming the application and activity labels in your AndroidManifest.xml file from “Monkey Game” to your games title.

Step 3: Create an Icon

You will need to bring in your own icon for the app. This needs to be brought into the “res” folder and then referenced from the AndroidManifest.xml file.

Simply do a File – New – Image Asset and select the file you want to import. Android studio will generate various resolution versions of it for you.

I believe you will want at least a 512×512 pixel image. It kills 2 birds with one stone because Android will use it for the icon and 512×512 is the resolution needed to upload your icon to the Play store page.

Step 4: Test it on an actual device

After doing these steps, sometimes you miss something and the app will crash. Make sure to test your Android Studio build on an actual device now.

Step 5: Create a Signed APK

You will need to create a Signed APK file to upload. Android Studio makes this pretty easy. If you don’t have a key or a keystore already, it will walk you through setting one up. Then use the key to create a Signed build of your game that will be used to publish.

Step 6: Fill out information on Google Play and Upload the Signed APK

You now need to go through all of the questions and info for the Google Play store. This includes uploading your icon as well as a feature image that at time of this writing is 1024×500 pixels. You can put whatever you want here but probably should make it related to your game. Additionally it asks for screenshots. Most phones can do this although it could be difficult with an action game, or you could do it with an emulator.

There is also an area to put a link to a youtube video if you want to cut a short promotional video for your game.

Other steps include filling out a content rating questionnaire, linking to a privacy policy, and setting up purchases and adds (to name a few).

Quick and Dirty

This is a brief overview of the whole process. Mostly just notes to myself with reminders about changing things in Android Studio for the next time I release a game like this.

Hope you find this helpful.

First Monkey-X Game: The Boss Shoots Back

The basic structure for our game is there, we need to start to make it more interesting now. Our Boss could use some work. All he does right now is move up and down.

Not exactly Boss like.

The Boss Shoots

Step 1 in making the game more interesting is having the Boss on every level actually shoot at the player.

This is actually pretty simple because of the work we did creating the character and projectile classes and their methods.

Boss Bullets Hurt

Now that the Boss is shooting, we need to make sure that projectiles that hit the player follow the same kind of rules that the player’s projectiles do. When they hit the player, they should damage the character and then disappear.

This means adding a little more logic to our CustomeEngine’s OnObjectCollision method.

Now when you play the game, if the player character gets hit by one of the Boss’ projectiles, it should get damaged and the projectile should disappear.

Extra Projectiles for the Boss

It seems like the Boss should be a little more powerful. Shooting one bullet at a time seems a little weak. So we are going to have our Boss shoot 3 bullets at once. That should make it feel a little more challenging.

To do this, we are going to slightly modify our CreateProjectile method to take a width and height offset from the character that is shooting. This will also come in handy later when we want to add powerups.

Your Boss should now be a worthy opponent firing 3 bullets at once.

Time for a Theme

All of our hard work is starting to pay off. We now have a framework for setting up levels with a Big Bad Boss at the end of each one that can move and shoot at the player.

Next we will start adding some images to the game to give it a theme.

Essential Planning for 2017

It often seems like we don’t have the time to pause and lay out a plan. But I have found this to be super valuable. It is time well spent and actually reduces the time it takes to get to your goals.

A 12 Week Plan

One of books that I read/listened to last year was called the 12 week year and described a method to essentially get a year’s worth of work done in 12 weeks.

I don’t know if this is entirely possible, but I did find that having a set of goals for the whole year was not ideal. Also, writing a post to review them every month was probably not a best use of writing time. Twelve weeks seems like a pretty good number for a set of goals and then reviewing them afterwards.

Major Goals

Part of the 12 week year planning process is setting a larger goal that is to be reached in about 3 years. This is the vision of what you want your life to be like in 3 years.

You then set smaller goals to be accomplished in the next 12 weeks that will move you closer to the 3 year vision. These goals should be a little bit of a stretch for you. They should not be impossible, but also not super easy.

Finally you breakdown the actions you are going to take each week to accomplish your 12 week goal.

Applying the Process

I have decided to give this planning method a try in the first quarter of 2017 to see how I like it. The vision part is a mix of personal and business goals so I will not be sharing that here, but I will be tracking my 12 week goals.

Goals for the 12 Weeks

You should probably have no more than 3 major goals for each 12 week stretch. Otherwise you will not be focused and probably won’t come close to any of them.

My goals for the next 12 weeks are:

  1. Finish the Making Your First Game with Monkey-X tutorial series and turn it into a short E-book: Although the Monkey community is not all that large, it is a great little framework and perfect for beginners. I am still learning a lot writing this tutorial although I have decided to switch target frameworks as a specialty.
  2. Clean up and release Prism Ship to Android with 2 versions, 1 paid with no ads and 1 free with ads. This will be hooked up to Google’s service that tracks high score: I really liked getting a game out to Android last year and I want one that could start a small revenue stream. Not looking to make tons of money with this, but I already have the code and want more practice with releasing things to Android.
  3. Begin specializing in Xamarin: one of the key concepts I learned last year was the importance of specialization. It is tough. There are so many cool things to learn. But if I want to actually achieve success, I will need to start by focusing on a niche. One of the reasons I like Monkey is because it allows cross platform deploys. Xamarin does the same thing for cross platform mobile app development. The overall focus will be on doing cross platform development and deployments. I will still be making games, just not writing about it as much in the first quarter. Additionally if I don’t like Xamarin at all after 3 months, I will pick something different.

So lots of changes coming up, but ultimately a clearer focus. Looking forward to an awesome 2017.

First Monkey-X Game: Final Boss and Game State for Winning

The game is getting pretty playable, but like all good things it needs to come to an end.

If you remember from our little design exercise, we have a goal that will end the game. When we defeat the Big Bad Boss.

In this step, we will add the Boss into the game and create a Game Won state for when the player defeats the Boss.

Getting to the Big Bad Boss

The boss is going to be another character that we add to the game. We want him to be tougher than any of our enemies so far and we want him to shoot at the player to make it challenging.

Let’s start by creating the Boss character.

So now we have a field where we can put our Boss and we have a method that we can call to create him, but we don’t want to call it right away because we only want to have our Boss show up when we get far enough into the game.

So we will need 2 more things. First we need something to track whether or not it is time for the Boss to show up, and once this tracker is satisfied we don’t want to create another Boss.

Ok, at this point when you run your game, if you survive for 15 seconds or so you should get to a point where the small enemies stop getting created and you see a large purple shaded box representing the boss.

Boss Behavior

Now that we can get to the Boss, we want an EPIC BOSS FIGHT! Ok, maybe it won’t exactly be epic at first, but we can start by giving him some basic behavior. We also need to add the ability to shoot the Boss.

To start with we want to add some simple AI to the Boss’ movement. Nothing fancy, just moving the Boss up and down.

Now your Boss should go up and down the screen. Really, really simple pattern for now. We can get fancy and create more complicated logic for the movement later.

Damaging the Boss

Now that the Boss is moving, we need to be able to destroy it so we can win the game. This means we need to wire up the collision detection for our player’s projectiles and the Boss hit box. We also need to make sure the Boss takes damage when it gets hit.

Now projectiles will collide with the Boss but our current Character code won’t handle this correctly after the Boss gets hit. So we need to make a few tweaks to the Character class.

Now you will need to go into your main Game class and update the constructors for your Player and the Final Boss. The regular enemy constructor is fine since it just uses the default. There is also a check when firing projectiles that needs updating.

Now your projectiles should hit the Boss and damage it. However you should notice that once the Boss’ health drops to 0, the Boss is still there and the projectiles just fly past.

We still need to make the OnUpdate method a little smarter about what happens when the Final Boss is destroyed.

Destroying the Boss and Next Level

Destroying the Final Boss is simple enough. In the OnUpdate code, simply add a check to remove the Boss from the game when his health reaches 0. But what we really want to do is change scenes to a show that we beat the boss.

In order to give us some room to give the game more depth, we are not actually going to have the player win the game after beating the first boss. Instead we are going to have the game transition to a Next Level scene.

Now we have a scene we can transition to, lets transition to it when our Boss dies.

And we don’t want to get stuck there so lets add a method to allow the player to continue.

Now when you play the game, after you destroy the Final Boss, you should get to the Next Level scene. Then if you hit enter it should start play again but your score will remain the same.

Actually Winning

What we really want to do in this chapter is give the player the ability to beat the game. In order to do that we need to add 1 more scene, the Game Won scene.

If you have been following along, you have already gotten pretty familiar with adding scenes to the game by now, and could probably do this yourself. Just in case here is the code for the Game Won scene.

Now we need to be able to actually get to this scene. Defeating the Boss doesn’t get us there, it only gets us to the next level, and right now we have infinite levels.

First let’s put a way to track what level we are on and set a maximum number of level. Then we can use those 2 values to tell us when to end the game.

Now whenever we get to the Next Level, lets update our current level and see if it is the final level.

Now when the player beats the boss on the last level, they have beat the game.

In the next section we will make the Boss a little tougher and let him shoot back.

How’d I do? Full Review of 2016

Its 2017. A new year and a new set of goals.

But one of the things I learned in 2016 is the importance of occasional reflection and evaluation. So before setting some new goals for myself with this blog and with making games, I am going to reflect a little on this past year’s goals and how I did.

Writing

Goal: Write 3 posts per week and publish 2 to build a small buffer of unwritten posts. This would have been 156 posts written and 104 published.

Actual: 70 posts written and published.

What’s great about this? Even though I did not hit my goal, in fact I came in just under half of the writing goal, I almost tripled my volume from 2015 (only wrote 26 posts that year). This is fantastic!

Games

Goal: Make one game per quarter (every 3 months) and release each of those games on the Play Store for Android. So 4 games and all released.

Actual: 2 Games finished, 1 about 50% of the way, and 1 idea kind of left to die. Only 1 of the 2 finished games was published to the Play store.

What’s great about this? This is the first time I have released a game on Android. I can now point people to my game or show it to them from my own phone. I learned a ton turning it into a multiplayer game and releasing for Android that can help me out in the future. In fact I am probably going to go back and release at least one of my games from 2015 to Android.

Reading

Goal: Original goal was 1 book on game design every 6 months, which I modified to 1 per quarter. So 4 books on game creation or game design for the year. Also read 1 article on game design or watch 1 video on it every week.

Actual: I read 3 books specifically related to making games and game design and several that were helpful, such as Clean Code. Not only that but I read over 25 books total last year. For the articles and videos, I did not keep track of them like I should have, but I read way more than 52 articles and watched quite a few videos and interviews on the subject. One of the goals I exceeded greatly.

What’s great about this? I learned a ton this year about making games, game patterns, game types, and different parts of the game making team. And I found so many more books to read for 2017.

Audience

Goal: Roughly 100 unique visitors a month by the end of 2016.

Actual: More like 30 or 40 although I had a couple months where it was more than 100. I switched analytics trackers in December so I lost some history, but this is to give me better information in the future.

What’s great about this? I actually started telling people about my blog and sharing some of my posts. This is way better than last year where I am not sure that more than 5 people visited my blog the whole year. Also, I actually hit my goal a couple of months.

Important Lessons

Written goals are super valuable. And they are even more valuable if you review them periodically.

Simply having the goal of getting 100 people to view my blog every month would not have been enough if I had not taken a measure every so often to see how I was doing and to remind myself to do something about it.

It also helps you see when your focus is on one of the goals and the others are suffering because of it.

Bigger goals are better because you are going to fail anyway.

One of the important things I learned this year from reading the 10X Rule by Grant Cardone is that most people fail at their goals. Only meaning that they don’t hit 100% completion on them.

So do you want to fail at a small goal or a big goal. If you are only going to get 50% of the way to your goal, you want a bigger goal. Because 50% of 100 is 50, but 50% of 1000 is 500.

I really felt this with writing especially. Upping my writing goal, even though I did not hit it, significantly increased my writing volume.

Overall 2016 was a huge improvement and I am looking forward to making more progress in 2017.

First Monkey-X Game: Restarting the Game

Now that the player can get to a game over state, we need to let them restart the game without having to refresh the web page.

Hit ENTER

We will add a new check for after the player has been destroyed for the ENTER key to be pressed to try again. Also we will add a message in the game over screen to tell players what they need to do.

Let’s start by adding the instructions to the Game Over screen on how to restart.

Now we want a way to reset the game whenever ENTER is pressed from the Game Over scene. We will do this by creating a small method in our game that goes through and deletes all of our enemies and bullets and recreates the Player.

You will notice that we have a new method here called CreatePlayer. Our next step is to refactor the code from our OnCreate method into this method so we can recreate our player when we reset the game.

The final step is to add the code to call the GameReset method when the ENTER key is pressed from the Game Over state. This will make its home in the Game’s OnUpdate method.

And now our player can easily start over when their little character gets destroyed.

Our next step will be creating a boss character and an end state to our game.