Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411517 Posts in 69377 Topics- by 58431 Members - Latest Member: Bohdan_Zoshchenko

April 27, 2024, 11:12:03 PM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsCommunityTownhallForum IssuesArchived subforums (read only)TutorialsScala for Games I: why is scala so awesome?
Pages: [1]
Print
Author Topic: Scala for Games I: why is scala so awesome?  (Read 7035 times)
Krux
Level 2
**



View Profile
« on: April 03, 2011, 05:31:41 PM »

First a few words about Scala. Scala is a young language designed for the Java Virtual Machine. I started to learn Scala less that a year ago, and my experience showed me that Scala is a much nicer and better language than Java. Scala does not only target the JVM, it also provides very good interaction to anything written in Java. This means you can use eg: LWJGL, JMonkey, Slick etc for game development.

some Scala features:
performance (as fast as Java)
object oriented (classes)
imperative programming (methods can change the state of an object)
functional programming (methods create a new object with the applied changed state)
lambda expression (functions as parameters, not function results)
closures ( cool stuff )
currying ( thats also very cool stuff  Durr...?)
typeinference ( wikipedia is your friend )
mixins (with traits, but much cooler that C# mixins)
inline xml (better for xml tranformations that XSLT  Big Laff)
implicit type conversions
and much more

many of these features you might already know, but I'll show you some features that I only know in scala, and might be interesting for game development.

Imagine you want to measure the time of an specific action. The most common way to do that would be to measue the time before the action, then after the action and calculate the difference. This could look like

Code:
[...]
val startTime = System.currentTimeMillis
// do something
val endTime = System.currentTimeMillis
val difference = endTime-startTime
[...]


Code:
[...]
def time(fun: => Unit) = {  //defining a funtion time, that takes one parameter that is
                         //a function itself with no arguments and no return (Unit = void)
    val startTime = System.currentTimeMillis
    fun //call the funtion
    val endTime = System.currentTimeMillis
    endTime-startTime  //the last line of a function is always the return value
}

val t = time{
    // do something
    // any codeblock can be passed as function
}
[...]
the second version of course lets you recycle the time function wherever you want to measure time. Try to do that with java  Shrug

similar constructs are also used for concurrent programming.
imagine you want to make an time expensive request to a server, but also want to keep responsive to the user. This is where futures are useful. A Future is a representation of an object that will only be available in the future
Code:
import scala.actors.Futures.future //in java this would be a static import, because future is a method
val a = future{
    //everything in this block is calculated on a different thread
    //so all here can be time consuming including blocking server communication or expensive calculations
    BigInt(3).pow(200000).toString //some useless expensive calculation result will later be in a
}

println("this line will be immediately called after the future has been created")
if(! a.isSet)
    println("a is not set")
println(a()) // a() blocks until a is set, thes it returns the content of a (a very long number)

another possible use of this construct might be to encapsulate the push and pop Matrix functions of openGL
Code:
def matrix(fun: => Unit){
    glPushMatrix
    fun
    glPopMatrix
}

matrix{
    translatef(1,2,3)
    matrix{
        rotatef(60,0,0,1)
        //draw something
    }

    matrix{
        rotatef(60,0,1,0)
        //draw something
    }
}

with this construct you never forget about any popMatrix

another nice feature of this language is pattern matching:
Code:
val l = List(1,2,3) //l is initialized with a new List
val List(a,b,c) = l //a b and are initialized with the content of l (a=1,b=2,c=3)
very nice about this, is that it works also swith case constructs. In Scala they are match case constructs.

Code:
val a:Any = [...]  //initialize a with anything
// now we can match the content of a
a match{
    case 1 =>
        println("one")
    case 3 =>
        println("three") //this is like switch case in C, Java or C#, except you do not need break
    case x:Double => // this time the pattern is matched to the datatype of a
        println("a is a double")
    case x:Int if(x%2 == 1) =>
        println("a is an odd integer")
    case List(1,2,3) => //a is matched to a List with exact content
        pritnln("123")
    case List(1,x,3) => //first and third content must be 1 and 3, the content in the middle can be used as x
        println("this middle is "+x)
    case 1 :: xs => //if a is a list and the first element of the list is 1, then xs is the list without the first element: List(1,2,3) becomes List(2,3)
        println(xs)
    case _ => //wildcard, will match anything
        println("a does not match anything")
}

So thats all about build in features. Now lets head to the more awsome parts of Scala. Some of the already mentioned features and many not mentioned features are very useful to develop domain specific languages (DSLs) inside of scala without sacrificing the power of the language itself. Normally a DSL is an extern script that is compiled or parsed and then linked to the program. A very popular example for this is the GLSL the openGL shading language. GLSL has build in support for many types of vectors and many functions to work with them. So then if you work with those DSLs you either work in the DSL where no classes exist to structure the program, or you work in you main programming language with no build in Vector support (normally vectors implemented with classes are not so cool as GLSL vectors). But thanks to the awseome features of Scala somebody creaded a vector math library that is very close to original GLSL. The developer also announced that he wants to develop his own compiler plugin, so that his DSL will be compiled into code that runs faster as any Java implementation of vectors.

if you are interested in learing more about Scala and making games with it, please post a comment. If you do not understand anything at all, please leave a comment, too. My tutorial will include how to use the not-so-simple, but powerful Simple Build Tool, and of the Scala way of programming Games.

for the first impression about scala, Simply Scala might be your choise
« Last Edit: April 05, 2011, 02:43:31 PM by Krux » Logged
Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic