-1

I am trying to run a python program in html but I am getting an error.

First it says

Then if I type anything it appears with this error

This was the Html code

<html>
    <head>
        <title>
            Anthony's Python Video Game
        </title>
        <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    </head>
    <body> 
            <py-script src = "VideoGame.py">
            </py-script>
            
    </body>
</html>

And in the terminal I wrote

python -m http.server port 5050

The python code is


print('This is my very first video game, this is a choose your own adventure game.')
print('The objective of this game is to get to the end of the longstreet road without dying.')
print('There will be decisions on the path that will be quite litteraly life or death, please choose coutiosly to survive.')
print('click i to check inventory or q to quit at any time')



#START

begin = input('Would you like to begin ')

def NO():
    print ('Please follow the rules or there will be consequences ://///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////')
    quit()

def STOP():
    print ("If you see anything out of the ordinary please do not stop and continue on the pathway ://///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////")
    quit()

def WENT_BACK_2():
    print('You instantly hear a loud bang and feel a pain in your forehead right before you feel everything go empty and drop to the ground dead.')
    print('...')
    NO()

def WENT_BACK_1():
    print ('You start back home, and relize that it feels like you have been walkning for a while, you look down at your watch and relize it has been 30 minutes and you feel like you are getting nowhere, you start to sprint back and you black out.')
    print ('...')
    print ('You wake up with a tattoo on your right arm, it reads. "Cannot go this way please dont'+ "'t" + ' disobey again, thank you ://///////////////////"')
    choose_to_go_back = 1

def inventory():
    if coins >=1:
        print ('You have', str(coins), 'coins')
    elif torch >=1:
        print ('You have', str(torch), 'torch')
    elif knife >=1:
        print ('You have', str(knife), 'knife')
    else:
        print('You have nothing in your inventory')

choose_to_go_back = 0
coins = 0
torch = 0
knife = 0
''''

elif line == 'q'.lower():
    quit()
elif line == 'i'.lower():
    inventory()
    continue
    
'''

''''

elif f == 'b'.lower() and choose_to_go_back == 0:
    WENT_BACK_1
    break
elif f == 'b'.lower() and choose_to_go_back == 1:
    WENT_BACK_2

'''


if begin == ('yes').lower() or begin == ('y').lower():
#SIGN
    while True:
        sign = input('You run into a sign that read rules before starting your quest, would you like to read ')
        line = (sign)
        if sign == 'yes'.lower() or sign == 'y'.lower():
            print('Hello, the fist rule is to read the rules ,if you disobey any of these rules there will be consequences, you are about to start down a journey with not many designated stops, please do not attempt to go backwards,')
            print('if you see anything out of the ordinary please do not stop and continue on the pathway, and DO NOT go into the woods, start on this journey on you own risk. We are not liable to any damages done to you or to your body. Thank you and good luck.')
            break
        elif line == 'q'.lower():
            quit()
        elif line == 'i'.lower():
            inventory()
            continue
        else:
            print('First rule states, "the fist rule is to read the rules ,if you disobey any of these rules there will be consequences"')
            print('://///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////')
            quit()
#
#
    
    print ('...')
    print ('You walk onto the street and everyting feels fine')

#FIRST DESISION TO GO BACK 
    while True:
        walk = input ('Would you like to continue(c) or walk back to your house(b) ')
        line = (walk)
        if walk == ('c').lower():
            break
        elif line == 'q'.lower():
            quit()
        elif line == 'i'.lower():
            inventory()
            continue
        elif walk == ('b').lower():
            WENT_BACK_1()
            while True:
                a = input('Try runing back again (b) or continue (c) ')
                line = (a)
                if a == ('b').lower():
                    WENT_BACK_2()
                elif line == 'q'.lower():
                    quit()
                elif line == 'i'.lower():
                    inventory()
                    continue
                elif a == 'c'.lower():
                    break
                else:
                    NO()
            break
        else: 
            NO()
    
#

#
    print('You walk along the road for a good 15 miuntest, you then see a split in the road.')
#

#SPLIT IN THE ROAD READ SIGN   
    while True:
        sign2 = input('Left has a sign and right does not, would you like to read the sign ')
        line = (sign2)
        if sign2 == 'y'.lower() or sign2 == 'yes'.lower():
            print ('DO NOT GO THIS WAY')
            break
        elif line == 'q'.lower():
            quit()
        elif line == 'i'.lower():
            inventory()
            continue
        else:
            break
#

