That's a good idea!
Something like the tutorial from Banjo, but with bigger functions. (Functions are named closures in groovy, right?)
I wanted to do something like this, because I see lot's of unreadable code. My (personal, hehe
) teacher for informatics always say: Write readable code! (Or you get spanked!
)
Let me start with rolling a dice:
Code:
// Dice Roll Example
// by MissEshock2002
// This script, from https://ss.deviatenow.com, is protected by this licence:
// CC0
setInfos(9, "Dice Roll Example", "Dice Roll Example for 1 or more Dice",
"MissEshock2002",
"v1.0", 0x222222, "en", ["example", "tutorial"]);
def getDiceRoll = { numberOfDice = 1 -> // default 1 dice, if no value given
// returns the sum of numberOfDice rolled dice
int rollSum = 0 // sum of all rolled dice
// loop: repeats numberOfDice times
(1..numberOfDice).each {
// getRandom(6): random between 0 and 5; +1 to get 1 to 6
// roll += ... sums up all rolls
rollSum += getRandom(6) + 1
}
return rollSum
}
int numberOfDice = 1
boolean endLoop = false
while (!endLoop) { // loop repeats till endLoop = true
// while loop to make sure input is positive number
// repeat, if input is wrong
while (true) {
numberOfDice = getInteger("How many dice to roll?", numberOfDice)
if (numberOfDice > 0) break // if input is correct: end while loop with break
}
int roll = getDiceRoll(numberOfDice)
// same as if ... else ...: (condition) ? "condition is true" : "condition is false"
String diceWord = (numberOfDice == 1) ? "Die" : "Dice"
// show results:
show("You rolled " + roll + " with " + numberOfDice + " " + diceWord + ".")
// show(String.format("You rolled %s with %s %s.", roll, numberOfDice, diceWord)) // the same with formatted string
showButton("->")
if (!getBoolean("Repeat?")) endLoop = true
}
show("- End of Script -")