A View Inside My Head

Jason's Random Thoughts of Interest

NAVIGATION - SEARCH

Self Promotion: My Games

As a web developer by trade, I find the ability to create an application using HTML5, CSS3, and JavaScript to be very compelling. In my opinion, Microsoft did a fantastic job of offering this as one of the language choices for developing Windows Store apps – you get native packaging of your web assets into an application that can be sold in an app store without needing to use a webserver, or a hybrid app container like PhoneGap, etc. 

I took advantage of this to write a handful of games that have been published.

Logo Image: Knave Defender   Logo Image: Knave Blackjack

Logo Image: Knave Craps   Logo Image: Knave Slots

Logo Image: WuX   Logo Image: WuX Defender

Knave Defender

The very first game that I wrote for the Windows Store was Knave Defender:

This game started out with the concept of being part of a larger Blackjack trainer – a series of mini-games intended to build skills needed for playing Blackjack. This particular mini-game was intended to strengthen the ability to quickly sum up a hand. The goal is to build a hand of 21 before an invading UFO lands (to destroy the ship). If you bust, then the invader escapes. If the invader lands, you lose a life.

Being my first game, I didn’t know when to stop adding things to it.  The original Knave Defender had a full soundtrack and sound effects (that I purchased rights to for about $50 total). It had multiple levels. It had a menu, and a pause mode, and configuration options.  And, after a year and a half of being in the store, it has only 189 downloads.

Just this week, I rewrote Knave Defender as a Universal App with the intention of releasing it for the Windows Phone, too. I stripped out a lot of the extra cruft, and turned it into a simple repeating invader game. Keeping with the original vision of being a Blackjack trainer, I disabled the display of the hand’s sum so that the player has to do that part in their head.  I also added a global leaderboard so that your high scores can be compared to other players from around the world.

Screen shot 1

 

Knave Blackjack

The first step to submitting an app to the Windows Store is to reserve a name for the app. As you can imagine, “Blackjack” was quickly snapped up by somebody out there, so I had to come up with another interesting name.  So, even before Knave Defender was released, I had the name “Knave Blackjack” reserved for this game.

Knave comes from a card that existed in the deck of playing cards before the Jack card was added. It was of the same rank as a Jack card today. One reason for its replacement was because the Knave’s index was “Kn” and was often mistaken for a King (“K”) in a fanned out hand held by a player.  So, in some ways, “Knave” is a synonym for “Jack”, and that’s why I use it today for all of my casino-related games.

The idea to write a blackjack game came from a presentation that I gave at Devlink with Mike Eaton. We were doing a parity talk to show how a Windows Store app would be developed in HTML/JavaScript (my preference) versus XAML (Mike’s).  Not wanting to do another To-Do list as the demo, we decided on using Blackjack as the theme instead. My part of that demo eventually morphed into Knave Blackjack:

Screen shot 1

I fell in love with CSS transforms while writing this game, and made the view of the table something that the user could control (panning, tilting, and zooming are all accomplished using touch gestures that change a style on a DIV).  I also designed the table to be skinnable for a marketing idea that I have yet to bring to fruition.

 

Knave Craps

For me, the best game in a casino is Craps, so I just had to follow up Blackjack with a realistic Craps game. A casino opened up along my daily drive home, so I had a place to play (I like to call that “research”) in order to observe how the dealers handle bets and payouts. After a few months of work, Knave Craps was released:

Screen shot 1

Writing Blackjack had taught me that people inherently do not trust Random Number generators, no matter how careful you are at trying to ensure random results. People even go so far as to accuse the game of intentionally doing something in order to screw over their bets.  (Their electronic bet, mind you, that cost them no real money to place). The reviews that I get for the Craps game show that the same issues exist.

To mitigate this, I added a feature to track statistics over time to see what the roll distribution is. I also added a feature to have thousands of rolls performed to ensure that the results fit the expected curve. And, to put the player in charge, I wrote the randomizer to shuffle through possible rolls over a 3-second period, allowing the player to stop the randomization at any time. 

 