#WENT RIGHT
    while True:    
        b = input('Would you like to go right(r) or left(l) ')
        line = (b)
        if b == 'r'.lower():
            print('You continue going the way that is intended')
            print('You go down the path for about ten miuntes and come across a man standing and staring blankly into space')
            while True:
                g  = input('Would you like to talk with the man or(t) or continue down the path(c) ')
                line = (g)
                if g == 't'.lower():
                    print('The man starts to speak')
                    print('"It is too late, it'+ "'" + 's a trap, go back, go back, go back, go back, go back, go ba-k-kkc-kc"')
                    print('Foam starts to acumulate in the mans mouth and he drops to the floor dead.')
                    while True:
                        f = input('Would you like to seach his body (s) go back (b) or coninue(c) ')
                        line = (f)
                        if f == 's'.lower():
                            print ('You found 5 boldtown coins')
                            coins = 5
                            print('And you continue on the path')
                            break
                        elif line == 'q'.lower():
                            quit()
                        elif line == 'i'.lower():
                            inventory()
                            continue    
                        elif f == 'b'.lower() and choose_to_go_back == 0:
                            WENT_BACK_1
                            break
                        elif f == 'b'.lower() and choose_to_go_back == 1:
                            WENT_BACK_2
                        elif f == 'c':
                            break
                    break
                elif line == 'q'.lower():
                    quit()
                elif line == 'i'.lower():
                    inventory()
                    continue
                elif g == 'c'.lower():
                    break
            break

#

#WENT LEFT    
        elif line == 'q'.lower():
            quit()
        elif line == 'i'.lower():
            inventory()
            continue     
        elif b == 'l'.lower():
            print('You continue left, good luck')
            print('...')
            print('After a few hours of walknig you decide it is time that you should stop')
            print('You decide to stop and rest. You set up a little camp ')
            print('...')
            print('You fall asleep')
            print('...')
            while True:
                d = input('You here a noise late into the night, do you decide to wake up ')
                line = (d)
                if d == 'y'.lower() or d == 'yes'.lower():
                    while True:
                        print('You notice a pair of eyes in the trees around you')
                        e = input ('Would you like to check it out(c) or walk away and forget about it(w) ')
                        line = (e)
                        if e == 'c'.lower():
                            STOP()
                        elif e == 'w'.lower():
                            break
                        elif line == 'q'.lower():
                            quit()
                        elif line == 'i'.lower():
                            inventory()
                            continue
                        else:
                            NO()
                    break
                elif line == 'q'.lower():
                    quit()
                elif line == 'i'.lower():
                    inventory()
                    continue
                else:
                    NO()
            break
        else:
            NO()
                
        
#    
    print('...')
    print('The path you decided to go eventually connects back at the end ')
    print('After another hour of walking on what seems like the endless path of nothing but trees, you come upon a village with a sign that labels it to be boldtown village')
    print('...')
    
    
#TOWN    
    while True:
        h = input('Would you like to visit the town, they may have resouses ')
        line = (h)
        if h ==  'y'.lower() or h == 'yes'.lower():
            print ('You see the village people and the village people see you, they all wave hi at the same time stoping what they are doing as if you are the fist person that you have ever seen before')
            print ('You need sleep, go to the hotel after you are done with your activity')
            while True:
                i = input('Would you like to go to the shop(s) or skip and go to the hotel(h) ')
                line = (i)
                if i == 's'.lower() and coins >= 1:
                    while True:
                        inventory()
                        j = input('You can by a torch for 2 coins(t) and/or a knife for 3 coins(k) click(e) to exit ')
                        line = (j)
                        if j == 't'.lower() and coins >= 2:
                            print('You got a torch')
                            torch = 1
                            coins -= 2
                            continue
                        elif j == 't'.lower() and coins <= 1:
                            print("You don't have enough coins")
                            continue
                        elif j == 'k'.lower() and coins >= 3:
                            print('You got a knife')
                            knife = 1
                            knife -= 3
                            continue
                        elif j == 'k'.lower() and coins <= 2:
                            print("You don't have enough coins")
                            continue
                        elif j == 'e'.lower():
                            break
                        elif line == 'q'.lower():
                            quit()
                        elif line == 'i'.lower():
                            inventory()
                            continue
                        else:
                            NO()
                    continue
                elif i == 's'.lower() and coins <= 1:
                    print('You do not have enough coins')
                    continue
                elif line == 'q'.lower():
                            quit()
                elif line == 'i'.lower():
                    inventory()
                    continue
                elif i == 'h'.lower():
                    print('You went to the hotel to get some sleep')
                    print('You talk to the hotel manager and he tells you that you will be able to have a free night at the hotel')
                    print("You accept the free night at the hotel. He tells you you need to go outside and your room is in the home next to this biulding")
                    print('He insists that he walks you over to the room')
                    while True:
                        k = input('Would you like him to come with you ')
                        line = k
                        if k == 'y'.lower() or k == 'yes'.lower():
                            print('He lights a candle and says. You never want to be in the dark around here. Something might come for you')
                            print ('He walks you to your room and you go to sleep')
                            break
                        elif line == 'q'.lower():
                            quit()
                        elif line == 'i'.lower():
                            inventory()
                            continue
                        else:
                            while True:
                                if torch >= 1:
                                    j = input('Would you like to light your torch ')
                                    line = (j)
                                    if j == 'y'.lower() or i == 'yes'.lower():
                                        torch -=1
                                        print ('You walk to your room and go to sleep')
                                        break
                                    elif line == 'q'.lower():
                                        quit()
                                    elif line == 'i'.lower():
                                        inventory()
                                        continue
                                    else:
                                        print('You walk to your room in the dark, you can not see anything around you. You here a swoosh in the dark and drop to the ground dead')
                                        NO()
                                else:
                                    print('You walk to your room in the dark, you can not see anything around you. You here a swoosh in the dark and drop to the ground dead')
                                    NO()
                            break
                    break
            break        
        elif line == 'q'.lower():
            quit()
        elif line == 'i'.lower():
            inventory()
            continue
        else:
            print('You walk for 15 miunets and relize the path looks the same')
            print('...')
            print('You come upon a village with a sign that labels it to be boldtown village')
            continue
         
