Implementing Websocket Game Server with Scala and Akka Streams [Part 4/4]

This is the last part where I code a client.

Thanks to everyone who watched the series! I know at times it was a bit hard to follow. I’ve made a mistake of coding and trying talk at the same time. It turns out it is a really hard and you cannot fully focus on both. Next time I’m going to do one thing at the time and then merge it in post-production.

Code: https://github.com/JakubDziworski/Akka-Streams-Websocket-Game-Server

Other parts: Implementing Websocket Game Server with Scala and Akka Streams

Implementing Websocket Game Server with Scala and Akka Streams [Part 3/4]

Last part of server side implementation. The remaining piece of the puzzle is client side which is next part’s subject.

Code: https://github.com/JakubDziworski/Akka-Streams-Websocket-Game-Server

Other parts: Implementing Websocket Game Server with Scala and Akka Streams

Implementing Websocket Game Server with Scala and Akka Streams [Part 2/4]

Second part of server side implementation.

Code: https://github.com/JakubDziworski/Akka-Streams-Websocket-Game-Server

Other parts: Implementing Websocket Game Server with Scala and Akka Streams

Implementing Websocket Game Server with Scala and Akka Streams [Part 1/4]

First part of server side implementation

Code: https://github.com/JakubDziworski/Akka-Streams-Websocket-Game-Server

Other parts: Implementing Websocket Game Server with Scala and Akka Streams

Github Code Search - Programmers' Goldmine

Learning new language or framework can sometimes be a struggle. Traditional approach is to read documentation which explains the concepts, and provides simple examples. Sometimes that might be enough, but what those documentations are often lacking are some advanced examples and usages in real projects.

Coming across a problem which is not described in documentation, most people look for solution on stackoverflow (or dig through sources). However the framework you are using might not be in the game for long enough to fill stackoverflow with every question you come up with.

Have you ever been stuck with a problem and thought to yourself:

“I know someone must have solved this before! Why there is no stackoverflow answer to this problem?”

You are right - someone has probably already solved it. And it’s very likely the solution has been pushed to github. It’s just a matter of finding it. Programmers are more likely to solve the issues themselves rather than ask random people on the internet about it.

Github search code

Github search provides a way to query repos in a various ways. One of them is searching code. This is extremly powerful feature. Every line ever written by anybody can be found with simple queries. The “good” thing about github is that the private repos are not free, so there are many projects implicitly shared to public by people who just want to backup their code. This is a goldmine of information!

Examples

Below are some of the examples which I find github search code is handy for.

Learning new api

Have you ever been stuck with 3rd party api, and unable to find similar code snippets for your case?

I was recently in need to use akka streams to read a huge file and pass the results to another file instantly. The documentation regarding this topic is good but short and could provide more examples.

Github advanced search to the rescue. After few clicks I found an awesome piece of code that streams the csv file modifies it and dumps to another file!

filepaths_example

Finding projects using technologies you are interested in

Let’s say you want to learn Spring MVC, Hibernate and testing with Spock. You could go to the docs of each libraries, and learn them one by one… or just find a project which integrates all of them.

Most platforms have some kind of dependency management tools. In case of Java that is usually Maven which stores all dependencies information in pom.xml file.

You can therefore query keywords and filename to find the projects you are interested in:

spring hibernate spock filename:pom.xml

This method is also great if you are looking for projects to contribute to.

find_technology

Integrating with external services

Looking for a quick way to integrate with github api using your favourite language? No problem - just look for the repos with the api url and filter by language:

api.github.com language:scala

find_integrations

Configuration

It also wouldn’t hurt to take a look at configuration files of real big projects. This might be extremly helpful, particularly in case of immature frameworks.

Let’s take a look how to configure akka cluster. Such configuration should contain ClusterActorRefProvider keyword and reside in file with .conf extension (usually application.conf):

ClusterActorRefProvider extension:conf

find_configuration

Conclusion

Github search is underrated yet extremly powerful tool for learning new apis,solving issues and finding repos you might be interested in. This is a great way to quickly get started with new framework - finding code snippets that are similar to what you want to achieve has never been easier. It also makes you feel less alone with the issues you encounter - it’s very likely some has already solved them. Likewise, discovering interesting projects with this search engine is just a matter of minutes.

JShell - Java 9 interpreter (REPL) - Getting Started and Examples

Many compiled languages include tools (sometimes called REPL) for statements interpretation. Using these tools you can test code snippets rapidly without creating project.

Take Scala as an example. Compilation can sometimes take a long time, but using repl each statement is executed instantly! That’s great when you are getting started with the language. Each expression gives you returned value and it’s type - that’s very valuable information.

In java, instead, we have to create a test or main method which prints results and needs to be recompiled every time you make a change.

When?

JShell will be introduced in Java 9 realease. You can however get early access build on https://jdk9.java.net/.

Running