Knave Slots

After Craps, I wanted to do one more casino-style game, but I also wanted it to be unique.  I came up with the concept of combining several games into one: Slots (for randomization), Blackjack, Baccarat, and 3-Card Poker.  The thought was that the slot machine aspect would generate three random cards for the player, and three for the house. The player would place a bet on the winner of any hand (either player, dealer, or tie), and spin the reels.  This game became Knave Slots:

Screen shot 1

 

WuX

At some point while writing the casino games, I started thinking about game theory and how randomization is handled by things like Rock-Paper-Scissors. This introduced me to the RoShamBo, a generalized game that Rock-Paper-Scissors is based on. A RoShamBo has an odd number of elements available, with each element beating half of the other elements (and beaten by half of the other elements). So, in Rock-Paper-Scissors, there are three elements, with each choice winning and losing to one other choice (not considering ties).

Being a fan of the World of Warcraft, I wanted to write a game that used the Elements to form a RoShamBo. Looking for some historical context, I stumbled upon the ancient Chinese Wu Xing (translates as five rows, but it is often taken to mean five elements in Western cultures). This gave me an odd number of elements to work with and rules about which element strengthens or weakens another element.

So, Wood, Fire, Earth, Metal, and Water made their debut in a puzzle/strategy came that I called WuX:

Screen shot 2

In WuX, players take turn placing a random element in a cell. They are blind to what the opponent has placed until both players have claimed the same cell, and then a decision is made using the Wu Xing RoShamBo. The goal is to get three-across (using the center cell), and if that is not possible, then to win more cells than your opponent.

It’s a puzzle in that you are trying to figure out what your opponent has placed where, and a strategy game because you need to keep enough of your elements around to beat their remaining element, especially for the all-important center cell.

WuX maintains a global leaderboard that tracks a cumulative score, as well as the number of wins, losses, and tie games over a player’s career.

 

WuX Defender

After the rewrite of Knave Defender to make it focused on being a Blackjack trainer, I decided to make a variant of the game using concepts from WuX. Each invader starts with a random element. Instead of cards, the player gets a random element to assign to an invader. The goal is to “weaken” the invader to destroy it, but it’s not always possible, so you have to try to decide how to dispose of elements in order to move on.  Sometimes, this results in strengthening an invader (i.e., adding wood to fire will strengthen the fire).

This game became Wux Defender:

Screen shot 1

 

What’s Coming

WuX started out as a mini-game in a larger game that I’m currently working on called Amassment. I decided that the WuX aspect made Amassment too complicated, so that’s why it was pulled out into its own standalone game. I’m hoping to have Amassment in the store before Summer 2014.

HTML/JavaScript Universal Apps: A First Look

For me, one of the most exciting and long-anticipated announcements from last week’s //BUILD conference is the upcoming ability to write Windows Phone 8.1 apps using HTML and JavaScript.

As a web developer, I spend a tremendous amount of time every day writing client-side code that runs in a web browser. I have made a huge investment in mastering these skills and keeping up with emerging trends and “best practices”. The declarative layout and rendering languages of the web, HTML and CSS, are widely known standards that for the most part work identically between platforms (albeit, with a few platform-specific idiosyncrasies). So, it makes perfect sense to me that HTML5 is the best solution for writing cross-platform apps.

Windows Phone 8.1, due for release later this month with widespread over-the-air updates happening this summer, will finally have parity with its tablet/desktop siblings in the ability to run WinRT apps.  This app model allows developers to use the language of their choice to develop apps, from C++ to .NET to HTML/JavaScript.

Since Windows 8.1 and Windows Phone 8.1 will share the same app model (as will the Xbox One, it was announced), the natural question is: Can I write my apps once and have them just work on each platform?  The answer, for the most part, is ‘Yes’, using a new solution type called Universal Apps.

Starting with Visual Studio 2013.2, you will find new project types for creating Universal Apps:

image

Creating a new Universal App project will make a solution with three projects inside: a Windows app project, a Windows Phone app project, and a Shared Code project:

image

Most of your application’s code will go into the Shared project. But, here’s where reality sets in: because a phone is different than a tablet/desktop, both in screen size, memory, and general platform capabilities, it is necessary to maintain some platform-specific pieces within their own project types.  So, any artifact that exists in a platform-specific project will override the same file from the shared project at build time.

For HTML/JavaScript apps, this primarily means maintaining different stylesheets between projects. But, in my tests, there are a few other things that didn’t “just work” while converting an existing Windows 8.1 app into a Universal App. These differences may require some code refactoring in order to separate the features that are only available on a particular platform from the rest of your shared code.

Incompatibilities that I’ve found:

  • No SettingsFlyout: In Windows 8.1 Apps, settings are maintained within flyouts that are accessed from the Settings Charm. This does not seem to be implemented on the phone, so you will need to find an alternative way for the user to specify settings, and refactor your codebase accordingly.

  • Web Fonts: It is very easy to bring a new font into a HTML/JavaScript Windows 8.1 app using Web Fonts (fonts that are temporarily used, but not installed to the system).  For my Windows 8 tablet/desktop apps, I’ve been using Embedded OpenType fonts (.eot).  This format does not appear to be supported on mobile Internet Explorer 11 (which is what the phone’s HTML/JS app container is based upon).  However, the Web Open Font Format (.woff) does work. [UPDATED]

  • Advertisements: In my Windows 8.1 games that are in the Windows Store, I use Microsoft’s advertising platform to earn a little bit of revenue from an otherwise free-to-play game. The Ad SDK is available for use within the Windows project, but not the phone project. Note: This incompatibility is for HTML/JavaScript project types only. The C# project type, for example, does provide an Ad SDK for phone apps.

  • Audio: My games make use of audio, as you would expect, for things like click feedback, explosions, etc. This is relatively straight forward using the HTML5 Audio element/object. Since I don’t have 8.1 installed on actual hardware, I’ve only been able to test using the Windows Phone emulator in Visual Studio. In those tests, there are severe synchronization issues with HTML5 audio. Sometimes sound never plays, and sometimes there is a lag of a few seconds before a sound finally plays. It seems to be a memory management/caching thing, because once a sound has played for the first time, there’s usually little lag if that same file needs to play again within several seconds. [Confirmed on Device – Nokia Lumia 928, delays exist]

    [Update]
    The issue with audio lag may be how I was initializing the code. For example, to play a sound effect from JavaScript, I’ve been using code in my Windows apps like:
    var sfx_click = new Audio("/audio/menuclick.mp3");
    sfx_click.msAudioCategory = 6; // GameEffects  
    sfx_click.volume = 0.8;
    sfx_click.play();
    

    I found a remark on MSDN that states:
    You must set the msAudioCatogery before setting the src property in code.

    So, I have rewritten the above to now look like:

    var sfx_click = new Audio();
    sfx_click.msAudioCategory = 6; // GameEffects 
    sfx_click.src = "/audio/menuclick.mp3";
    sfx_click.volume = 0.8;
    sfx_click.play();
    

    Though I am still experimenting, this seems to have greatly improved the lag situation (so explosions happen at the appropriate time, etc).
  • NuGet: Integration with NuGet seems a bit weird, if not incomplete. You can add a package to the platform-specific projects individually, but not to the shared project. And, NuGet itself seems to get confused, because even though the package is added to the packages folder, none of the artifacts (scripts, css, etc) get created within the project itself. So, if there’s a library that I need to use in both places, what feels natural is to use NuGet to install the packages, and then use “Add Existing” to include files from the platform project’s packages folder into the shared project… but, this means that those artifacts are not truly maintained by NuGet.  If there’s then an update to the package, then I’ll need to manually repeat the process.

  • Windows.ApplicationModel.Store.CurrentApp.getAppReceiptAsync(): It seems, at least at the moment, that the XML returned from the Windows store differs from the XML returned from the Phone store. Specifically, the Phone document includes a default xmlns on the document element, while the Windows document does not (so, code that uses XPath queries will need to be handled conditionally depending on the platform).
  • Speech API: While converting Knave Craps to the phone, I came across an “Access Denied” error while initializing the Speech Synthesizer. I’m trying to come up with a workaround or find out the root cause.  The line of code that resulted in the exception:
    var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();