# Day 2 in village

else:
    print('Maybe you will play next time, might have fun ://///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////')
    quit()

The game is not finished yet but it is able to run fine in the terminal, let me know what you think the problem is

3
  • 2
    You need to provide a minimal reproducible example. And post a stack trace as a text not as a screenshot. It seems underlying Pyodide throws a JS exception when quit() is called. Try catching the SystemExit exception in Python. Commented Jan 25, 2023 at 6:10
  • input in pyscript does not work like it does in a console. You should create some HTML to do your input. pythonprogramming.altervista.org/… Commented Jan 25, 2023 at 6:26
  • 1
    @Tim Roberts, no input() works fine on PyScript although it's ugly. Commented Jan 25, 2023 at 7:28

1 Answer 1

2

A challenge with moving from a terminal to a browser is that the way users interact in a linear manner in the terminal and the way that the browser needs to be driven to get the same linear interaction are a little different.

The box being popped up over the page is the input call you are doing during the script. The way that PyScript (or most other ways of working in a browser) operates, if you print things in the script before you run input you won't see them on the page until after the user has completed the input and the script has yielded control back to the browser.

Some comments that hopefully will help you move forward with the project:

  1. All of your code is being run at the time the page is loaded, so you won't see any output on the page until either the user has completed all the input responses or you've had an error.

To get around that situation, you need to make some changes to how your script runs. Particularly, you want to use what is referred to as 'asynchronous' or 'event-driven' programming. This means that you write code that performs parts of the logic for your game, reacting to the events that the user provides in order to move through the game, but yielding control back to the browser whenever you want to wait for user to take an action. input is one way of asking the browser to get interaction from the user, but it breaks the rendering of anything before it in that part of the script, so I'd suggest your use case is better with a different method. I'll come back to that.

To write something like this in a web browser, you render the initial page, then add code to individual parts of the page that will run when the user interacts with those parts of the page. Those bits of code can then change the page, setting up for the next interaction.

You'll also find debugging the other errors easier if you make it possible to work with individual bits of code and verify they work independently as you build your game.

  1. Using an HTML alternative to input might be more user-friendly and easier to work with in your code.

This is what I referred to above. If you put an "input" element on the page (<input id="command"> as HTML instead of input() as a Python call) then you can work with it like this in your script whenever you want to see what the user has typed:

command = document.getElementById('command').value

This allows you to have the user type into the actual web page under the instructions you've given them, and prevents the locking of the screen while the user types.

  1. Writing out all the logic for the user's decisions as code each step of the way is prone to errors and makes the code fairly long.

Instead, if you write the logic as generic logic and then provide it with data that describes the steps the user goes through, then you can get your code smaller and it is easier to debug.

Suggestions

I've made an example below for a simple structure for doing this with the beginning of a game.

First, we need a few additional things on the HTML page:

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>
  <body> 
    <div id="narrative"></div>
    <div>
      <input id="command"></input>
      <button class="button" type="button" id="button">Go!</button>
    </div>
    <py-script src = "game.py" />
  </body>
</html>

There is now an input that the user can type into, and a button for them to say to perform an action. There's also a space to write out the narrative of the game.

You can hook a function up to the button using this PyScript code:

from js import document
from pyodide import create_proxy

def react_to_input(event):
    pass

input_proxy = create_proxy(react_to_input)
document.getElementById("button").addEventListener("click", input_proxy)

Note that you don't get the command as a parameter to the function - you need to then get it from the browser:

def react_to_input(event):
    command = document.getElementById('command').value

I'll also create some functions that output the narrative to the page, either as a plain text, italics for a prompt, or bold for repeating back what you said to it:

def emit_narrative(description):
    document.getElementById('narrative').innerHTML += f'<div>{description}</div>'

