Trying to run Python in html

2024/10/10 14:29:44

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')#STARTbegin = 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 = 1def 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_1break
elif f == 'b'.lower() and choose_to_go_back == 1:WENT_BACK_2'''if begin == ('yes').lower() or begin == ('y').lower():
#SIGNwhile 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.')breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse: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():breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelif 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()continueelif a == 'c'.lower():breakelse:NO()breakelse: 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')breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse:break
##WENT RIGHTwhile 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 = 5print('And you continue on the path')breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continue    elif f == 'b'.lower() and choose_to_go_back == 0:WENT_BACK_1breakelif f == 'b'.lower() and choose_to_go_back == 1:WENT_BACK_2elif f == 'c':breakbreakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelif g == 'c'.lower():breakbreak##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():breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse:NO()breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse:NO()breakelse: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 = 1coins -= 2continueelif j == 't'.lower() and coins <= 1:print("You don't have enough coins")continueelif j == 'k'.lower() and coins >= 3:print('You got a knife')knife = 1knife -= 3continueelif j == 'k'.lower() and coins <= 2:print("You don't have enough coins")continueelif j == 'e'.lower():breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse:NO()continueelif i == 's'.lower() and coins <= 1:print('You do not have enough coins')continueelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelif 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 = kif 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')breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse: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 -=1print ('You walk to your room and go to sleep')breakelif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse: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()breakbreakbreak        elif line == 'q'.lower():quit()elif line == 'i'.lower():inventory()continueelse: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 villageelse: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

Answer

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_proxydef react_to_input(event):passinput_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_locationglobal game_overif game_over:emit_narrative(f"<i>The game is over, so I'm ignoring you'</i>")returncommand = document.getElementById('command').valuedocument.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 = Trueemit_prompt("You have lost!")elif locations[current_location]['state'] == 'win':game_over = Trueemit_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 = Falseemit_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_proxylocations = {'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_locationglobal game_overif game_over:emit_narrative(f"<i>The game is over, so I'm ignoring you'</i>")returncommand = document.getElementById('command').valuedocument.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 = Trueemit_prompt("You have lost!")elif locations[current_location]['state'] == 'win':game_over = Trueemit_prompt("You have won!")else:emit_prompt(locations[current_location]['prompt'])current_location = 'start'
game_over = Falseemit_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!

https://en.xdnf.cn/q/118447.html

Related Q&A

Removing from a string all the characthers included between two specific characters in Python

Whats a fast way in Python to take all the characters included between two specific characters out of a string?

Pyside6: Create QTabWidget with function rather than class

Ive been trying to make an application using Pyside6 and cant seem to understand why we cant create a QDialog having QTabWidget with just functions. I am not sure if I am making a mistake somewhere so,…

Pythons End Of Life

What exactly will happen to Python 2.7 after 1/2020?I understand that Python 2.7 will no longer be supported but what will actually happen? Does it mean that decision makers will delete the whole cod…

Gathering numerical data from a string input

I would like to get user input for their credit rating e.g AAA, A, BBB etc and then assign an interest rate to this. For example, if the user has a good credit rating e.g AAA I would charge an interest…

Getting Turtle in Python to recognize click events [duplicate]

This question already has an answer here:Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates(1 answer)Closed 5 months ago.Im trying to make Connect …

Delete last widget from gridlayout

I have a Grid layout in which I add Qlineedits at runtime. while pushing the button I want to delete the last qline edit from the gridlaout Why does this function delete all qlinedits at the same time …

Counting unique words

Question:Devise an algorithm and write the Python code to count the number of unique words in a given passage. The paragraph may contain words with special characters such as !, ?, ., , , : and ; and …

Django cant find template dir?

Originally I had just one app in my Django project, the templates consisted of an index.html a detail.html and a layout.html ... the index and detail files extended the layout. They all lived in the sa…

Python Programming Loop

Im doing an assignment where I have to conduct a quiz for different topics. This is my code so far.print("Hello and welcome to Shahaads quiz!") #Introduction name = input("What is your n…

How to fix stale element error without refreshing the page

Trying to get details of Tyres on this page. https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL . Each tyre has different FINITIONS. The price and other details are different for each FINITIONS. I w…