Changing python to read code differently? - python

When I make text adventures in python for my friends, I am constantly frustrated that I have to code the adventure upward since python reads code from top to bottom. For example:
def stage2():
def stage1():
def start():
Then so on and so forth.. Is there any way that I can make python read the code in a different way so that I can code text adventures from the top up?

You can write your functions in whatever order you like, so long as they are defined before they are called.
For instance,
def start():
print("Welcome to the adventure")
stage1()
def stage1():
print("You made it this far!")
stage2()
# if you called start() here,
# you would have an error when stage1() tries to call stage2(),
# because the interpreter doesn't know what a stage2 is yet.
def stage2():
print("Oops - you died.")
start()
works fine.
On the other side of things:
def test():
if True:
print("Yup")
else:
slartibartfast()
test()
runs fine because the interpreter never gets around to asking what a slartibartfast is ;-)

Related

How to kill a thread that uses an input?

I am trying to make an online game using socket and threading. It is a competitive hangman game, where the fastest one to complete the word wins. I want that, when one of the players wins/runs out of lives, the other player gets kicked out of its game and is told that they have won/lost. However, I have run into a problem.
1: If I use "threading", there is no way to close the thread (since the program needs to read user input, I need to use the input() function, which means that the player's thread can't be terminated until they insert a character).
2: If I use "multiprocessing" (which has a terminate() function), I can't use input() (multiprocessing doesn't allow it).
I am in a stalemate, what should I do?
P.D: This is my first stackoverflow post ever, please tell me if I made a mistake at writing the post!
Ok, I got it, it is an ugly and complicated solution, but it works.
I created a program that emulates the "input" command, without being the input command itself (so it doesn't stop the processes).
Here it is:
import pynput.keyboard
global string
string=""
c=0
global oldprinted
oldprinted=""
def GetInput():
import pynput
def on_press(key):
global oldprinted
global string
if key==pynput.keyboard.Key.enter:
listener.stop()
else:
prompt="Introduce your input: "
try:
if key==pynput.keyboard.Key.backspace and len(string)>0:
string=string[:-1]
else:
string+=str(key.char)
prompt+=(string)
print(" "*len(oldprinted),end="\r")
print(prompt,end="\r")
oldprinted=prompt
except:
pass
print("Introduce your input: ",end="\r")
with pynput.keyboard.Listener(suppress=True,on_press=on_press) as listener:
listener.join()
return string
data=GetInput()
print("\n")

How do I run a function from an input before the code for the function has been read?

I am writing a game, similar to mastermind, and I want a choice bewteen an easy or hard version. I'm not sure how to do this as I need the question before the actual game starts but then there's an error because the function is being called to run before it has been assigned.
def difficulty():
difficulty = input("would you like to the easy or hard version?")
if difficulty == ("easy"):
easy()
elif difficulty == ("hard"):
hard()
difficulty()
This is the start then after is the function with the harder game code then the easier game code. I am trying to run the easy if they request easy and vice versa but the easy () and hard() don't run the code as it isn't assigned yet. I think this is because python reads the code from top to bottom and stops when it finds an error but not sure.
I have never used this before so I apologise if things are unclear or I have done some things wrong.
I am also relatively new to python.
If anybody could help me I would greatly apprectiate it.
Python is quite smart when it comes to identifying functions inside a module. For instance you could do this:
def x():
y()
def y():
print("Y")
x()
and it would execute correctly.
You are right about the execution of a code block that happens from top to bottom, as well as the definitions of those functions will also be constructed top to button, but executed afterwards.
I see some issues in your code.
you do difficulty = input("would you like to the easy or hard version?") but at the same time you have a function called def difficulty. There is a conflict there, try to rename that variable.
you don't need to do ("easy"), it's overkill, you can compare directly to "easy".

Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code?

All programs which I see in tutorials are console and code is executed from first line to the last line and if there is while everything starts from the first line. Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code? The best example of what I want to do is router CLI. Where can I find such examples?
def main():
while(True):
initial_setup() #choose IPs to monitor
while(True):
do_some_work() # do monitor the IPs
I need some listener in the secons while which detects keypresses and then I go to initial setup, meanwhile do_some_work works and only after I finish adittional changes in initial_setup do_some_work restarts.
Sorry I am noob and not very good in explaining probaly because English is not native for me. The best example from real life I can name is CLI of router, you can setup intreface and meanwhile router do routing in the background.
Code for Sergio S:
import threading
import time
def hello():
while(True):
print("Hello")
time.sleep(2)
def hi():
while(True):
print("hi")
time.sleep(2)
def press_key():
a=input()
a=False
return a
def circle():
MrBoolean=True
while(MrBoolean):
thr=[]
thr.append(threading.Thread(target=hello))
thr.append(threading.Thread(target=hi))
thr.append(threading.Thread(target=press_key))
for i in thr:
i.start()
for i in thr:
i.join()
mrBoolean=thr[3]
def main():
while(True):
circle()
main()
From your description, it seems you're searching for something called multithreading: while one part of the application does one thing, the other does something else. See these other questions for more details: How to use threading in Python? , How to stop a looping thread in Python?
whats_typed = input('Say Aah:')
if whats_typed.strip() == 'Aah':
print('Thanks!')
else:
print('Whoops. Your input was:', whats_typed)
The above changes what is executed depending on user input when the program is run.

Trying to execute a set of functions in order

I am a Python noob, and I'm trying to make a washing device, programming the interface with Python. For now, the machine should work like that:
Wash
Tell washing is complete
Dry
Tell drying is complete
For this, after times for washing/drying are entered, a button is pressed:
button1 = Button(window.tk, command = lambda:main_process(int(varWashtime.get()), int(varDrytime.get())))
def main_process(wash_seconds,dry_seconds):
wash(wash_seconds)
stop_wash()
dry(dry_seconds)
stop_dry()
return
def wash(seconds):
varWashStarted.set("Washing Started")
Timer(seconds,idle_fnc).start()
return
def stop_wash():
varWashStarted.set("Washing Stopped")
Timer(3,idle_fnc,()).start()
return
def dry(seconds):
varDryStarted.set("Drying Started")
Timer(seconds,idle_fnc,()).start()
return
def stop_dry():
varDryStarted.set("Drying Stopped")
return
def idle_fnc():
pass
return
Here, I used the function idle_fnc to make threading.Timer properly work.
I found out that I can just use Timer to call other functions after each other, but I would prefer to return from a function, then branch to a new one.
My problem is, as I click the button, the whole thing executes without waiting; I instantly see "Washing Stopped" and "Drying Stopped" on the corresponding label, without the delays triggered.
What is the problem?

Text adventure in Python issue

I am working on a text adventure in Python. I'm very new to the concept of object oriented programming (and programming in general), so I'm not entirely sure what went wrong. Well, what I've done so far is made two methods; one that handles what the user types in, and one that dictates what will happen in the game, using other methods defining rooms that I will create in the future. One problem I have, though, is that I can't test the program by running it! When I run it, there is no prompt for user input - the program just ends without returning any error. There's not much code so maybe you could help me in determining the problem! I'm sure there's something really obvious in there I've forgotten...
class Main(object):
def handle_events(self, userinput, cmd):
self.userinput = userinput
self.cmd = cmd
userinput = raw_input('> ')
cmd = {'use' : use,'quit' : quit, 'help' : help}
if userinput[0] not in cmd:
print "Invalid command. Check [help] for assistance."
def main(self, handle_events):
print '''You are in a dark room filled with
strange and ominous objects.
After some feeling around, you think
you can make out a light switch.'''
self.userinput
if userinput[1] == 'switch':
print "You flicked the switch!"
Main().main
You are not calling your method. Main().main is just a reference to the method. To call it you need another set of parentheses: Main().main().

Categories