def emit_prompt(prompt):
    if prompt == "":
        prompt = "What next?"
    emit_narrative(f'<i>{prompt}</i>')

def emit_command(command):
    emit_narrative(f'<b>{command}</b>')

There's a lot of ways you could go from here in terms of making the game logic, but to work well in a browser you still need it to be driven by the user's actions. I think working with a data structure that stores all your locations and the commands that the user might type would help to make the code easier to modify to work in an event-driven way:

locations = {
    'start': {
        'description': """You are at the start.""",
        'prompt': 'Would you like to begin?',
        'state': '',
        'commands': { 'yes': 'begin', 'y': 'begin', 'DEFAULT': 'lose_game' }
    },
    'begin': {
        'description': """You have found a sign: 'Read the rules!'.""",
        'prompt': 'Would you like to read the rules?',
        'state': '',
        'commands': { 'yes': 'read_rules', 'y': 'read_rules', 'DEFAULT': 'lose_game' }
    },
    'read_rules': {
        'description': """First rule of game is read the rules.""",
        'prompt': '',
        'state': '',
        'commands': { 'win the game': 'win_game', 'DEFAULT': 'lose_game' }
    },
    'win_game': {
        'description': """You have won.""",
        'state': 'win'
    },
    'lose_game': {
        'description': """You have lost.""",
        'state': 'lose'
    }
}

We can then use this in the react_to_input function:

def react_to_input(event):
    global current_location
    global game_over
    if game_over:
        emit_narrative(f"<i>The game is over, so I'm ignoring you'</i>")
        return
    command = document.getElementById('command').value
    document.getElementById('command').value = ""
    emit_command(command)
    if (command in locations[current_location]['commands']):
        current_location = locations[current_location]['commands'][command]
    else:
        current_location = locations[current_location]['commands']['DEFAULT']
    emit_narrative(locations[current_location]['description'])
    if locations[current_location]['state'] == 'lose':
        game_over = True
        emit_prompt("You have lost!")
    elif locations[current_location]['state'] == 'win':
        game_over = True
        emit_prompt("You have won!")
    else:
        emit_prompt(locations[current_location]['prompt'])

Then all we need to do to stitch it all together is put some startup code in:

current_location = 'start'
game_over = False

emit_narrative(locations[current_location]['description'])
emit_prompt(locations[current_location]['prompt'])

I'll put the code again all together for easier reading:

from js import document
from pyodide import create_proxy

locations = {
    'start': {
        'description': """You are at the start.""",
        'prompt': 'Would you like to begin?',
        'state': '',
        'commands': { 'yes': 'begin', 'y': 'begin', 'DEFAULT': 'lose_game' }
    },
    'begin': {
        'description': """You have found a sign: 'Read the rules!'.""",
        'prompt': 'Would you like to read the rules?',
        'state': '',
        'commands': { 'yes': 'read_rules', 'y': 'read_rules', 'DEFAULT': 'lose_game' }
    },
    'read_rules': {
        'description': """First rule of game is read the rules.""",
        'prompt': '',
        'state': '',
        'commands': { 'win the game': 'win_game', 'DEFAULT': 'lose_game' }
    },
    'win_game': {
        'description': """You have won.""",
        'state': 'win'
    },
    'lose_game': {
        'description': """You have lost.""",
        'state': 'lose'
    }
}

def emit_narrative(description):
    document.getElementById('narrative').innerHTML += f'<div>{description}</div>'

def emit_prompt(prompt):
    if prompt == "":
        prompt = "What next?"
    emit_narrative(f'<i>{prompt}</i>')

def emit_command(command : str = ""):
    emit_narrative(f'<b>{command}</b>')

def react_to_input(event):
    global current_location
    global game_over
    if game_over:
        emit_narrative(f"<i>The game is over, so I'm ignoring you'</i>")
        return
    command = document.getElementById('command').value
    document.getElementById('command').value = ""
    emit_command(command)
    if (command in locations[current_location]['commands']):
        current_location = locations[current_location]['commands'][command]
    else:
        current_location = locations[current_location]['commands']['DEFAULT']
    emit_narrative(locations[current_location]['description'])
    if locations[current_location]['state'] == 'lose':
        game_over = True
        emit_prompt("You have lost!")
    elif locations[current_location]['state'] == 'win':
        game_over = True
        emit_prompt("You have won!")
    else:
        emit_prompt(locations[current_location]['prompt'])

current_location = 'start'
game_over = False

emit_narrative(locations[current_location]['description'])
emit_prompt(locations[current_location]['prompt'])

input_proxy = create_proxy(react_to_input)
document.getElementById("button").addEventListener("click", input_proxy)

I haven't got an inventory in there, or more complicated aspects of the rules. But hopefully it provides some information that is useful!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.