Creative Commons Licence This work is licensed under a Creative Commons
Attribution-ShareAlike 4.0 International License

Source: gitlab

Snake in Groovy

Andy Balaam
artificialworlds.net/blog

Contents

Snake

Groovy

Java-like

import java.util.Random  
Random rand = new Random()  
def moveApple() {
    this.applePos = [
        rand.nextInt( 15 ),
        rand.nextInt( 15 ),
    ]
}

Dynamic

def game = new Game( gridSize, rand );

class Game
{
    def gridSize
    // ...

Dynamic

def isApple( pos )
{
    return ( pos == applePos )
}

Dynamic

def t = new Thread(
    { println( "foo" ) } as Runnable )

# Or even:
def t = new Thread( { println( "foo" ) } )

Dynamic

def x = [
    'get': { return 'dummy' },
    'put': {}
] as IGetAndPut

Declarative

class MyStuff
{
    def something
    int anInt
}
def s = new MyStuff(
    something:"S", anInt:3 )

println( s.getAnInt() )

def s = [255, 0, 128] as java.awt.Color

Declarative

def swing = SwingBuilder.build()
{
    frame(
        id:'frame',
        title:'Snake in Groovy',
        defaultCloseOperation:WC.EXIT_ON_CLOSE,
    )
    {
        panel( new SnakePanel( gridSize ), id:'canvas' )
    }
}

Declarative

frame.keyPressed =
    { game.keyPressed( it.keyCode ) }

Declarative

def gridSize = [ 20, 20 ]
def m = [ 'a':0, 'b':2 ]

Closures

# Draw a dot for each bit of the snake
game.snakeBody.each {
    scaledGfx.dot( Colors.snake, it )
}

stringList.eachWithIndex()
    { obj, i -> println( i, obj ) };

// See also find, findAll, lots of others

Convenience

scaledGfx.write(
    "Score: ${game.snakeBody.size()}." )

Convenience

doOutside {
    // Something on a background thread
    doLater {
        // Async, on the event thread
    }
    edt {
        // On the event thread, and we wait
        // for it before we continue
    }
}

Convenience

Global scope

while( true )
{
    frame.repaint()
    sleep( 100 )
    game.step()
}

Global scope

class KeyCode {
    static int ESCAPE = 27
    static int SPACE  = 32
    static int RETURN = 10
}

Other features

More info

Videos youtube.com/user/ajbalaam
Twitter @andybalaam
Blog artificialworlds.net/blog
Projects artificialworlds.net