Angel \”Java\” Lopez on Blog

April 26, 2013

TDD Kata (1): Rock Paper Scissors Lizard Spock

Two weeks ago, I read at Spanish list TDDev a new kata published at the blog Aprendiendo TDD:

Piedra Papel Tijera Lagarto Spock

based on a problem published in (Spanish post)

http://www.solveet.com/exercises/Kata-Piedra-Papel-Tijera-Lagarto-Spock/20

I took the description from Wikipedia article:

http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock

The rules of Rock-paper-scissors-lizard-Spock are:

  • Scissors cut paper
  • Paper covers rock
  • Rock crushes lizard
  • Lizard poisons Spock
  • Spock smashes (or melts) scissors
  • Scissors decapitate lizard
  • Lizard eats paper
  • Paper disproves Spock
  • Spock vaporizes rock
  • Rock breaks scissors

And then, I started to code the solution using TDD, in C#. You can check re result at:

https://github.com/ajlopez/TddOnTheRocks/tree/master/SpockGame

The commit history reveals commit by test:

https://github.com/ajlopez/TddOnTheRocks/commits/master/SpockGame

See the first test/commit: it didn’t compile. Then, it started to compile, but with red result. Then, I added the minimal code to pass the test, and refactor, and so on.

I decided to have two tests, one per permutation: testing Scissors cut Paper, and other testing Paper is cut by Scissors. I could refactor the test to have an internal method testing in both ways

The initial design was based on:

- Having an instance of Game class (the alternative was to have static methots, directly in the class)

- Having an enumeration for game options (Play.Scissors, etc…)

- Having an enumeration for the play result (PlayResult.Tie, PlayResult.FirstPlayer…)

Instead of having play result, I could put a method that compare two options, deciding which one is “greater”. Today, I could refactor the implementation to use that approach.

See the last refactor: I could leave the code as is, with if command deciding which play wins, to decide when the first player wins:

But I wrote a  new way:

based on Wikipedia article suggestion:

One way to remember the rules is to remember the standard "rock-paper-scissors" ordering, where each gesture defeats the one before it, and is defeated by the one after. But then add the two novel gestures near the word they approximately rhyme with:

  1. Rock
  2. Spock
  3. Paper
  4. Lizard
  5. Scissors

In this expanded list, each gesture is defeated by the following two options, and defeats the preceding two.

But I feel the previous code is more clear. Sometimes, we must decide between having a clear code vs a clever one.

More TDD katas are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

April 25, 2013

Mass Programming Language (1) Inception

Filed under: .NET, C Sharp, Mass, Open Source Projects, Programming Languages — ajlopez @ 9:09 am

Next Post

Three weeks ago, I was working on the implementation of an interpreted language, written in C#. The new language is called Mass (dedicated to  @MArtinSaliaS):

https://github.com/ajlopez/Mass

The current solution has three projects: a class library, its tests, and a console program, mass.exe, that launches Mass programs

You can run a hello.ms:

mass hello.ms

The classic Hello world source code:

println("Hello, world")

An example with classes and objects

class Person
	define initialize(firstname, lastname)
		self.firstname = firstname
		self.lastname = lastname
	end
	
	define getName()
		return self.lastname + ", " + self.firstname
	end
end

adam = new Person("Adam", "TheFirst")

println(adam.getName())

An example with access to .NET types and objects:

dirinfo = new System.IO.DirectoryInfo(".")

for fileinfo in dirinfo.GetFiles()
	println(fileinfo.Name)
end

The idea is  to have a dynamic language that leverages an underlying language provided with a rich class library and ecosystem, like in AjSharp and other of my projects. Before Mass, I was working on:

- Implementing Python in C# (see PythonSharp)

- Implementing Ruby in C# (see RubySharp)

- AjSharp (see repo and post)

But this time I wanted to implement something with simple sintax and semantic. Indeed, I was playing with “simple” ideas for a compiler over Javascript, see SimpleScript (1) First Ideas.

Then, with Mass, I deliberately wanted to avoid:

- Multiple commands in the same line (I discarded ‘;’ like in Ruby)

- Syntax based in spaces and indentation (Python discarded)

- Function invocation using only the name; Mass impose the explicit use of parenthesis (Ruby discarded; Mass is like JavaScript)

