Why isn't my if statement working? (graphics.py related) - python

I'm creating a mini program & I'm trying to check whether the user inputs what I want them to -- They're only supposed to type one of the following: happy, sad, angry,nervous,excited but for some reason its ignoring that entire if statement and even the table (rectangle) I drew doesn't appear as well?
from graphics import *
win = GraphWin("Moods", 800, 500)
#Creating the input Box + A Go Button.
inputBox=Entry(Point(400,250),12)
inputBox.draw(win)
colour=inputBox.getText().lower()
message=Text(Point(400,50),"Click to go next!")
message.setFace('courier')
message.setSize(20)
message.draw(Win)
submsg1=Text(Point(400,100),"")
submsg1.setText("(Allowed moods are: Happy, Sad, Angry, Nervous,
Excited)")
submsg1.setFace('courier')
submsg1.setSize(15)
submsg1.setStyle('italic')
submsg1.draw(win)
clickPoint = win.getMouse()
#Checking user inputs the right way.
if not colour.isalpha():
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
elif (colour !="happy" or colour !="sad" or colour !="angry"):
error=Text(Point(400,300),"Please type either: happy, sad, angry")
error.draw(win)
else:
#Clearing Second Frame, for next screen.
inputBox.undraw()
goButton.undraw()
error.undraw()
message.undraw()
submsg1.undraw()
#Moving to next frame.
table=Rectangle(Point(50,400),Point(750,400))
table.setFill("blue")
table.draw(win)

Basically what is happening with your code is that this line here;
elif (colour !="happy" or colour !="sad" or colour !="angry"):
this will execute if one of the conditions is true because of how the or works. because one of them will always be true (because the user cannot enter happy and sad at the same time).
so for your example you will want the and function as then all of the conditions will have to be true for it to run.
elif (colour !="happy" and colour !="sad" and colour !="angry"):
now to finish off you need to move this line colour=inputBox.getText().lower() to below this line clickPoint = win.getMouse() but before the if because getText is an event which executes when you call it, so at the moment when you call it at beginning it gets nothing because the user hasnt entered anything yet.
so it should look like this;
clickPoint = win.getMouse()
colour=inputBox.getText().lower()
#Checking user inputs the right way.
if not colour.isalpha():

Instead of
elif (colour !="happy" or colour !="sad" or colour !="angry"):
use
elif (colour !="happy" and colour !="sad" and colour !="angry"):
(and instead of or) as your original condition is always satisfied.

Related

How to loop with button input, cycle between different options in python?

I have a loop that takes a three way switch input and selects an option on power up of a camera:
# Set GPIO input
switchColorOne = pyb.Pin("P9", pyb.Pin.IN, pyb.Pin.PULL_UP)
switchColorTwo = pyb.Pin("P7", pyb.Pin.IN, pyb.Pin.PULL_UP)
#Set color pallete by switch
if switchColorOne.value() == 0:
sensor.set_pixformat(sensor.RGB565)
elif switchColorTwo.value() == 0:
sensor.set_pixformat(sensor.GRAYSCALE)
else:
sensor.set_color_palette(sensor.PALETTE_IRONBOW)
sensor.set_pixformat(sensor.RGB565)
I would like to take the input from a single push button to cycle through the three options during the switch, preferably with a while loop so it can happen continually. I can't figure out how to make this happen, do I need a debouncer, can I use a for loop to iterate through different lines of code?
You said above was button is in off state,
You can try like this.
switchColorOne = pyb.Pin("P9", pyb.Pin.IN, pyb.Pin.PULL_DOWN)
switchColorTwo = pyb.Pin("P7", pyb.Pin.IN, pyb.Pin.PULL_DOWN)
#Set color pallete by switch
if switchColorOne.value() == 1:
sensor.set_pixformat(sensor.RGB565)
elif switchColorTwo.value() == 1:
sensor.set_pixformat(sensor.GRAYSCALE)
else:
sensor.set_color_palette(sensor.PALETTE_IRONBOW)
sensor.set_pixformat(sensor.RGB565)````
The problem is you are just creating arbitrary conditions and your program has no way to know to go back to them when you press a button. If you want to make this work in a non-blocking manner you should use interrupts
C1 = pyb.Pin("P9", pyb.Pin.IN, pyb.Pin.PULL_UP)
C2 = pyb.Pin("P7", pyb.Pin.IN, pyb.Pin.PULL_UP)
sensor.set_color_palette(sensor.PALETTE_IRONBOW)
sensor.set_pixformat(sensor.RGB565)
def update(pin):
globals C1, C2, sensor #you might not even need this line
if pin is C1: sensor.set_pixformat(sensor.RGB565)
elif pin is C2: sensor.set_pixformat(sensor.GRAYSCALE)
C1.irq(update, pyb.Pin.IRQ_FALLING)
C2.irq(update, pyb.Pin.IRQ_FALLING)
You may have to switch to IRQ_RISING or pull your pins down. This gets you in the ballpark, though.

can't figure out a loop with some conditions