Sideloading Windows 8.1 Apps

I have created several games for the Windows Store. The process of writing and submitting an app for publishing to the consumer-facing store is well-scripted, with Visual Studio taking care of packaging everything needed into one file, which is then uploaded using the developer portal website, and then finally signed and published by Microsoft’s back end systems.  Once published, the user discovers and installs the app using the Windows Store app on their own machine.

But, what about deploying Line Of Business (LOB) apps for enterprises, which are installed for use only within a corporation (and, thus, are not appropriate for hosting on the public consumer-facing store)?  For now, deploying an application to enterprise machines requires a process known as Sideloading. This can be thought of as the equivalent of manually running Setup.exe in order to install desktop applications, though the requirements and processes involved are different.

First, when building the appx, the developer will need to use a code-signing certificate that links to a trusted root CA since it will not be signed by the Windows Store. The preferred thing to do would be to purchase a code-signing certificate from a company already in the default list of trusted Third-Party Root Certification Authorities (such as DigiCert Assured ID Code Signing certificate).  It should also be possible to use a self-issued certificate that belongs to the enterprise, albeit with a bit of extra work to install root CA certificates onto all of the target machines.

To set the certificate from within the Visual Studio project, simply double-click on the package.appxmanifest file, navigate to the “Packaging” tab, and then click the “Choose Certificate” button.

Next, the user’s machine must have an appropriate operating system.  Side Loading is NOT permitted on the edition of Windows 8.1 that is targeted for home users (known simply as Windows 8.1).  So, this currently means that the user’s machine must be running Windows RT 8.1, Windows 8.1 Pro, Windows 8.1 Enterprise, or Windows Server 2012.

Next, the machine must be configured to allow trusted apps to be installed.  This can be performed using the Group Policy Editor by setting “Allow all trusted apps to install” setting to “Enabled”:

image

Note: This Group Policy setting simply sets the following registry key: HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Appx\AllowAllTrustedApps = 1

If the machine is running Windows 8.1 Enterprise, and is domain-joined, then it is all set to side-load applications.  Windows RT 8.1 and Windows 8.1 Pro machines must first perform a one-time activation of a Sideloading Product Key, which is acquired using volume licensing channels (sold in bulk, and costs roughly $30 per machine).

UPDATE: Microsoft will be allowing domain-connected 8.1 Pro machines to side-load applications just the same as 8.1 Enterprise. And, side loading product keys will be available for free from volume licensing, or for around $100 from Open License. You only need one product key per organization now, because they're unlimited.  See: http://blogs.windows.com/windows/b/springboard/archive/2014/04/03/windows-8-1-sideloading-enhancements.aspx

To install and activate the Sideloading Product Key on a machine, open a command prompt as Administrator, and then execute these commands:

  1. slmgr /ipk <unique 25-digit sideloading product key>
  2. slmgr /ato ec67814b-30e6-4a50-bf7b-d55daf729d1e

Finally, Windows Store apps are installed per user, so the following needs to be repeated for each user that will log onto a given machine (or automated using Microsoft System Center 2012 Configuration Manager):

  1. Open the Windows Powershell prompt (i.e., type Powershell on the Start Screen and select Windows Powershell from the search results).
  2. Execute the following:
    Add-AppxPackage "C:\path\yourapp.appx"
  3. Visual Studio may have packaged your .appx as an .appxbundle, so substitute that file instead.  As a tip, when copying a file path from Windows Explorer, hold the Shift key when right-clicking on a file, and you’ll have an extra menu item called “Copy as Path” that will include the directory and filename all as one string. This can be pasted into the Windows Powershell window using a right-click.
  4. If the appx has a dependency, such as the WinJS library, then you must include this as part of the Add-AppxPackage command:
    Add-AppxPackage "C:\path\yourapp.appx" -DependencyPath "C:\path\Dependencies\Microsoft.WinJS.2.0.appx"

 

What can go wrong?

In short, there are a lot of things that can go wrong when side loading apps on Windows 8.1 – probably too many to document in a simple blog post.  However, here’s a couple of cryptic things that we experienced when trying to deploy an app for the first time:

Application would not install.  Error message:

Deployment failed with HRESULT: 0x80073CF9, Install failed. Please contact your software vendor. Deployment Add operation on Package … failed with error 0x8007000D.

Diagnosis and fix: It was found that JavaScript libraries that were installed using NuGet were saved using a Windows 1252 encoding.  HTML/JS apps need to have their JavaScript files saved using a UTF-8 with BOM encoding so that the scripts can be precompiled. 

Note: If Visual Studio 2013 is installed on a machine, then the appx would sideload just fine (resulting in me repeating over and over “But, it works on my machine!”) Without Visual Studio installed, this very descriptive error was encountered when my client attempted to sideload the appx.

To correct this, open each .js file in the Visual Studio project, then choose the “Advanced Save Options” item in the File menu.  Change the Encoding to “Unicode (UTF-8 with signature) – Codepage 65001”, then click “OK”.  Save the file, then rebuild the project.

image

Note: Running the appx through Windows App Cert Kit (WACK) will also point this out, but in my case, I had updated a NuGet package and thought I could get away without running the WACK tests again since they had previously passed, and my app was working just the same with the new updates.

 

Application installed without error, but would not launch. Red X on live tile. Event Log:

/Applications and Services Logs/Microsoft/Windows/Apps/Microsoft-Windows-TWinUI/Operational

Activation of the app …!App for the Windows.Launch contract was blocked with error 0x80073CFC because its package is in state: Modified.

Diagnosis and fix: This is what you will find when Sideloading has not been activated, either because a Sideloading Product Key was not installed, or the Windows 8.1 Enterprise machine is not domain-joined. 