- Base values and classes (integers, strings, lists, etc…) having a crowd of methods (like Ruby and Python). No, Mass prefers to expose and use the underlying language/class library.

Then, I wanted:

- Functional values, as first-class citizens, like in JavaScript. So, having to put explicit parenthesis to invoke a function allows me to use the name of the function as a functional value

- Dynamic objects: each object can be extended at any moment, with new instance variables, object functions, a la JavaScript

- Syntax based in lines: each command has its own line. No command separation

- Syntax based in keywords: the end of a command list is marked with ‘end’, no braces

- As far as possible, only one way to do something, instead of the many ways motto a la Perl

- Complete keywords, then ‘define’ instead of ‘def’

- Simple inheritance at classes. But Mass could be expressive without written classes, using native classes from .NET framework and other libraries. It could be used as an scripting language.

- Explicit setting of variables that are out of the local scope (a topic for next posts)

- Variable scope by file, like in the require of JavaScript/NodeJs/CommonJS

- Module by file, with a require that automatically searches in directories, a la NodeJs/CommonJs. Notably, Mass can consume node_modules folder, so Mass module can be published and installed using NPM!

- Package manager, using NPM. You can use package.json to declare the dependencies, and publish new modules at NPM (using ‘mass-‘ as the suggested namespace).

In upcoming posts, I will write more details about implementation, guiding design ideas, examples. But now, you can see the code and the test examples at public repo. And yes, all was written by baby steps, using TDD.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

May 29, 2012

AjGenesis Code Generation in .NET, Javascript and Ruby, All the Gates are Open

Usually, I get up early in the morning. Today, I got up a bit earlier, with some ideas about how to implement a simple template engine for my personal project, AjGenesis in Ruby. Then, I put my hands at work, and 3 hours later I had a solution, built using TDD (I made frequent commits, so you can see the progress of development in the GitHub Log).

The result at my GitHub account:

https://github.com/ajlopez/AjGenesisRb

Initially, I planned to use one of the template engines already available in Ruby, like Haml. But I decided to write my own implementation. Past week, I wrote AjGenesis in Javascript/NodeJs, see:

https://github.com/ajlopez/AjGenesisNode

In that project, I separated the template engine in another package:

https://github.com/ajlopez/SimpleTpl

In this way, I designed the template format to be similar to the original templates in classic AjGenesis.

I reuse the Javascript template engine in another new project (code kata of the past weekend):

https://github.com/ajlopez/SimpleMvc

a simple MVC implementation over NodeJs/Express.

So, now you have three projects:

- Classical AjGenesis code generation, implemented in .NET (see examples folder)
- AjGenesis in Javascript/Node, with SimpleTpl template engine, with interpolated Javascript expressions, and embedded Javascript commands (see samples folder)
- AjGenesis in Ruby, with a similar internal template engine, with interpolated Ruby expressions, and embedded Ruby commands (see samples folder)

AjGenesis in Javascript was published to npm (node package manager) as beta.

AjGenesis in Ruby is still not a gem: work in progress.

REMEMBER: all these projects GENERATES the text artifacts YOU WANT to generate. There are not limited to a technology, platform or programming languages.

It’s really interesting to see how simple ideas can be reimplemented in dynamic languages. Next steps: more samples, ruby gem, node package, and web site implementing code generation as a service (ASP.NET implementation commented in my old post). (see AjGenesis: Basis of Its Implementation).

Pending implementation languages: Python, maybe Java.

(Original photo from: http://commons.wikimedia.org/wiki/File:Table_Rock_Dam_during_April_2008_White_River_Flood.jpg)

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

March 13, 2012

Acquarella Syntax Highlighter

Filed under: .NET, Acquarella, C Sharp, Open Source Projects — ajlopez @ 2:15 pm

Past weekend, I was coding a simple and configurable syntax highlighter, in C#, named Acquarella. You can see the result at:

https://github.com/ajlopez/Acquarella

The current solution has a class library project, a console program and a test project:

The idea is to have a library you can reference and use from your projects, in case you need some syntax highlighting functionality. The library takes a text (an string) and, giving the source code language and style name, transform it to another text, using configuration files. There is a more detailes information at project README.md.

Dog fooding, the Token.cs class transformed by Acquarella:

namespace Acquarella.Lexers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class Token
    {
        private string text;
        private int start;
        private int length;
        private TokenType type;

        public Token(TokenType type, string text, int start, int length)
        {
            this.type = type;
            this.text = text;
            this.start = start;
            this.length = length;
        }

        public string Value
        {
            get
            {
                return this.text.Substring(this.start, this.length);
            }
        }

        public TokenType Type { get { return this.type; } }

        public int Start { get { return this.start; } }

        public int Length { get { return this.length; } }
    }
}