I'm starting to learn programming and trying to write my first flash game bot, but I think I can't sort things out
This game is, player click in 5 areas randomly, if player is lucky, the enemy will get shot and reduce his hp. Enemy's hp is 6, and this game requires player to finish this in no more than 7 shots, which means player has only one chance to miss the guess.
So I "cut" the HP bar into 6 jugdement areas, and use PIL in python to judge the pixel's color change in every area, then let pyautogui to do some auto clicks. Main part of this code is:
while True:
flag = 1
for i in range(6):
s = screenGrab()
pixels = s.load()
pixelJugde_1 = pixels[judgeAreas[i]] # jugde if hp is reduced after this shot
if pixelJugde_1 != (0, 0, 0): # if this shot missed
randomClick() # try again
s = screenGrab()
pixels = s.load()
pixelJugde_2 = pixels[judgeAreas[i]] # second judge of this shot
if (pixelJugde_2 != pixelJugde_1): # hp changed, second try didn't miss
flag = 1 # mark this shot has been tried twice
randomClick() # continue next shot
elif (pixelJugde_2 == pixelJugde_1 and flag == 1): # second try missed
resetResult() # restart the game
break
else:
print 'got shot' # success at first try
randomClick() # next shot
now my problem is, if the first shot has been tried twice and marked, when the next shot begins and misses, it will still try twice, just like the marking flag is not working. So how to fix this?

Modifying a dictionary inside of an if statement

I've been trying to make a basic text game in Python, and I'm using dictionaries to contain the player's information. I want to make it so that when a player's health reaches 0, the code will stop running. I've had trouble making that happen. My dictionary, which is at the beginning of my code, looks like this:
playerAtt = {}
playerAtt["Weapon"] = "Baseball bat"
playerAtt["Party"] = "Empty"
playerAtt["Health"] = 15
playerAtt["Cash"] = "$100"
print(playerAtt)
if playerAtt['Health'] <= 0:
exit()
The bottom section is what I wrote to try and make the code stop running when the player's health reached zero, but it doesn't seem to work. In one path of my game, your health gets set to zero and the game is supposed to end, but the program continues to run:
townChoice = raw_input("You met a traveler in the town. 'Yo. I'm Bob. Let's be friends.' Will you invite him to your party? Y/N\n")
if townChoice == 'y' or townChoice == 'Y':
print("That kind traveler was not such a kind traveler. He stabbed you with a machete. RIP " + Name + '.')
playerAtt['Health'] == 0
When you reach this part of the game, all it does is print the message, and moves on to the next decision. In this situation, I could just manually end the program by doing exit() under the print command, but there are circumstances where the player only loses a fraction of their health, and they would eventually reach zero. Sorry if this is a stupid question, I've only been working on Python for a few days.
You have two "=" when you set the player's health to 0
I had put 2 == instead of 1 = when defining
playerAtt["Health"].
Also, I needed to make sure it was constantly checking if the player's health was zero, so I used a while loop. I used
while playerAtt["Health"] = 0:
deathmsg()
exit()
to fix it. deathMsg was a function I made to display a random death message, for more information.

Make text appear based on key press (give user real time feedback) in psychopy

I have a stimulus loop in psychopy that displays images for 4 seconds that subjects make binary decisions about. I would like to give them feedback as to which choice they have made.
I.e.: a image gets displayed for 4 seconds with white 'YES' and 'NO' displayed on either side of it. When the user presses a key, the corresponding word turns red. If they then press a different key, it switches. After 4 seconds, the next image appear with white words.
Does anyone know how to go about doing this? Many thanks for any suggestions.
You can do this with a custom code component. Add the code component to your routine.
Under the "Each Frame" tab add the following code:
if (t >=4) and (t < 8):
if clear_keys:
event.getKeys()
clear_keys = False
else:
theseKeys = event.getKeys(keyList=['y', 'n'])
if 'y' in theseKeys:
Yes.color = 'red'
No.color = 'white'
elif 'n' in theseKeys:
Yes.color = 'white'
No.color = 'red'
Under the "Begin Experiment" tab add the following code:
clear_keys = True
You will need to change the Yes and No objects in the script to the names of your text components. You will also need to change the number 4 to the start time of the picture and number 8 to the end time.
Here is a picture of my trial as an example.

Simple Graphics library not coloring lines

I'm a student learning to program, and my current assignment is to write a graphing calculator using the Simple Graphics library. I got everything working, except for coloring the lines. The first line should be red, the second should be green and the third one blue, then they repeat. Here is the code I added for the colors:
if count % 3 == 1:
print("red")
setColor = ("red")
elif count % 3 == 2:
print("green")
setColor = ("green")
else:
print("blue")
setColor = ("blue")
Earlier in the code, I set count = 1 and at the end of my drawing loop, I have count = count + 1.
Whenever I try to use the program, all the lines appear black. When I look at the terminal, I see "red", "green" and "blue" all being printed successfully at the right times. Using RGB values to define the color doesn't help either.
Does anyone have any idea of what I could be doing wrong? I can post the entire code for drawing the lines, but I thought people wouldn't want to sift through 30 lines.
setColor = ("color") should just be setColor("color"). setColor is a function, that takes in input and performs an action. If it was a variable, which is just a name for some data that you will provide, your code would be correct. (Variables almost never have verbs in their names.)

Categories

Resources