samedi 4 décembre 2021

How can I get my python game results into the html output div?

I'm using Pyodide for this, and need to get my div to recognize the game results in real time or as the game progresses. I think I'm just missing something in my try-catch but I don't think I need to redefine the const. I've tried to make output a global variable, but that doesn't work either. Does anyone have any insight here?

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdn.jsdelivr.net/pyodide/v0.18.1/full/pyodide.js"></script>
    <meta charset="UTF-8">
</head>
<body>

<p>
      Enter Rock, Paper, or Scissors.
    </p>

    <button onclick="evaluatePython()">Play!</button>
    <br />
    <br />
    <div>Output:</div>
    <textarea id="output" style="width: 100%;" rows="10" disabled></textarea>

    <script>
      const output = document.getElementById("output");

      function addToOutput(s) {
        output.value += ">>>" + "\n" + s + "\n";
      }

      output.value = "Initializing...\n";
      // init Pyodide
      async function main() {
        let pyodide = await loadPyodide({
          indexURL: "https://cdn.jsdelivr.net/pyodide/v0.18.1/full/",
        });

        output.value += "Ready!\n";
        return pyodide;
      }
      let pyodideReadyPromise = main();

      async function evaluatePython() {
       let pyodide = await pyodideReadyPromise;

       try{
         let output = await pyodide.runPython(`from random import randint

t = ["Rock", "Paper", "Scissors"]

computer = t[randint(0,2)]

player = False

while player == False:
    player = input("Rock, Paper, Scissors?")
    if player == computer:
          print("Tie!")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!, computer, covers, player")
        else:
            print("You win!", player, "smashes", computer)
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
        else:
            print("You win!", player, "covers", computer)
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
        else:
            print("You win!", player, "cut", computer)
    else:
        print("That's not a valid play. Check your spelling!")
    player = False
    computer = t[randint(0,2)]`);

                  addToOutPut(output);
                  } catch (err) {
                    addToOutput(err);
                }
              }
    </script>
</body>
</html>

Thanks for taking a look!

Aucun commentaire:

Enregistrer un commentaire