Complete DiceRoller Singleton Version

Created script: "DiceRoller.gd" to be the only dice script attached to a node and will act as a singleton. A single DieManager object is created in this script. The DieManager's values can be changed and methods can be called through the DiceRoller Script
This commit is contained in:
Andrew Tang 2022-07-11 01:16:34 +08:00
parent 3a402d4331
commit 59b74b946a
5 changed files with 162 additions and 111 deletions

View File

@ -0,0 +1,69 @@
#This script is for the overarching node that will contain the diemanager singleton
#It should be the only one of the die scripts that is attached onto a node.
extends Control
#desired dice types and needed percentage to pass are selected by game/user
#desiredDice takes an int array representing the # sides on the die/dice
#neededPercentageToPass takes a float that
export var desiredDice: Array
export var neededPercentageToPass: float
#Define dieManager variable
var dieManager
func _ready():
#create diemanager object
dieManager = DieManager.new(desiredDice, neededPercentageToPass)
#function gets the result of the roll(s) and shows it in the UI
func _on_Die_button_down():
#rollDice function returns an array with the following elements in the following positions:
#rollDice result: [[rolledValues], percentRolled, passResult, neededPercent, degreeOfSuccess, dice]
var result = dieManager.rollDice()
#assigning variable names to each of them for better clarity
var rolledValues = result[0]
var percentRolled = result[1]
var passResult = result[2]
var neededPercent = result[3]
var degreeOfSuccess = result[4]
var dice = result[5]
#Check if passed or not
if passResult:
$Outcome.text = "Successful Roll!"
else:
$Outcome.text = "Failed Roll!"
var diceResultText = "Rolled Values:\n"
#Prints the integer calues of each die rolled in the form: "D(num faces): (value rolled)"
for i in range(dice.size()):
diceResultText += ("D" + str(dice[i]) + ": " + str(rolledValues[i]) + "\n")
#changing labels on screen
$RolledValues.text = diceResultText
$PercentNeeded.text = "Percent Needed to Pass: " + str(neededPercent * 100) + "%"
$PercentRolled.text = "Percent Rolled: " + str(percentRolled * 100) + "%"
$DegreeOfSuccess.text = "Degree of Success: " + str(degreeOfSuccess * 100) + "%"
#revealing labels to user
$Outcome.show()
$RolledValues.show()
$PercentNeeded.show()
$PercentRolled.show()
$DegreeOfSuccess.show()
#Calls the cleardata method for the diemanager and hides the text on screen
func _on_Reset_button_down():
$Outcome.hide()
$PercentNeeded.hide()
$PercentRolled.hide()
$DegreeOfSuccess.hide()
$RolledValues.hide()
dieManager.clearData()
dieManager.setDieManager(desiredDice, neededPercentageToPass)

View File

@ -1,13 +1,13 @@
[gd_scene load_steps=3 format=2] [gd_scene load_steps=2 format=2]
[ext_resource path="res://DieManager.gd" type="Script" id=1] [ext_resource path="res://DiceRoller.gd" type="Script" id=1]
[ext_resource path="res://Die.gd" type="Script" id=2]
[node name="DieManager" type="Control"] [node name="DieManager" type="Control"]
anchor_right = 1.0 anchor_right = 1.0
anchor_bottom = 1.0 anchor_bottom = 1.0
script = ExtResource( 1 ) script = ExtResource( 1 )
desiredDice = [ 20, 7, 10 ] desiredDice = [ 10, 4, 6, 20 ]
neededPercentageToPass = 0.4
[node name="ColorRect" type="ColorRect" parent="."] [node name="ColorRect" type="ColorRect" parent="."]
anchor_right = 1.0 anchor_right = 1.0
@ -24,7 +24,6 @@ margin_top = 2.0
margin_right = 92.0 margin_right = 92.0
margin_bottom = 91.0 margin_bottom = 91.0
text = "Roll Die/Dice" text = "Roll Die/Dice"
script = ExtResource( 2 )
[node name="RolledValues" type="Label" parent="."] [node name="RolledValues" type="Label" parent="."]
visible = false visible = false
@ -95,4 +94,4 @@ margin_bottom = 469.0
text = "Reset" text = "Reset"
[connection signal="button_down" from="Die" to="." method="_on_Die_button_down"] [connection signal="button_down" from="Die" to="." method="_on_Die_button_down"]
[connection signal="pressed" from="Reset" to="." method="_on_Reset_pressed"] [connection signal="button_down" from="Reset" to="." method="_on_Reset_button_down"]

View File

