Hello, I am new to MicroPython and therefore this is likely to be a stupid question that anyone should know the answer to, but when I run the following program on my MicroBit it says that there is a syntax error on the line 24-41. If it matters, this is a Rock Paper scissors game, and in lines 24-41 I am trying to makes it say wether you win, lose or tie.
Here is the code:
from microbit import *
import random
rpsbot = ["P2 : Rock", "P2 : Paper", "P2 : Scissors"]
rps = ["Rock", "Paper", "Scissors"]
display.scroll("A=Rock / B=Paper / A+B=Scissors")
while True:
sleep(2000)
if button_a.is_pressed() and button_b.is_pressed():
rps = "P1 : Scissors"
elif button_a.is_pressed():
rps = "P1 : Rock"
elif button_b.is_pressed():
rps = "P1 : Paper"
break
display.scroll(str(rps))
display.scroll(random.choice(rpsbot))
while True:
sleep(500)
if (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Win")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll ("Win")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Win")
Thanks in advance,
String Error on And command!
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: String Error on And command!
You need to save the random choice:
Then your comparisons should look like this:
The [5:] syntax strips out the "Px : " part of the string to leave just "Rock", "Paper" or "Scissors"
Your lineis doing nothing because you redefine rps later.
The correct way to compare strings is with the "==" operator. The "is" operator serves a different purpose and won't work in this context.
There is a lot that could be done to simplify this code but perhaps the first thing for you is to get it to run
Incidentally I don't have a Microbit so my suggestions are untested.
Code: Select all
sel = random.choice(rpsbot)
display.scroll(sel)
Code: Select all
if sel[5:] == rps[5:]:
Your line
Code: Select all
rps = ["Rock", "Paper", "Scissors"]
The correct way to compare strings is with the "==" operator. The "is" operator serves a different purpose and won't work in this context.
There is a lot that could be done to simplify this code but perhaps the first thing for you is to get it to run
Incidentally I don't have a Microbit so my suggestions are untested.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.