As one of my first projects trying to learn python I decided to make an RC car. But now I've been stuck with the same 2 problems for a long time, and can't find a real good answer. In my code for the moment, I connect to my raspberry through bluetooth from my phone. When I send simple commands, the care moves. But I also added 3 sensors so I could build some sort of autopilot, where the car evades objects in his path.
My code: https://pastebin.com/ggUFcrpT
def serialread():
while True:
line = ser.read()
print line
if line == 's':
ser.write("Abandom ship! \n")
resetmotorpins()
elif line == 'f':
ser.write("Going forward, captain! \n")
resetmotorpins()
forward()
elif line == 'r':
ser.write("Dizzy! \r\n")
resetmotorpins()
right()
elif line == 'l':
ser.write("If nothing goes right, go left! \n")
resetmotorpins()
left()
elif line == 'b':
ser.write("nah fam, i'm out, f*ck this shiet. \r\n")
resetmotorpins()
reverse()
elif line == "t":
ser.write("autoPilot activate \n")
auto = 1
resetmotorpins()
while auto == 1:
line = ser.read()
if line == "y":
ser.write("autoPilot deactivated \n")
resetmotorpins()
auto = 0
else:
meet()
elif line == "m":
meet()
elif line == 'o':
servomotorright()
elif line == 'x':
servomotorleft()
elif line == 'q':
waardesVragen()
I think it gets stuck at the line = ser.read() and that it needs a line to run through the code. But I have no idea how to make it just loop constantly and make somekind of interupt when I send a letter/command.
On top of that I'm trying to initialize mulithreading so I can print my values from the 3 sensor constantly and make an interrupt when it's close to hitting an object. But the multithreading seems to not be working, once I got into the sensor value printing, it never leaves that loop and doesn't listen to my bluetooth connection anymore.
Any suggestions? I hope I posted this right, it's my first question here.
I'm using python 2.7.5 on a raspberry pi B
Related
I'm making a short little test, and I'm planning to have achievements and such. However the code doesn't work
All of this is the achievements and the variables, this message is displayed after reaching this point:
Traceback (most recent call last): File "<string>", line 106, in
<module> NameError: name 'leader' is not defined
if sad == 1:
if fear == 0 and leader == 1 and known == 1:
print("Congrats, you are the 'Foolish Leader'1/13")
elif fear == 1 and leader == 1 and known == 0:
print("Congrats, you are the 'Smart, yet scared Leader'2/13")
elif fear == 0 and leader == 1 and known == 0:
print("Congrats, you are the 'Smart Leader'3/13")
elif fear == 1 and leader == 0 and known == 1:
print("Congrats, you are the 'Scared Fool'4/13")
elif sad == 1 and coward == 1:
print("Congrats, you are the 'Sad Coward'5/13")
elif fear == 1 and coward == 1:
print("Congrats, you are the 'Scared Coward'6/13")
elif sad == -1:
if mind_changed == 1:
print("Congrats, you can't make up your mind.7/13")
elif mind_changed == 0:
print("Congrats, you can make up your mind.8/13")
elif insane == 1:
print("Congrats, you are a horrible person and I never want to see you again.9/13")
elif lazy == 1:
print("Congrats, you are lazy.10/13")
elif suic == True:
print("I hope that you're ok.11/13")
elif envy == 1:
print("Congrats, you're a good person.12/13")
elif fear == 1:
print("Congrats, you're scared easily.13/13")
if suic == True:
print("I hope you're ok.... Due to you choosing 'C' on the Multiple Choice, I suggest you stop playing.?/13")
I was expecting to get achievements and such.
The error you posted Traceback (most recent call last): File "<string>", line 106, in <module> NameError: name 'leader' is not defined tells you that on line 106 your program tries to access the variable 'leader' without it being defined first.
Are you defining this variable before you use it (e.g. leader = 0)? Maybe you're defining it in an if-statement which might not always execute?
So i'm trying to do a turtle controller program in Python but a message appears saying:
Traceback (most recent call last):
File "C:\Users\Sony\Desktop\PythonCode\TurtleController.py", line 35, in <module>
string_artist(t_program)
NameError: name 'string_artist' is not defined
I've tried removing the string_artist and the problem didn't occur anymore. However without string_artist the turtle controller doesn't work anymore.
from turtle import *
def turtle_controller(do, val):
do = do.upper()
if do == 'F':
forward(val)
elif do == 'B':
backward(val)
elif do == 'R':
right(val)
elif do == 'L':
left(val)
elif do == 'U':
penup()
elif do == 'D':
pendown()
elif do == 'N':
reset()
else:
print('unrecognized command')
instructions = '''Enter a program for the turtle:
example F100
N = New drawing
U/D = Pen Up/Down
F100 = Forward 100 (you can choose another number if you want)
B50 = Backwards 50
R90 = Right 90 deg
L45 = Left 45 deg'''
screen = getscreen()
while True:
t_program = screen.textinput('Deseneaza in Python!', instructions)
print(t_program)
if t_program == None or t_program.upper() == 'END':
break
string_artist(t_program)
I'm writing a modified Yahtzee game in Python 3 called '5 Dice' where the user only wins if they roll a 3, 4, or 5 of a kind. I am using a list for the dice roll but I am having trouble comparing the random list values and now it doesn't even want to work. Please help!
import time
import os
import random
number_of_dice = 5
rolls = []
def dice_roll():
os.system("clear")
print("Welcome to 5 Dice!")
raw_input("Press ENTER to roll")
for q in range(number_of_dice):
rolls.append(random.int(1,6))
rolls.sort()
time.sleep(1)
print(*rolls)
if rolls[0] == rolls[2]:
print("You rolled a three of a kind!")
try_again()
if rolls[0] == rolls[3]:
print("You rolled a four of a kind!")
try_again()
if rolls[0] == rolls[4]:
print("You rolled a five of a kind!")
try_again()
def try_again():
choice = input("Would you like to play again? Y/N: ")
if choice == "Y" or choice == "y":
dice_roll()
if choice == "N" or choice == "n":
quit()
else:
print("Please type Y or N")
I can currently see two problems with your code:
1.
Firstly, your code is indented at the beginning for some reason. This results in an indentation error, which could be why your program is not even working. If you move all the code at the start backwards, it should work.
2.
When you are comparing the dice, you say: if rolls[0] == rolls[2]. This doesn't mean three are the same, because you are only comparing two of the dice! It should be more like: if rolls[0] == rolls[1] == rolls[2]. If you change this, your game should work.
I hope this helps.
I'm practicing conditionals and logical operators.
How do I make the following rock, paper, scissors game print "This is not a valid object selection." immediately after Player 1's input, if Player 1 enters an invalid object? Right now the string is not printed until both players have entered an object.
Also, any suggestions for making the following code more elegant?
player1 = input('Player 1? ')
player2 = input('Player 2? ')
if (player1.lower() == 'rock' and
player2.lower() == 'rock'):
print('Tie.')
elif (player1.lower() == 'rock' and
player2.lower() == 'paper'):
print('Player 2 wins.')
elif (player1.lower() == 'rock' and
player2.lower() == 'scissors'):
print('Player 1 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'paper'):
print('Tie.')
elif (player1.lower() == 'paper' and
player2.lower() == 'scissors'):
print('Player 2 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'rock'):
print('Player 1 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'scissors'):
print('Tie.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'rock'):
print('Player 2 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'paper'):
print('Player 1 wins.')
else:
print('This is not a valid object selection.')
How about a function to ask each player their choice? Only if the player enters a valid selection will they be allowed to proceed through the code to your logic statements.
def get_choice(Player_number):
print('Player', Player_number, 'please enter your choice: ', end='')
while True:
choice = input().lower() #lower converts input to all lowercase
if choice in ('rock', 'paper', 'scissors'): # check if valid choice
return choice # if valid return choice
else:
print('Incorrect choice, try again: ', end='') # else print this and start loop agan
player1 = get_choice('1')
player2 = get_choice('2')
For the logic part, note that if player1 choice == player 2 choice, this will substitute 3 elif blocks in your code, ie.
if player1 == player2:
print('tie')
Now replaces pl==rock and p2 == rock, p1 == scissors and p2 == scissors, ect.
edit:
1) The problem if you move the print statement in 2 to inside the input in 4 is you can no longer specify the ,end='' parameter, as it does not work with input. As you said it will generate SyntaxError. The code looks much cleaner when run this way in terminal as it all lines up, but do test it for yourself.
2) end='' prints an empty string at the end of the print statement. you are confusing this with end='\n' which prints a new line after print. As my way keeps the cursor on the same line after the print, it lines up with the input to make it look nice, see above question. Note the print statement in python by default passes , end='\n'. This is why
print('hello') #same as print('hello', end='\n')
print('world)
hello
world
print('hello', end='')
print('world', end='')
helloworld
3) The while True loop will alway evaluate to true. So the body of the while loop will constantly cycle - However, it can return out of the entire function with the 'return choice' function. The only way to leave this function if to get down the logical steps required to reach the return statement. In this case unless the choice is in that tuple('rock', 'paper', 'scisors') it will just print invalid entry try again, finishing the block. However, As while is still true the loop will begin again and ask the user to input again. This will repeat until a valid choice is selected.
4) You could concatenate it onto the player_number eg..
print('Player', Player_number + ',' , 'please enter your choice: ', end='')
I am using Python and I am trying to write a simple program that simulates a rock, paper, scissors game. Everything works except for when I enter an invalid response (something other than rock, paper, or scissors) when I get this error.
Traceback (most recent call last):
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 88, in <module>
main()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 14, in main
number = user_guess()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 48, in user_guess
return number
UnboundLocalError: local variable 'number' referenced before assignment
I understand that this is telling me that number isn't referenced, but from what I understand of the code, it shouldn't need a number when the qualifier is false.
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
#get the user's guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
user_guess()
def is_valid_guess(guess):
if guess == 'rock' or 'paper' or 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Thank you for your help!
Here's your problem:
if guess == 'rock' or 'paper' or 'scissors':
This line in is_valid_guess doesn't do what you think it does. Instead, it always returns True. What you're looking for is something like this:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
or more concisely:
if guess in ('rock', 'paper', 'scissors'):
The problem is that what you have always returns True because of how Python evaluates strings in a boolean context. The line if guess == 'rock' or 'paper' or 'scissors': evaluates as:
if (guess == 'rock') or ('paper') or ('scissors'):
What this means is that Python checks to see if guess == 'rock'. If that's true, the conditional evaluates to True. If it's false, the interpreter tries to evaluate bool('paper'). This always evaluates to True because all non-empty strings are "truthy". Therefore, your whole conditional is always True, and every string is "valid".
As a result, your code considers all strings "valid" and then blows up when it fails to assign a number to a guess that is not actually supported.
As a final note, your is_valid_guess method could be trimmed a bit, since you're just returning the result of your boolean expression. Rather than using the status variable as an intermediate, you can just compute the expression and return it right away. I also use the lower() method of string objects to allow for case-insensitive guessing, in case that's something you want to allow.
def is_valid_guess(guess):
return guess.lower() in ('rock', 'paper', 'scissors')
You've got another issue, which you mentioned in the comments: you've implemented user_guess in a recursive fashion, so that it calls itself if the user enters an invalid guess. However, in this case, it does not return the result of the recursive call. You need to either return the recursive result by changing the last line of user_guess to:
return user_guess()
Or else you should make that function use a loop instead of recursion, which is what I would do, since the function is not inherently recursive. You can do something like this:
def user_guess():
# get first guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# If that guess is invalid, loop until we get a valid guess.
while not is_valid_guess(guess):
print('That response is invalid.')
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# Now assign the (valid!) guess a number
# This dictionary is just shorthand for your if/elif chain.
guess_table = {
'rock' : 1,
'paper' : 2,
'scissors' : 3
}
# Return the number associated with the guess.
return guess_table[guess.lower()]
Change
if guess == 'rock' or 'paper' or 'scissors':
to
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
In fact, to make the function as streamlined as possible, just do this:
def is_valid_guess(guess):
return guess == 'rock' or guess == 'paper' or guess == 'scissors'
As other users have pointed out, you need to change your validation in is_valid_guess to:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
While this won't solve your immediate problem, it is good (upvote-worthy) advice, and will let you avoid some errors you would have run into.
Additionally, no matter what the user inputs, you always return what they type in. To prevent this, you must return user_guess() in your else block:
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess() # <-- right here
Just change input to raw_input