@ -1,11 +1,11 @@
#Die class #Die class
extends Node2D
extends Button
class_name Die class_name Die
#value of selected die type #value of selected die type
var numFaces: int var numFaces: int
#Class constructor #Class constructor
func _init(value): func _init(value):
numFaces = value numFaces = value
@ -19,3 +19,6 @@ func rollDie():
return rolledNum return rolledNum
#Returns the number of faces on this die
func getNumFaces():
return numFaces

View File

@ -1,13 +1,17 @@
#This is the diemanager script that controls the rolling of the die/dice as well as calculates #This is the diemanager script that controls the rolling of the die/dice as well as calculates
#the end result #the end result
extends Control class_name DieManager
export var desiredDice = [20, 8] extends Node2D
#Array of the desired dice values to mod god wants
var desiredDice: Array
#User can select the percentage needed for a successful roll
var neededPercentageToPass: float
var validDieTypes = [4, 6, 8, 10, 12, 20] var validDieTypes = [4, 6, 8, 10, 12, 20]
#boolean for if a percentageroll is taking place #boolean for if a percentageroll is taking place
#we need a boolean for this because the way a percentage roll is calculated #we need a boolean for this because the way a percentage roll is calculated
#with two D10s is different than if one were using other dice #with two D10s is different than if one were using other dice
@ -16,143 +20,109 @@ var isPercentageRoll = false
#diceUsed holds the dice objects that are rolled #diceUsed holds the dice objects that are rolled
var diceUsed = [] var diceUsed = []
#diceInPlay holds the die objects as well.
#This and diceUsed are essentially the same arrays (holding the dice objects), but I had to use
#two arrays due to the parameters in returnDiePercentage
var diceInPlay = []
#rolledValues holds the integer value rolled from each die #rolledValues holds the integer value rolled from each die
var rolledValues = [] var rolledValues = []
#User can select the percentage needed for a successful roll
export var neededPercentageToPass = .2
#boolean based on whether the overall roll passed or not #boolean based on whether the overall roll passed or not
var passedRoll var passedRoll
#float holding the degree of success (rolledVal - neededPercentageToPass) #float holding the degree of success (rolledVal - neededPercentageToPass)
var degreeOfSuccess var degreeOfSuccess
#Constructor for diemanager class
func _init(dice, percent):
desiredDice = dice
neededPercentageToPass = percent
loadData()
#set values of diemanager
func setDieManager(dice, percent):
desiredDice = dice
neededPercentageToPass = percent
loadData()
#Load the diceInPlay array #Load the diceInPlay array
func _ready(): func loadData():
for elem in desiredDice: for elem in desiredDice:
if elem in validDieTypes: if elem in validDieTypes:
diceInPlay.append(Die.new(elem)) diceUsed.append(Die.new(elem))
#conditional to check if two D10s are being used #conditional to check if two D10s are being used
#if so, we know that a percentage roll is taking place #if so, we know that a percentage roll is taking place
if len(desiredDice) == 2 && desiredDice[0] == 10 && desiredDice[1] == 10: if len(desiredDice) == 2 && desiredDice[0] == 10 && desiredDice[1] == 10:
isPercentageRoll = true isPercentageRoll = true
#Resets the data in the script
func clearData():
isPercentageRoll = false
rolledValues = []
desiredDice = []
diceUsed = []
neededPercentageToPass = 0
#Returns the percent value of an individual die
#This is the function that returns the percentage of a rolled die (rolled val / total sides) #Stores the rolled value in rolledValues
#The UML showed that this function only had one parameter, "inputedDie," so I assumed that
#was the rolled integer value. However, in order to find the percetage we need the total sides as well
#As a result, I would get the total sides by ensuring that the inputedDie corresponds to the die at index 0
#of the diceInPlay array.
func returnDiePercentage(inputedDie): func returnDiePercentage(inputedDie):
#In case this method is being called on no dice
if len(diceUsed) == 0:
push_error("Cannot roll without any dice!")
var totalSides = diceInPlay[0].numFaces var rolledVal = inputedDie.rollDie()
#ensuring we don't lose the die objects in memory by storing them in another array #add rolled integer value to array
diceUsed.append(diceInPlay[0]) rolledValues.append(rolledVal)
diceInPlay.remove(0)
#Checks if a percentageroll is being done #Checks if a percentageroll is being done
if isPercentageRoll: if isPercentageRoll:
#This conditional is used to detemrine if the rolled value is #This conditional is used to detemrine if the rolled value is
#for the tens or ones digit #for the tens or ones digit
if (len(diceUsed) == 1): return float(rolledVal % 10)
return float(inputedDie % 10) / 10.0
else:
return float(inputedDie % 10) / 100.0
var result = float(inputedDie) / float(totalSides) return float(rolledVal) / float(inputedDie.numFaces)
return result
#Rolls all of the dice in diceUsed
#returns the average of all the percentages
func rollDice():
#In case this method is being called on no dice
if len(diceUsed) == 0:
push_error("Cannot roll without any dice!")
#Function to show all of the results on screen
func showOnUI(passResult, percentRolled) -> void:
if passResult:
$Outcome.text = "Successful Roll!"
else:
$Outcome.text = "Failed Roll!"
var diceResultText = "Rolled Values:\n"
#Prints the integer calues of each die rolled in the form: "D(num faces): (value rolled)"
for i in range(diceUsed.size()):
diceResultText += ("D" + str(diceUsed[i].numFaces) + ": " + str(rolledValues[i]) + "\n")
#NOTE: degree of success is always calculated regardlesss of success/failure. Let me know if this should be changed
degreeOfSuccess = percentRolled - neededPercentageToPass
#changing labels on screen
$RolledValues.text = diceResultText
$PercentNeeded.text = "Percent Needed to Pass: " + str(neededPercentageToPass * 100) + "%"
$PercentRolled.text = "Percent Rolled: " + str(percentRolled * 100) + "%"
$DegreeOfSuccess.text = "Degree of Success: " + str(degreeOfSuccess * 100) + "%"
#revealing labels to user
$Outcome.show()
$RolledValues.show()
$PercentNeeded.show()
$PercentRolled.show()
$DegreeOfSuccess.show()
#function for when "roll" button is clicked
func _on_Die_button_down():
#denominator will equal the total number of dice rolled #denominator will equal the total number of dice rolled
var denominator = 0 var denominator = 0
#sum of floats of all rolled die percentages #sum of floats of all rolled die percentages
var sumOfPercentages = 0 var sumOfPercentages = 0
#stores the rolled integer value of die in loop if isPercentageRoll:
var rolledVal sumOfPercentages += (returnDiePercentage(diceUsed[0]) / 10.0) + (returnDiePercentage(diceUsed[1]) / 100.0)
else:
for die in diceUsed:
sumOfPercentages += returnDiePercentage(die)
denominator += 1
#remember that the size of diceInPlay decrements by 1 each time returnDiePercentage is called var result = []
while diceInPlay.size() > 0:
rolledVal = diceInPlay[0].rollDie()
#add rolled integer vaslue to array result.append(rolledValues)
rolledValues.append(rolledVal)
#add percentage to sum
sumOfPercentages += returnDiePercentage(rolledVal)
#increment denominator
denominator += 1
var result
if isPercentageRoll: if isPercentageRoll:
#Percentage roll result remains the sum of the rolls #Percentage roll result remains the sum of the rolls
result = sumOfPercentages result.append(sumOfPercentages)
else: else:
#result is average of sum of percentages otherwise if denominator == 0:
result = sumOfPercentages / denominator result.append(0)
#result is average of sum of percentages otherwise rounded to 2 decimcal places
passedRoll = (result >= neededPercentageToPass) result.append(stepify((float(sumOfPercentages) / float(denominator)), 0.0001))
showOnUI(passedRoll, result) passedRoll = (result[1] >= neededPercentageToPass)
#NOTE: degree of success is always calculated regardlesss of success/failure. Let me know if this should be changed
degreeOfSuccess = result[1] - neededPercentageToPass
result.append(passedRoll)
result.append(neededPercentageToPass)
result.append(degreeOfSuccess)
result.append(desiredDice)
#rollDice result: [[rolledValues], percentRolled, passResult, neededPercent, degreeOfSuccess, dice]
return result return result
#Reset stored values and text
func _on_Reset_pressed():
$Outcome.hide()
$PercentNeeded.hide()
$PercentRolled.hide()
$DegreeOfSuccess.hide()
$RolledValues.hide()
#Fill diceInPlay again and empty diceUsed
for die in diceUsed:
diceInPlay.append(die)
diceUsed = []
rolledValues = []

View File

@ -9,13 +9,19 @@
config_version=4 config_version=4
_global_script_classes=[ { _global_script_classes=[ {
"base": "Button", "base": "Node2D",
"class": "Die", "class": "Die",
"language": "GDScript", "language": "GDScript",
"path": "res://Die.gd" "path": "res://Die.gd"
}, {
"base": "Node2D",
"class": "DieManager",
"language": "GDScript",
"path": "res://DieManager.gd"
} ] } ]
_global_script_class_icons={ _global_script_class_icons={
"Die": "" "Die": "",
"DieManager": ""
} }
[application] [application]
@ -24,6 +30,10 @@ config/name="GodotDiceRoller_Andrew"
run/main_scene="res://DiceRoller.tscn" run/main_scene="res://DiceRoller.tscn"
config/icon="res://icon.png" config/icon="res://icon.png"
[autoload]
DiceRoller="*res://DiceRoller.gd"
[physics] [physics]
common/enable_pause_aware_picking=true common/enable_pause_aware_picking=true