For testing purposes, a developer or outside organization may have Windows 8.1 Enterprise from MSDN installed, but not domain-joined.  You cannot obtain Sideloading Product Keys from MSDN, so in order to test sideloading, that machine will need to be joined to a domain.  What I did for my standalone development machine (running Windows 8.1 Enterprise) was to create my own Active Directory on a Windows Azure virtual machine, and then perform an offline domain join using djoin.exe (http://technet.microsoft.com/en-us/library/offline-domain-join-djoin-step-by-step(v=ws.10).aspx).

Inside Bitcoin: What is a Bitcoin?

Bitcoin is best described as an open source digital currency and decentralized/peer-to-peer payment system. Okay, but what does that mean? 

Let’s break it down:

  • Open Source: Every aspect of how Bitcoin works is public knowledge. The primary client software, called the QT wallet, is an open-source project hosted on GitHub, so any developer can review the source to look for bugs or code that introduces malicious behavior.
  • Digital Currency: The core purpose of Bitcoin is to serve as a currency, or form of money. Currency, in general terms, refers to a medium of exchange. That is, I give you something of value in exchange for something else of value. Both parties must recognize the value of each item being exchanged to be equal for the system to be valid.

    Bitcoin fulfills one half of that exchange, being a medium that holds value. It is digital currency because it exists only as numbers in cyberspace, protected by cryptographic information that only the owners of each Bitcoin are privy to (because of this, it is also commonly referred to as a cryptocurrency).  Ownership of Bitcoin can be transferred from one person to another.
  • Decentralized/Peer-to-Peer Payment System: Bitcoin is designed so that no one person or agency is in control of the system. It’s truly the people’s currency, where users that give Bitcoin its value also maintain the underlying system that allows value to be transferred between owners.

Value in Bitcoin is assigned by address. A person can own any number of addresses – they are very cheap to create at random, and the probability of your computer creating an address that collides with one owned by another person’s is practically 0%.

To spend a Bitcoin that you own, you transfer it to the recipient’s address. This is known as a transaction. A transaction has two parts: IN and OUT.

While it’s convenient to think of a Bitcoin address as being like a bank account, where all of the value is accumulated and stored, the reality is that the value is stored in transactions. You can only spend value that has been sent to you as the OUT part of a prior transaction, and you spend it by referencing that OUT as the IN of your new transaction. So, the balance of any Bitcoin address is the sum of all of the unspent transaction OUTs destined for that address (referred to as UTXO).

When you create a new transaction, using your Bitcoin-QT wallet or some other piece of client software, the transaction is broadcast to the entire network of nodes that make up the Bitcoin network. Eventually (usually within 10 minutes), that transaction is recorded into the permanent public ledger, and then everyone in the world knows that the Bitcoin that you spent has been transferred from your address to the recipient’s address (and they are then free to spend it themselves).

One important thing to note: Bitcoin is built upon the concept of distrust.

“What’s that!?” you say?

Since Bitcoin exists only on the Internet, and there is no one centralized authority to trust, then you must question and validate each piece of data that the system provides to ensure that it is real and not generated by a clever thief. This is why all of the details about how to verify data is public knowledge – as long as the majority of the users participating follow the same rules, then it becomes impossible for somebody to game the system by introducing data that does not conform to those rules.

As a result, every node that participates in the Bitcoin network must download and verify every transaction since the beginning of time (which was in 2009 for Bitcoin itself) to ensure that they are valid and have not been tampered with. For each transaction downloaded, the node must ensure that the IN part had not been previously spent within another transaction (known as a double spend). As more and more nodes confirm the validity of transactions, the confidence in the transaction increases and the risk of a double spend occurring decreases.

Note: Some things above have been generalized for the purpose of being a general overview. The goal of this blog series is to dive deeper into how Bitcoin works, which will clarify/expand upon some of the vague or technically incomplete parts listed here.

1KdGkhNSBPBp64HrqrNUWPYHoEjm3CXcfd

Inside Bitcoin: SHA256

SHA256 is a cryptographic hash function. Its purpose is to take in an arbitrary length of bytes (the “message”), perform number crunching, and then produce 32 bytes that uniquely represents the original message (the “hash value”, or “digest”).  A small change to the message, even toggling a single bit somewhere, results in a vastly different digest due to a property of cryptographic hash functions known as the “Avalanche Effect”. 

While it is easy to calculate the hash code for any given message, it is considered to be infeasible for somebody to generate a message that results in a particular hash code. This makes SHA256 a one-way function. Likewise, it is considered infeasible at the moment to find two different messages that have the same hash code (known as a “collision”). 

Note: This does not mean that collisions are impossible, though, because after all, the output is only 32 bytes for any length of input.  So, being fed enough bytes will eventually result in a repeated hash code.  Being infeasible in this case simply means that collisions are random events that cannot be used to create other collisions for other messages.

Because of these properties, hash functions like SHA256 are often used to verify that a message hasn’t been tampered with, or hasn’t become corrupted during transmission.  It is also convenient to store the hashes of passwords in a database instead of the passwords themselves, so that in the event of a security breech, the secrets are not revealed.

Calculating a SHA256 hash code consists of multiple rounds of bitwise operations: and, or, xor, shifts, and rotates. Because there are no conditional branching operations in the algorithm, SHA256 can be implemented entirely in hardware.  This is the basis behind FPGA and ASIC mining devices (a topic for a later blog post).

Try it yourself! Type a message to view the resulting SHA256 hash, and see how small changes to the input greatly impacts the results.  Also, try to find a message that results in one or more leading zeros.

SHA256 Sample

1KdGkhNSBPBp64HrqrNUWPYHoEjm3CXcfd