Skip to content

Instantly share code, notes, and snippets.

@regakakobigman
Created May 21, 2019 07:20
Show Gist options
  • Save regakakobigman/99e081af844964fd3f3812057667242a to your computer and use it in GitHub Desktop.
Save regakakobigman/99e081af844964fd3f3812057667242a to your computer and use it in GitHub Desktop.
Simple dice calculator in Godot
extends Node
var dice_regex = RegEx.new()
func _ready() -> void:
randomize()
dice_regex.compile("(?<dice>[0-9]*)?d(?<sides>[0-9]+)(?: ?(?<operator>\\+|-) ?(?<modifier>[0-9]*))?")
func rand_dice(dice: String) -> int:
"""
Takes dice notation in the form of d4, 2d6, d8 + 3, or 3d4-6
"""
# Original regex: (?<dice>[0-9]*)?d(?<sides>[0-9]+)(?: ?(?<operator>\+|-) ?(?<modifier>[0-9]*))?
var result = dice_regex.search(dice)
var results = {}
for key in result.names.keys():
results[key] = result.strings[result.names[key]]
if results[key] == '':
results.erase(key)
elif results[key] as int != 0:
results[key] = results[key] as int
var value := 0
var size: int = results.size()
var adding: bool = false
if results.has("operator"):
adding = results["operator"] == "+"
match size:
1: # dn
value = randi() % results["sides"] + 1
2: # ndn
for n in results["dice"]:
value += randi() % results["sides"] + 1
3: # dn +/- n
value = randi() % results["sides"] + 1
var n = results["modifier"]
value = (value + n) if adding else (value - n)
4: # ndn +/- n
for n in results["dice"]:
value += randi() % results["sides"] + 1
var n = results["modifier"]
value = (value + n) if adding else (value - n)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment