shoGambler/plugins-src/diceroll/main.go

87 lines
2.2 KiB
Go
Raw Normal View History

2024-10-20 17:12:11 +01:00
package main
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"shoGambler/lib"
"github.com/gin-gonic/gin"
)
func Metadata() (lib.PluginData, error) {
return lib.PluginData{
Name: "dice-roll",
// It does return points
CanReturnPoints: true,
// It does not add points outside out /api/dice-roll
CanAddPoints: false,
// It does not need an arbitrary API, it's fine within the constraints of the plugin API
HasExtraAPI: false,
// It does not need an arbitrary API, so this is nil
ExtraAPICode: nil,
// It recommends 10 points to be spent
RecommendedPoints: big.NewInt(10),
// You can input arbitrary point amounts
CanAcceptArbitraryPointAmount: true,
// Very simple HTML
PluginHTML: `
<h1>Dice Roll</h1>
<p>Roll a dice</p>
<button id="roll">Roll</button>
`,
// Very simple script
PluginScript: `
document.getElementById("roll").addEventListener("click", async () => {
let points = BigInt(0);
try {
points = BigInt(prompt("How many points do you want to spend?"));
} catch (e) {
alert("Invalid number");
return;
}
sendCost(points);
})
</script>
`,
// The API code is the function ApiCode
ApiCode: ApiCode,
// If the plugin html says the plugin has returned data rather than points, it's an error
OnDataReturn: "alert('Error: this plugin should be returning points'); throw new Error('Error: this plugin should be returning points')",
}, nil
}
func ApiCode(_ *gin.Context, input lib.ApiInput) (*big.Int, error) {
// Roll a die
diceRoll, err := rand.Int(rand.Reader, big.NewInt(6))
if err != nil {
return nil, err
}
// 1, 2 and 3 - lose all points
// 4 and 5 - keep points
// 6 - win 125% points
if input.InputPoints != nil {
switch diceRoll.Uint64() + 1 {
case 1, 2, 3:
// Lose all points
return big.NewInt(0), nil
case 4, 5:
// Keep points
return input.InputPoints, nil
case 6:
// Win 125% points
result, _ := new(big.Float).Mul(new(big.Float).SetInt(input.InputPoints), big.NewFloat(1.25)).Int(nil)
return result, nil
}
return nil, errors.New("dice roll out of range: " + diceRoll.String())
} else {
fmt.Println(input.InputPoints)
return nil, errors.New("input points is nil")
}
}