Once you downloaded jdk9 there is a jshell executable in a bin directory. I suggest running it in verbose (-v) mode for the first time:

kuba@kuba-laptop:~/repos$ jdk-9/bin/jshell -v
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro


jshell> 

You can go back to non verbose mode using /set feedback normal.

Default imports

By default you get a set of common imports:

jshell> /imports
|    import java.util.*
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.util.concurrent.*
|    import java.util.prefs.*
|    import java.util.regex.*

You can add your own any time.

Expressions

You can type any valid java expression, and it will tell you the returned value, it’s type and assign it to a variable:

jshell> 3+3
$1 ==> 6
|  created scratch variable $9 : int

jshell> $1
$1 ==> 6
|  value of $1 : int

Variables

It is possible to declare variables and name them. Once you do that they become visible in the scope.

jshell> int x=5
x ==> 5
|  created variable x : int

jshell> x
x ==> 5
|  value of x : int

Methods

You can also define methods and even replace them:

jshell> void helloJShell() { System.out.println("hello JShell"); }
|  created method helloJShell()

jshell> helloJShell();
hello JShell

jshell> void helloJShell() { System.out.println("wow, I replaced a  method"); }
|  modified method helloJShell()
|    update overwrote method helloJShell()

jshell> helloJShell()
wow, I replaced a  method

Commands

Aparat from language syntax you can execute jshell commands. Some of the most useful ones (/help to list all of them) are:

listing variables

jshell> /vars
|    int x = 0
|    double j = 0.5

listing methods:

jshell> /methods
|    printf (String,Object...)void
|    helloJShell ()void

The printf method is defined by default.

listing sources

jshell> /list
  14 : helloJShell();
  15 : void helloJShell() { System.out.println("wow, I replaced a  method"); }
  16 : helloJShell()

editing sources in external editor

jshell> /edit helloJShell

Opens external editor, and replaces helloJShell method.

Example use cases

After 20 years of Java without REPL one might wonder what scenarios are suitable for JShell. Here are some examples.

Veryfing return type

Remember the time you learned that dividing two integers in Java does not result in floating number? For some time I was convinced that both numerator and denominator have to be floating for a result to be floating too. Let’s test that:

jshell> 1/2
$1 ==> 0
|  created scratch variable $1 : int

jshell> 1.0/2
$2 ==> 0.5
|  created scratch variable $2 : double

jshell> 1/2.0
$3 ==> 0.5
|  created scratch variable $3 : double

jshell> 1.0f/2
$4 ==> 0.5
|  created scratch variable $4 : float

jshell> 1/2.0f
$5 ==> 0.5
|  created scratch variable $5 : float

Turns out only one of them has to be floating.

Testing Java niuanses

Did you know that comparing autoboxed integers references which values are from range -128 to 127 (inclusive) returns true (they are cached)? You can verify that with shell in a matter of seconds:

jshell> Integer i1 = 127
i1 ==> 127

jshell> Integer i2 = 127
i2 ==> 127

jshell> i1 == i2
$35 ==> true

jshell> Integer i2 = 128
i2 ==> 128

jshell> Integer i1 = 128
i1 ==> 128

jshell> i1 == i2
$38 ==> false

Formatting

Sometimes the logs need to be verbose and properly formatted. This is tedious task and usually leads to few recompile cycles which significantly slows us down. Imagine you forgot what was the format sign responsible for integers. You can quickly verify that:

Let’s try %i (integer):

