Search code examples
javascriptbuttonhexbbc-microbit

Lets say I have two buttons button A and button B I need it so that if I press B it will cycle through different values and pressing A will print them


On my BBC micro:bit V1 the original I am trying to make a virtual DND dice set but I only have two buttons to work with. So I am trying to make it so that if I press one button I am able to go from D4 to D6 to D8 Ect. and if I press another button It displays the number from the D4 or D6. unfortunately I cant find anyone else who has come across this problem or a way to fix it.

I have tried using arrays but I am nearly positive they can't be used in correlation to Randit.

input.onButtonPressed(Button.A, function () {
    D20 = randint(1, 20)
    basic.showString("D20 = " + D20)
})
input.onButtonPressed(Button.B, function () {
    
})
let D20 = 0
let swapOut = [randint(0, 10), randint(0, 20)]
basic.pause(2000)
basic.showString("Press A to roll D20")
if (input.buttonIsPressed(Button.B) <= 1) {
    basic.showString("" + (swapOut[0]))
}
if (input.buttonIsPressed(Button.B) <= 1) {
    basic.showString("" + (swapOut[1]))
}

As far as I can tell I cant use arrays to detect how many times something can be pressed. and then move that information between inputs.


Solution

  • A possible way of doing this is to have button A increment an index that refers to a list of possible dice types. And then button B would generate the dice roll using the index value to find which range of numbers (dice type) it should be using.

    An example of implementing this would be:

    input.onButtonPressed(Button.A, function () {
        ActiveDice += 1
        if (ActiveDice > DTypes.length) {
            ActiveDice = 0
        }
        basic.showString("D" + convertToText(DTypes[ActiveDice]))
    })
    input.onButtonPressed(Button.B, function () {
        basic.showNumber(randint(1, DTypes[ActiveDice]))
    })
    let DTypes: number[] = []
    let ActiveDice = 0
    ActiveDice = 0
    DTypes = [
    20,
    12,
    10,
    8,
    6,
    4
    ]
    

    Or in the blocks editor: micro:bit blocks code

    You do have other inputs on the micro:bit V1. For example, you have the "on shake". So button A could go one way through the list. Button B could go the other way through the list. And "shake" could roll the dice.