Nice :-)

Pending work: Recognize comments, more styles (maybe using css files), more language configurations, extending Lexer (maybe RubyLexer, CSharpLexer, etc.)

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

February 29, 2012

AjBase (1) Implementing an In-Memory Database

Filed under: .NET, AjBase, C Sharp, Open Source Projects — ajlopez @ 8:29 pm

In mid 2009, I started to write an in-memory database, as a coding exercise in C#. These days, I resumed work on that project. Now the code resides in my GitHub repository:

https://github.com/ajlopez/AjBase

Nice history image at Github:

The current solution:

As usual, it was developed using Test-Driven Development. All tests in green:

The key implemented elements are:

Engine: It has a list of created databases (in memory, there is no persistence).

Database: It is the container for tables.

Table: A table has rows, and a RowDefinition.

RowDefinition: it manages the list of columns in a table.

Row: it keeps the values of the table columns, in an object array.

I have a doubt: to keep the schema (RowDefinition) per table, or go for a schema-less (free columns) per row. Now, I will keep the schema approach.

This year, I started to parse SQL statements. SQL is not my preferred languages (too many quirks, etc…), but the project can parse the simplest commands:

I want to add an ADO.NET provider, see the Data namespace:

I have a simple ADO.NET DbConnection, with some very basic (incomplete) ExecuteQuery, ExecuteNonQuery support.

Next steps: complete ADO.NET provider, more SQL parse support, concurrency and transaction support (big challenges! :-).

Next posts: examples for creating a database, creating a table, inserting data, selecting data, by code and by SQL statements. Meanwhile, you can explore the tests code, to see how to code those examples.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

February 25, 2012

AjRools (1) Rule Engine in C#

Filed under: .NET, AjRools, Open Source Projects, Rule Engine — ajlopez @ 6:50 pm

Since last year, I was conducting a bit of research about rule engines, specially in Java:

http://delicious.com/ajlopez/ruleengine

I reviewed JBoss Drools Expert (see http://delicious.com/ajlopez/drools). Past December, I assisted to Buenos Aires JBoss Meetup (see Spanish post)

In the old eighties, I met Rete Algorithm (see The Rete Matching Algorithm, Dr.Dobb’s). After all that, I decide to implement my own rule engine, in C#. You can check my progress at:

https://github.com/ajlopez/AjRools

This is the current solution:

As usual, it was coded using TDD.

I have facts, that are asserted, like Temperature = 38. And rules, that based on the asserted facts, produce other asserted facts (I plan to add actions, too, beyond fact assertions). A rule example:

# Rules example
rules
# Rule for Child Fever
rule
	when
		Temperature > 38
		Age <= 12
	then
		HasFever is true
end
# Rule for Adult Fever
rule
	when
		Temperature > 37
		Age > 12
	then
		HasFever is true
end
end

I have ideas to extend the rule engine to support objects with properties, not only variables:

rule
when
	p is_a Patient
	p.Temperature is 39
then
	p.HasFever is true
end

but this feature is still in progress. I didn't adopt the Rete algorithm, yet, or something similar. I want to have a running implementation, with tests. Then, changing internal algorithm is like an exercise on refactoring.

Pending work: more object+properties support, session (client use of the internal implementation), etc.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

February 19, 2012

Scala: Links, News and Resources (1)

Filed under: .NET, Functional Programming, Java, Links, Programming Languages, Scala — ajlopez @ 7:43 pm

Next Post

These are my first Scala programming language links.

http://en.wikipedia.org/wiki/Scala_%28programming_language%29

Scala (play /ˈskɑːlə/ skah-lə) is a multi-paradigm programming language designed to integrate features of object-oriented programming and functional programming.[3] The name Scala is aportmanteau of “scalable” and “language”, signifying that it is designed to grow with the demands of its users. James Strachan, the creator of Groovy, described Scala as a possible successor to Java.[4]

The design of Scala started in 2001 at the École Polytechnique Fédérale de Lausanne (EPFL) by Martin Odersky, following on from work on Funnel, a programming language combining ideas from functional programming and Petri nets.[5][not in citation given] Odersky had previously worked on Generic Java and javac, Sun’s Java compiler.[5]

Scala was released late 2003 / early 2004 on the Java platform, and on the .NET platform in June 2004.[3][5][6] A second version of the language, v2.0, was released in March 2006.[3]

On 17 January 2011 the Scala team won a 5 year research grant of over €2.3 million from the European Research Council.[7] On 12 May 2011, Odersky and collaborators launched Typesafe, a company to provide commercial support, training, and services for Scala. Typesafe received $3 million investment from Greylock Partners.[8][9][10][11]

Scala comes to .Net | The Scala Programming Language
http://www.scala-lang.org/node/10299

Scala In 5 Years – My Prediction « GridGain – High Performance Cloud Computing
http://gridgaintech.wordpress.com/2011/06/28/scala-in-5-years-my-prediction/

Why Java Folks Should Look Forward to Scala | Javalobby
http://java.dzone.com/articles/why-java-folks-should-look

Scala eXchange opening
http://www.slideshare.net/Odersky/scala-exchange-opening

Ruminations of a Programmer: Composing Heterogeneous DSLs in Scala
http://debasishg.blogspot.com/2011/06/composing-heterogeneous-dsls-in-scala.html

Scala Labs – Home
http://scala-labs.github.com/

Spark Cluster Computing Framework
http://www.spark-project.org/
Spark is an open source cluster computing system that aims to make data analytics fast — both fast to run and fast to write.

Along Came Betty » Clojure and Akka: A match made in …
http://blog.darevay.com/2011/06/clojure-and-akka-a-match-made-in/?utm_source=twitterfeed&utm_medium=twitter

Scala: The Static Language that Feels Dynamic
http://www.artima.com/weblogs/viewpost.jsp?thread=328540

Compiling Scala to LLVM
https://days2011.scala-lang.org/sites/days2011/files/ws3-2-scalallvm.pdf

Why Java folks should look forward to Scala | /var/log/mind
http://blog.dhananjaynene.com/2011/05/why-java-folks-should-look-forward-to-scala/

Functional Languages will Rule (but not this year) – Good Stuff
http://goodstuff.im/functional-languages-will-rule-but-not-this-y

Scala: A Better Java for Android
http://robots.thoughtbot.com/post/5836463058/scala-a-better-java-for-android

Ruminations of a Programmer: Combinators as the sublanguage of DSL syntax
http://debasishg.blogspot.com/2011/05/combinators-as-sublanguage-of-dsl.html

Typesafe
http://typesafe.com/
Typesafe makes it easy to build web-scale software based on the open source Scala programming language and Akka middleware. From multicore to cloud computing, it’s purpose built for scale.

The Pragmatic Bookshelf | Programming Concurrency on the JVM
http://pragprog.com/titles/vspcon/programming-concurrency-on-the-jvm

InfoQ: Actor Thinking
http://www.infoq.com/presentations/Actor-Thinking

Clojure or Scala for bioinformatics/biostatistics/medical research – Stack Overflow
http://stackoverflow.com/questions/5250459/clojure-or-scala-for-bioinformatics-biostatistics-medical-research

InfoQ: Guardian.co.uk Switching from Java to Scala
http://www.infoq.com/articles/guardian_scala

Asynchronous Event Sourcing using Actors
http://jonasboner.com/2009/02/12/event-sourcing-using-actors.html

Functional Scala: Expressions, Extensions and Extractors « brain driven development
http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/

iWork.com – JVM Languages
http://public.iwork.com/document/?d=JVM_Languages.key&a=p1045023190

Scala Team Wins ERC Grant | The Scala Programming Language
http://www.scala-lang.org/node/8579

Ruminations of a Programmer: Monads – Another way to abstract computations in Scala
http://debasishg.blogspot.com/2008/03/monads-another-way-to-abstract.html

Monads Are Not Metaphors – Code Commit
http://www.codecommit.com/blog/ruby/monads-are-not-metaphors

Algorithmically challenged: Sieve of Eratosthenes (the real one) Scala One-Liner
http://dcsobral.blogspot.com/2010/12/sieve-of-eratosthenes-real-one-scala.html

Code Monkeyism: Singletons without Singletons: Scala Type Classes
http://codemonkeyism.com/singletons-singletons-scala-type-classes/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+stephansblog+%28Code+Monkeyism+%7C+Stephans+Blog%29

Erik Engbrecht’s Blog: Higher-Level versus Higher-Order Abstraction
http://erikengbrecht.blogspot.com/2010/07/higher-level-versus-higher-order.html

Ruminations of a Programmer: Scala – To DI or not to DI
http://debasishg.blogspot.com/2008/02/scala-to-di-or-not-to-di.html

Real-World Scala: Introduction
http://jonasboner.com/2008/10/01/real-world-scala-introduction.html

Tom Morris’ wiki » Scala for Hackers
http://tommorris.org/wiki/Scala_for_Hackers

Scala Style Guide
http://davetron5000.github.com/scala-style/

Monads in Scala
http://lamp.epfl.ch/~emir/bqbase/2005/01/20/monad.html

Building Distributed Systems in Scala
http://www.slideshare.net/al3x/building-distributed-systems-in-scala

James Carr » Blog Archive » Learning Scala: Factorials and foldRight
http://blog.james-carr.org/2010/05/31/learning-scala-factorials-and-foldright/

Scala Beauty – Fun with Logic « Thinkmeta
http://thinkmeta.wordpress.com/2010/03/25/scala-beauty-fun-with-logic/

Beyond Mere Actors
http://docs.google.com/present/view?id=ddmk3f43_63zpg3jcgz&ncl=true

My Links
http://www.delicious.com/ajlopez/scala
http://www.delicious.com/ajlopez/scala+tutorial
http://www.delicious.com/ajlopez/scala+presentation
http://www.delicious.com/ajlopez/scala+video

More Scala links are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

February 13, 2012

Azure: Links, News and Resources (3)

Filed under: .NET, Azure, Cloud Computing, Links — ajlopez @ 1:54 pm

Previous Post

More links I collected during my work and research.

Cyan – Simpler than Azure
http://cyannet.codeplex.com/
Cyan is a .NET dynamic client for the Azure Table Storage REST API.

Azure Table Storage & Dynamic TableServiceEntity
http://stackoverflow.com/questions/7522235/azure-table-storage-dynamic-tableserviceentity

richorama / AzureSugar
https://github.com/richorama/AzureSugar
Syntactic sugar to make Azure development a little sweeter
Support is also available for using dynamic types (or dictionaries) to insert and query table storage.

Azure Table Storage with dynamic entities objects
http://ruiromanoblog.wordpress.com/2009/05/15/azure-table-storage-with-dynamic-entities-objects/

WindowsAzure / azure-sdk-for-node
https://github.com/WindowsAzure/azure-sdk-for-node/tree/dev/examples/myevents

Accessing Azure Role Environment information from NodeJS
http://nodeblog.cloudapp.net/accessing-azure-role-environment-information-from-node

Windows Azure Startup task to run npm install to avoid deploying node modules
http://nodeblog.cloudapp.net/startup-task-to-run-npm-in-azure

Leveraging Node.js’ libuv in Windows Azure
http://msdn.microsoft.com/en-us/library/hh527737(v=VS.103).aspx

Getting the samples to work on the Azure Node.js SDK
http://coderead.wordpress.com/2012/01/03/getting-the-samples-to-work-on-the-azure-node-js-sdk/

Microsoft will add Linux virtual machines to Windows Azure
http://arstechnica.com/business/news/2012/01/microsoft-will-add-linux-virtual-machines-to-windows-azure.ars

Create Hosted Service using Windows Azure Management API
http://debugmode.net/2012/01/02/create-hosted-service-using-windows-azure-management-api/

Microsoft Windows Azure PaaS Gets Node.js Update
http://www.talkincloud.com/microsoft-windows-azure-paas-gets-node-js-update/

How to deploy WordPress using the Windows Azure SDK for PHP WordPress scaffold
http://azurephp.interoperabilitybridges.com/articles/how-to-deploy-wordpress-using-the-windows-azure-sdk-for-php-wordpress-scaffold

Advertising Company Adopts Cloud Computing, Gets 400 Percent Improvement
http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?CaseStudyID=4000008145

Kobojo
Game Developer Meets Demand and Prepares for Success with Scalable Cloud Solution
http://www.microsoft.com/casestudies/Case_Study_Detail.aspx?CaseStudyID=4000008216

What is Windows Azure?
http://www.youtube.com/watch?feature=player_embedded&v=poDRw_Xi3Aw

Azure On GitHub
https://github.com/blog/1010-azure-on-github

Azure: Running Multiple Web Sites in a Single WebRole
http://blog.elastacloud.com/2011/01/11/azure-running-multiple-web-sites-in-a-single-webrole/

Deploying independent web applications to Windows Azure using single web role
http://weblogs.asp.net/gunnarpeipman/archive/2011/12/29/deploying-independent-web-applications-to-windows-azure-using-single-web-role.aspx

Modificar el tiempo de vida del token proporcionado por Windows Azure AppFabric Access Control
http://www.returngis.net/2011/12/modificar-el-tiempo-de-vida-del-token-proporcionado-por-windows-azure-appfabric-access-control/

Windows Azure Multi Application
http://azuremultiapp.codeplex.com/
Windows Azure Multi Application is a complete sample solution that allow deploy dinamically aplications to existing role instance.
After deploy admin tool new application can be deployed, without modify initial azure deployment. Each application can be deployed independently and can be of different types; ASP.NET WebForms, ASP.NET MVC, Windows Service, Console Application…

How to combine a Worker Role and an MVC4 Web Role into a single Azure instance
http://blog.liamcavanagh.com/2011/12/how-to-combine-a-worker-role-with-a-mvc4-web-role-into-a-single-instance/

Hadoop Streaming and F# MapReduce
http://blogs.msdn.com/b/carlnol/archive/2011/12/16/hadoop-streaming-and-f-mapreduce.aspx

Windows Azure Architecture Guide – Part 2 – Code Samples
http://www.microsoft.com/download/en/details.aspx?id=27878

Windows Azure + a pinch of UK
http://paper.li/ericnel/1314797915

Using Amazon and Azure Cloud Services in your Delphi XE2 and C++Builder XE2 Applications
http://www.youtube.com/watch?v=BRFbiRcLtkc&feature=player_embedded

What’s new in Windows Azure
http://www.infoworld.com/d/microsoft-windows/whats-new-in-windows-azure-181578

Microsoft Azure gets an open source rival
http://www.infoworld.com/d/open-source-software/microsoft-azure-gets-open-source-rival-181845

Introduction to the Hadoop on Azure Interactive JavaScript Console
http://www.youtube.com/watch?v=alPMYcomUEs

Node.JS in Windows Azure
http://channel9.msdn.com/Events/windowsazure/learn/Node-JS-in-Windows-Azure

Azure price cuts, bigger databases, now with node.js and MongoDB support, Hadoop on its way
http://arstechnica.com/microsoft/news/2011/12/azure-price-cuts-bigger-databases-now-with-nodejs-and-mongodb-support-hadoop-on-its-way.ars?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+arstechnica/index+(Ars+Technica+-+Featured+Content)

Improved Developer Experience, Interoperability, and Scalability on Windows Azure
http://blogs.msdn.com/b/windowsazure/archive/2011/12/12/improved-developer-experience-interoperability-and-scalability-on-windows-azure.aspx

Azure Node.js Developer Center
https://www.windowsazure.com/en-us/develop/nodejs/

Deploying Node.js Applications to Windows Azure via Blobs or Git Sync
http://blog.smarx.com/posts/deploying-node-js-applications-to-windows-azure-via-blobs-or-git-sync

Ten Basic Troubleshooting Tips for Windows Azure
http://www.davidaiken.com/2011/11/15/ten-basic-troubleshooting-tips-for-windows-azure/

Now Available! Updated Windows Azure SDK & Windows Azure HPC Scheduler SDK
http://blogs.msdn.com/b/windowsazure/archive/2011/11/14/updated-windows-azure-sdk-amp-windows-azure-hpc-scheduler-sdk.aspx

My Links
http://delicious.com/ajlopez/azure

January 7, 2012

Social Games Programming (Part 7) Game Moves Processing

Filed under: .NET, Azure, Game Development, JavaScript — ajlopez @ 5:24 pm

Previous Post
Next Post

In this post, I want to discuss the game play processing in Tic Tac Toe. It involves many pieces, from Razor view using Javascript to Web Role, to Azure Blob Storage.

These are the javascript files referenced in Tic Tac Toe view (at SocialGame.Web/Areas/Samples/Views/TicTacToe/Index.cshtml):

<script src="@Url.AreaContent("Scripts/jQuery.tmpl.js")" type="text/javascript"></script>
<script src="@Url.AreaContent("Scripts/knockout-1.2.1.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/game/ServerInterface.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/game/GameService.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/game/UserService.js")" type="text/javascript"></script>
<script src="@Url.AreaContent("Scripts/game/TicTacToeBoard.js")" type="text/javascript"></script>
<script src="@Url.AreaContent("Scripts/game/TicTacToeGame.js")" type="text/javascript"></script>
<script src="@Url.AreaContent("Scripts/game/TicTacToeViewModel.js")" type="text/javascript"></script>
<script src="@Url.AreaContent("Scripts/game/TicTacToeController.js")" type="text/javascript"></script>

As I wrote in the previous post, ServerInterface, GameService and UserService are game-agnostic components. They could be used in any game. For each new kind of game X, you must implement XBoard, XGame logic, XViewModel and an appropiate XController.

At the end of that view, there is the creation of the game-agnostic services:

var apiURL = "@this.ViewBag.ApiUrl";
var blobURL = "@this.ViewBag.BlobUrl";
var si = new ServerInterface();
var gs = new GameService(apiURL, blobURL, si);
var user = new UserService(apiURL, blobURL, si);

The @this.ViewBag properties are filled in the ASP.NET MVC controller (see BaseController.cs)

The creation of the game controller:

// check for canvas, show an "Upgrade your browser" screen if they don't have it.
var canvas = document.getElementById('board');
if (canvas.getContext == null || canvas.getContext('2d') == null) {
    $("#game").toggle();
    $("#notSupported").toggle();
    return;
}
var board = new TicTacToeBoard(canvas);
var game = new TicTacToeGame();
var controller = new TicTacToeController(viewModel, gs, board, game);
controller.setGameQueueId(gameQueueId);
controller.start();

But the interesting part is in the controller constructor:

function TicTacToeController(viewModel, gameService, board, game) {
    this.viewModel = viewModel;
    this.gameService = gameService;
    this.board = board;
    this.game = game;
    this.started = false;
    var controller = this;
    this.board.onMove = function (x, y) { controller.onMove(x, y); };
};

Notice the this.board.onMove: the controller register itself to process new moves detected by the board component. At its start method, the controller register itself to process game service updates:

controller.gameService.process(
        gameQueueId,
        function (queue) { controller.processGameQueue(queue); },
        function (action) { controller.processAction(action); }
        );

Let’s examine the processing of game moves.

1 – The board component detects a click, then it sends a new move to controller (using the onMove callbalk)

2 – The controller sends the new move to game logic, to update state (I omitted the view model in this sequence/graph)

3 – The controller sends the new move to game service.

4 – The game services sends a new command to web role, using the server interface

5 – The Web Role API receives the new command

6 – The command info is appended to the game status blob, at Azure storage

Now, the other client processing:

1 – The game service, using a timer, polls the game status, calling the service interface

2 – The service interface, using JSONP, retrieves the current game status from Azure Blob storage

3 – If a new move is detected, the game service calls a callback function provided by the controller (game service has no reference to controller).

4 – The controller sends the new move to game logic, updating state (I omitted the view state here)

5 – The controller sends the new move to board component, to update the canvas

A key point: the controller knows NOTHING about the service interface, WCF Web API, blob storage. So, you can change the game service to route and detect new moves in other ways. Next post: modify game service to use a Node.js server for game move processing.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

December 19, 2011

Social Games Programming (Part 6) Testing Game and Service with TDD and QUnit

Filed under: .NET, Azure, Game Development, QUnit, Test-Driven Development — ajlopez @ 8:44 am

Previous Post
Next Post

In my previous post, I presented the new version of Windows Azure Toolkit for Social Games. It has simple games to demonstrate the use of Javascript, HTML 5 canvas, game moves processing, Azure worker roles and web roles. Let’s explore in this post the making of client game logic, in Javascript, using TDD and QUnit.

There are online tests at:

http://watgames4.cloudapp.net/Test

Let’s run the Tic Tac Toe Game Logic tests:

http://watgames4.cloudapp.net/Samples/ClientTest/TicTacToeGameTest

This page is using QUnit for client Javascript unit testing. I wrote about that library at:

TDD with Javascript and QUnit

The above page is testing the Tic Tac Toe logic. Remember, each game is implemented in parts, the logic is one of them:

The client code resides in TicTacToeGame.js inside the SocialGames.Web project. Their first lines:

TTTColor = { Empty: 0, Cross: 1, Circle: 2 };
function TicTacToeGame() {
    this.board = [
     [TTTColor.Empty, TTTColor.Empty, TTTColor.Empty],
     [TTTColor.Empty, TTTColor.Empty, TTTColor.Empty],
     [TTTColor.Empty, TTTColor.Empty, TTTColor.Empty]
     ];
}
TicTacToeGame.prototype.move = function (x, y, color) {
    this.board[x][y] = color;
};
TicTacToeGame.prototype.isEmpty = function (x, y) {
    return this.board[x][y] == TTTColor.Empty;
};
....

The client test page (TicTacToeGameTest.cshtml) was built at the same time, using a TDD (Test-Driven Development) approach. Look at first tests:

test("Create Empty Board", function () {
    var game = new TicTacToeGame();
    for (var x = 0; x < 3; x++)
        for (var y = 0; y < 3; y++)
            ok(game.isEmpty(x, y));
    equal(game.isTie(), false);
    equal(game.hasWinner(), false);
});
test("Valid Moves on Empty Board", function () {
    var game = new TicTacToeGame();
    for (var x = 0; x < 3; x++)
        for (var y = 0; y < 3; y++) {
            ok(game.isValid(x, y, TTTColor.Cross));
            ok(game.isValid(x, y, TTTColor.Circle));
        }
});
test("No Winner in Empty Board", function () {
    var game = new TicTacToeGame();
    equal(game.getWinner(), TTTColor.Empty);
});
test("Get Winner in First Row", function () {
    var game = new TicTacToeGame();
    game.move(0, 0, TTTColor.Cross);
    game.move(1, 0, TTTColor.Cross);
    game.move(2, 0, TTTColor.Cross);
    equal(game.getWinner(), TTTColor.Cross);
    equal(game.isTie(), false);
    equal(game.hasWinner(), true);
});

The idea is to take baby steps, one test at a time, designing the game logic “API”, its expected behavior. In this way, you expend less time debugging in a dynamic language like Javascript, and you gain a test suite that can save your day in case of major refactoring. Look at the Four In A Row logic and client tests: you will find a similar approach.

Ok, not all can be easily tested, or build using TDD. Some of the game-agnostic services are using Ajax and Blob Storage, and to test them you must consider asynchronous Ajax calls. You can check:

http://watgames4.cloudapp.net/Test/ServerInterfaceTest

(You must be logged in using your Facebook or Windows Live ID, an example of use of Federated Security and Access Control Service (ACS))

This time, the system under test is the game-agnostic Server Interface:

There are some tricks in the test code (ServerInterfaceTest.cshmlt), an excerpt:

test("Call User/Verify", function () {
    var success = function (result) { ok(true); start(); };
    var error = ajaxGetError;
    stop(10000);
    expect(1);
    si.sendAjaxGet(apiURL + "user/verify", success);
});

expect is a QUnit function that prepare the framework to receive 1 ok(true) sometime during the test run. That confirmation is included in callback function success that it will be called after the successful processing of the asynchronous call .sendAjaxGet. Async life is not easy ;-)

More code analysis is coming. And some adapt to use Node.js as game server.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

« Newer PostsOlder Posts »

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 57 other followers