jshell> printf("I got %i apple",1)
|  java.util.UnknownFormatConversionException thrown: Conversion = 'i'
|        at Formatter$FormatSpecifier.conversion (Formatter.java:2691)
|        at Formatter$FormatSpecifier.<init> (Formatter.java:2717)
|        at Formatter.parse (Formatter.java:2565)
|        at Formatter.format (Formatter.java:2507)
|        at PrintStream.format (PrintStream.java:977)
|        at PrintStream.printf (PrintStream.java:873)
|        at printf (#s8:1)
|        at (#51:1)

Oops, maybe %d (decimal) :

jshell> printf("I got %d apple",1)
I got 1 apple

Conclusion

JShell is a very useful tool for prototyping and testing Java code snippets. Even though it is not yet officially released I highly recommend checking it out. There is also a JShell Java api which allows you to evaluate JShell from java. Once the java 9 is out I bet there will be JShell integrations in most popualar IDEs - this will make using it even more handy.

Solid in practice - Liskov Substitution Principle

3rd video of the series. This time it’s all about Liskov substitution.

Solid in practice - Open Closed Principle

This is the second episode of the series. The screencast contains explanation of open closed principle.
It also gives an practical example of a class violating this principle and how to fix it.

Solid in practice - Single Responsibility Principle

The screencast contains explanation of single responsible principle.
It also gives an practical example of a class violating this principle and how to fix it.

Creating JVM language [PART 20] - Writing real application with Enkel

Sources

The project can be cloned from github repository.
The revision described in this post is 5afeaa64a7fb22fad7fe2c30ee440d9a3ff25337.

Playing cards drawing simulator

In the previous 19 posts I’ve been describing the process of creating my very first programming language. All that hard work I’ve put into it would seem pointless if I’d never used it for anything useful, right?

I came up with an idea of playing cards drawing simulator. The idea is to provide number of players and number of cards per player. As an output you get randomized collection of cards for each player. Just like in real games the cards are being removed from the stack when drawing.

Card class

Card {

    string color
    string pattern

    Card(string cardColor,string cardPattern) {
        color = cardColor
        pattern = cardPattern
    }

    string getColor() {
        color
    }

    string getPattern() {
        pattern
    }

    string toString() {
        return "{" + color + "," + pattern + "}"
    }
}

There is nothing fancy here. Just simple domain object. It is immutable representation of a playing card.

CardDrawer class

CardDrawer {
    start {
        var cards = new List() //creates java.util.ArrayList 
        addNumberedCards(cards) //calling method with 3 arguments (last 2 are default)
        addCardWithAllColors("Ace",cards) 
        addCardWithAllColors("Queen",cards)
        addCardWithAllColors("King",cards)
        addCardWithAllColors("Jack",cards)
        //Calling with named arguments (and in differnet order)
        //The last parameter (cardsPerPlayer) is ommited (it's default value is 5)
        drawCardsForPlayers(playersAmount -> 5,cardsList -> cards) 
    }

    addNumberedCards(List cardsList,int first=2, int last=10) {
        for i from first to last {  //loop from first to last (inclusive)
            var numberString = new java.lang.Integer(i).toString()
            addCardWithAllColors(numberString,cardsList)
        }
    }

    addCardWithAllColors(string pattern,List cardsList) {
        cardsList.add(new Card("Clubs",pattern))
        cardsList.add(new Card("Diamonds",pattern))
        cardsList.add(new Card("Hearts",pattern))
        cardsList.add(new Card("Spades",pattern))
    }

    drawCardsForPlayers(List cardsList,int playersAmount = 3,int cardsPerPlayer = 5) {
        if(cardsList.size() < (playersAmount * cardsPerPlayer)) {
            print "ERROR - Not enough cards" //No exceptions yet :)
            return
        }
        var random = new java.util.Random()
        for i from 1 to playersAmount {
            var playernumberString = new java.lang.Integer(i).toString()
            print "player " + playernumberString  + " is drawing:"
            for j from 1 to cardsPerPlayer {
                var dawnCardIndex = random.nextInt(cardsList.size() - 1)
                var drawedCard = cardsList.remove(dawnCardIndex)
                print "    drawed:" + drawedCard
            }
        }
    }
} 

Running

First we need to compile Card class (no multiple files compilation implemented yet). Once the Card is compiled CardDrawer is able to find it on classpath (providing we added current dir to classpath)

java -classpath compiler/target/compiler-1.0-SNAPSHOT-jar-with-dependencies.jar: com.kubadziworski.compiler.Compiler EnkelExamples/RealApp/Card.enk
java -classpath compiler/target/compiler-1.0-SNAPSHOT-jar-with-dependencies.jar:. com.kubadziworski.compiler.Compiler EnkelExamples/RealApp/CardDrawer.enk

kuba@kuba-laptop:~/repos/Enkel-JVM-language$ java CardDrawer 
player 1 is drawing:
    drawed:{Diamonds,Queen}
    drawed:{Spades,7}
    drawed:{Hearts,Jack}
    drawed:{Spades,4}
    drawed:{Hearts,2}
player 2 is drawing:
    drawed:{Diamonds,4}
    drawed:{Hearts,Ace}
    drawed:{Diamonds,Jack}
    drawed:{Spades,Queen}
    drawed:{Spades,King}
player 3 is drawing:
    drawed:{Diamonds,Ace}
    drawed:{Clubs,2}
    drawed:{Clubs,3}
    drawed:{Spades,8}
    drawed:{Clubs,7}
player 4 is drawing:
    drawed:{Spades,Ace}
    drawed:{Diamonds,3}
    drawed:{Clubs,4}
    drawed:{Clubs,6}
    drawed:{Diamonds,2}
player 5 is drawing:
    drawed:{Hearts,4}
    drawed:{Hearts,Queen}
    drawed:{Hearts,10}
    drawed:{Clubs,Jack}
    drawed:{Diamonds,8}

Great! This proofs that Enkel,though in early stage, can already be used for creating some real applications.

Goodbye Enkel

I had a really great time creating Enkel and sharing the whole process here. Writing code is one thing, but describing it in a way, that other people could understand it is another challenge itself.

I learned a lot during the process, and hope some other people benefited (or will benefit) from the series too.

Unfortunately this is the last post of the series. The project will however be continued, so keep track of it!