I am building a small car simulator game. it's like a terminal window, I type start and it started normally. I press stop and it stops. Unfortunately, when I start it again, I had a error like this.
Traceback (most recent call last):
File "C:\Users\****\OneDrive\New folder\Car Emulator.py", line 12, in <module>
turtle.shape('square')
File "<string>", line 5, in shape
turtle.Terminator
I don't know what does this mean, because I called the turtle.bye() function. Although I Searched all the Stack Overflow forums just like that. the code is like this:
while True:
command = input(">").lower()
if command == "start":
if engine == False:
engine = True
print("Car started.")
t.shape('square')
else:
restart = input("Car already started. Restart? (Y) Yes (N) No ")
if restart.upper == "Y":
engine = False
t.bye()
engine = True
t.shape('turtle')
print("Car Restarted.")
elif command == "stop":
if engine == True:
engine = False
t.bye()
print("Car stopped.")
else:
print("Car already stopped.")
elif command == "help":
print('''
start - start the car
stop - stop the car
quit - exit
''')
elif command == "quit":
please someone explain this to me
while True:
command = input(">").lower()
if command == "start":
if engine == False:
engine = True
print("Car started.")
#t.shape('square')
else:
restart = input("Car already started. Restart? (Y) Yes (N) No ")
if restart.upper == "Y":
engine = False
# t.bye()
engine = True
#t.shape('turtle')
print("Car Restarted.")
elif command == "stop":
if engine == True:
engine = False
#t.bye()
print("Car stopped.")
else:
print("Car already stopped.")
elif command == "help":
print('''
start - start the car
stop - stop the car
quit - exit
''')
elif command == "quit":
output
[root#localhost ~]# python3 test.py
>start
Car started.
>stop
Car stopped.
>start
Car started.
>stop
Car stopped.
>stop
Car already stopped.
>start
Car started.
>start
Car already started. Restart? (Y) Yes (N)
Check your while loop, if you want to repeat anything inside the while loop, it should have a correct indentation.
Example https://www.w3schools.com/python/python_while_loops.asp
Note: Removed some part of the code to test it.
Related
1--when we enter help following should appear:
start-to start the car
stop-to stop the car
quit-to exit
2--when we enter started message : car started should be shown
3--when entered stop: Car stopped should be displayed
4--when entered quit...should be exited through the loop
5--we cannot start car two times or more --message like car started already should be shown same with the stop
my code:
command=""
while True:
command=input('>').lower()
if command=='start':
print("Car started")
elif command=='stop':
print("Car stopped")
elif command=="help":
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
elif command=='quit':
break
else:
print("I don't understand that")
I did these part but was unable to prevent the car from starting twice. Help :)
You can use a simple flag is_car_started to record the status of whether the car is already started or not. When you start the car, set is_car_started to True. When you stop the car, set it to false.
command=""
is_car_started = False
while True:
command=input('>').lower()
if command=='start':
if is_car_started == True:
print("Car started already")
else:
is_car_started = True
print("Car started")
elif command=='stop':
is_car_started = False
print("Car stopped")
elif command=="help":
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
elif command=='quit':
break
else:
print("I don't understand that")
you can define a boolean variable outside your while loop. Like first_start = true.
Then inside your while loop in the if statement where you check if command=="start" you can set first_start to false.
On the very top you can add an if-statement that prints your message when first_start == false.
The if-statement would look something like this:if not first_start:...
You need to keep track of whether or not the car is started. You can also achieve a superior structure to your code with match/case (requires Python 3.10). For example:
started = False
while True:
match input('Enter command: ').lower():
case 'start':
if started:
print('Already started')
else:
print('Car started')
started = True
case 'stop':
if started:
print('Car stopped')
started = False
else:
print('Car not started')
case 'quit':
print('Goodbye')
break
case 'help':
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
case _:
print("I don't understand that")
i had a similar issue and this is how i resolved it
hope it helps...
if is_car_started == True:
print("car started already...")
else:
is_car_started = True
print("car started... ready to go")
command = input("> ")
started = False
while True:
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
it renders "car has already started" infinite time when i state "start" and likewise with other inputs. how do i inhibit this? would be very helpful if you explain it in beginner terms, thank you!!
You need to put the command inside the while loop, so that the loop stops until the user has enterd his desired command:
started = False
while True:
command = input("> ")
if command == "start":
...
Male sure to add the input to thie while loop. In your case, it is just taking one input and then the value of command is fixed. So, it is an infinite loop.
But when you change the location and keep it inside the loop, every time it asks for the input, the value of command will change.
Also, .lower() will convert the input to lower case to remove case insensitivity
started = False
while True:
command=input('>> ').lower()
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
You need input a new command every while loop, otherwise it will fall into infinite loop with the same first inputed command condiction.
code:
started = False
while True:
command = input("> ")
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
result:
> start
car started
> stop
car is stopped
> stop
car has already stopped
> start
car started
> start
car has already started
> quit
What is happening in your loop is:
while True - A while loop will always run until this statement is False, as True is never False, this will loop forever until the break command is ran.
if command == "start" - Because command is set outside of the while loop, it is always equal to start and this if statement will always run
The first run, it will print "car started" and every other loop after will print "car has already started".
To stop this, you need to change the value of command to change the behaviour each time you loop. To do this, you can just get an input at the start of the loop:
started = False
while True:
command = input("> ") # Input inside the loop
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
You are never changing the value for command and the loop is running "while True", so it will never stop.
When the user gives the input, lets say "start", your script is assigning the string "start" to the command.
It is looping infinitely because the first if statement is checking the value for the variable command, which after the input will always be "start".
You can solve it in multiple ways.
One is to change the name of the variable after the if statement:
command = input("> ")
started = False
while True:
if command == "start":
if started:
print("car has already started")
command = ""
Another way is to add break commands after each if comparison.
You can also change while True to while not started. The loop will continue until you change the variable started to True, which you are already doing after each conditional block.
Little context: I'm working with a Zumi (physical toy car that can be programmed with Python)
However, this issue pertains to threading, looping, and inputs. All my threading works fine. However, a specific while loop acts weirdly after the first iteration.
from zumi.zumi import Zumi
import threading, time, sys
zumi = Zumi()
def commands(star):
global comm
print("thread 1 started")
time.sleep(1)
while star == "t":
try:
inp = str(input("Command: ")) <---
if inp.lower() == "d":
comm = "d"
elif inp.lower() == "r":
comm = "r"
elif inp.lower() == "p":
comm = "p"
elif inp.lower() == "b":
print("Killing Zumi")
zumi.stop()
sys.exit()
else:
print("I don't understand.")
except EOFError as e:
print(end = "")
inp = ""
def constacheck(star):
global comm
print("thread 2 started")
while star == "t":
if comm == "d":
forwards()
elif comm == "r":
backwards()
elif comm == "p":
parallel()
star = "t"
inp = ""
comm = ""
print("create and start thread 1")
x = threading.Thread(target=commands, args=(star))
x.start()
time.sleep(1)
print("create and start thread 2")
z = threading.Thread(target=constacheck, args=(star))
z.start()
I put an arrow which points to the area of interest. The first time I run the code, I am asked for the input, and it does everything correctly. However, immediately afterwards, it should ask for the same input, and change the variables according (which will them affect my second loop- constacheck). Instead it returns an EOFError: Error when reading a line, which I solved by making the code repeat the loop, ignoring the error. However, every loop afterwards raises the same error, and thus creates a constant loop of printing "Command: "
It looks something like this:
Command: d
Driving forwards.
Command: Command: Command: Command: Command: Command: Driving forward.Command: Command: Command: Command: Command: Command: Command: Driving forward.
etc.
How do I stop the EOFError, and every time the while loop in commands() loops, ask for an input?
Thanks.
I'm programming a simple text adventure game with Python 3 and the cmd module.
I need to somehow trigger the game over method but I didn't find a solution on document.
The CMD module got the do_quit() function, but that needs user input, and quit() or exit() kills the whole program, whereas I just need to get out of cmdloop()
Any idea how to deal with this?
Thanks in advance!
def moveDirection(direction):
global location
if direction in rooms[location]:
if rooms[rooms[location][direction]].get(UNLOCKED, True) == True:
print('You move to the %s.' % direction)
location = rooms[location][direction]
if location == 'Hallway' and bGuardAlive == True:
print("Game over! Guard caught you!")
printLocation(location)
else:
print("Door is locked")
else:
print('You cannot move in that direction')
def main():
printLocation(location)
GameLoop().cmdloop()
class GameLoop(cmd.Cmd):
prompt = '\n> '
def do_quit(self, arg):
"""Quit the game."""
return True
Usually (if I understand correctly), you create you own class derived from Exception, you throw the exception at the place you want to exit, and you will have a try clause where you want to land.
After trial and error i get it working. I needed use postcmd()
Here is my code:
def postcmd(self, stop, line):
if bGuardAlive == False and location == 'Hallway':
print("Game over! Guard caught you!")
return True
elif location == 'Tower Ruins':
print("You won!")
return True
return stop
Hopefully this will help somebody
I am currently writing an audio playout system using python3 and afplay. I have run into a problem where I cannot get it to automatically go to the next song in the playlist, whilst still allowing for user control.
for i in range(metadata["length"] - start):
i += start
curr = songs[i]
play(directory + curr)
paused_bool = False
while True:
clear()
print("Currently playing track #" + str(i+1) + ", called '" + curr + "', from playlist '" + metadata["name"] + "'.")
command = input("What would you like to do? 'play', 'stop/exit', 'pause', or 'skip/next': ")
if command == "play" or command == "pl":
if not paused_bool:
print("It is already playing.")
else:
play(directory + curr)
elif command == "stop" or command == "st" or command == "quit" or command == "q" or command == "exit":
stop()
return
elif command == "pause" or command == "p" or command == "pa":
if paused_bool:
print("The audio shall remain paused.")
paused_bool = True
stop()
elif command == "move the hell on" or command == "skip" or command == "next" or command == "n" or command == "s" or command == "":
stop()
break
clear()
Above is the code that plays each song inside a folder. I want to be able to manually go to the next song using the "next" command, but also have it automatically go to the next after some time has passed, specifically the length of the song.
I have tried using the threading package, but I then run into a problem when I can't break the while loop from a function:
for i in range(metadata["length"] - start):
i += start
curr = songs[i]
play(directory + curr)
paused_bool = False
while True:
clear()
def auto():
time.sleep( length( curr_song ) )
stop() # stop() & break goes to the next song
break
thread = Thread(target = auto, args = [])
thread.start()
print("Currently playing track #" + str(i+1) + ", called '" + curr + "', from playlist '" + metadata["name"] + "'.")
command = input("What would you like to do? 'play', 'stop/exit', 'pause', or 'skip/next': ")
if command == "play" or command == "pl":
if not paused_bool:
print("It is already playing.")
else:
play(directory + curr)
elif command == "stop" or command == "st" or command == "quit" or command == "q" or command == "exit":
stop()
return
elif command == "pause" or command == "p" or command == "pa":
if paused_bool:
print("The audio shall remain paused.")
paused_bool = True
stop()
elif command == "move the hell on" or command == "skip" or command == "next" or command == "n" or command == "s" or command == "":
stop()
break
clear()
I apologise that the question is incredibly convuluted, but any help would be greatly appreciated.
You may want to use scheduler.
It would change somewhat the logic of your code, but it would likely be more functional.
You would, by default, schedule an event for playing the next song (use enter or enterabs). You could get the running time of the current song so you know when to schedule the next one.
If "next" is selected, you would cancel the previous event and schedule two others: 1) a new one for immediate execution, play the next song, 2) play the following song.