Skipping through all elifs to the end and activating the last statements - python

I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses "a" it changes the left facing gif of that shape using the giant el if wall. However, we ran unto an error where instead of executing the elif statements, it just skips to the last line and changes to the J shape no matter what shape was called in the random statement. Any help would be awesome, thank you! (We are still learning btw) also the rotate function is also supposed to happen when the user presses the "d" key but its supposed to change to the other direction.
import turtle as trtl
import random as rand
wn = trtl.Screen()
#configurations
tetris = trtl.Turtle()
drawer = trtl.Turtle()
background = trtl.Turtle()
starty = int(-400)
square = ("sqaure_block.gif")
s_block_normal = ("S_block_norm.gif")
s_block_standing = ("S_block_right.gif")
invert_s_block_normal = ("Z_block_norm.gif")
invert_s_block_standing = ("Z_block_right.gif")
l_block_normal = ("L_block_norm.gif")
l_block_180 = ("L_block_180.gif")
l_block_right = ("L_block_right.gif")
l_block_left = ("L_block_left.gif")
line_normal = ("line_block_norm.gif")
line_standing = ("line_block_standing.gif")
t_block_normal = ("T_block_norm.gif")
t_block_180 = ("T_block_180.gif")
t_block_right = ("T_BLOCK_RIGHT.gif")
t_block_left = ("T_block_left.gif")
j_block_normal = ("J_block_norm.gif")
j_block_180 = ("J_block_180.gif")
j_block_right = ("J_block_right.gif")
j_block_left = ("J_block_left.gif")
wn.addshape (square)
wn.addshape(s_block_normal)
wn.addshape(s_block_standing)
wn.addshape(invert_s_block_normal)
wn.addshape(invert_s_block_standing)
wn.addshape(l_block_normal)
wn.addshape(l_block_180)
wn.addshape(l_block_right)
wn.addshape(l_block_left)
wn.addshape(line_normal)
wn.addshape(line_standing)
wn.addshape(t_block_normal)
wn.addshape(t_block_180)
wn.addshape(t_block_right)
wn.addshape(t_block_left)
wn.addshape(j_block_normal)
wn.addshape(j_block_180)
wn.addshape(j_block_right)
wn.addshape(j_block_left)
Tshape = [square, s_block_normal, invert_s_block_normal, l_block_normal, line_normal, t_block_normal, j_block_normal]
squarecor = [-50, -25, -100, -50]
wn.bgcolor("lightblue")
background.speed("fastest")
background.hideturtle()
background.pu()
background.goto(-400,-200)
background.fillcolor("blue")
background.pencolor("blue")
background.begin_fill()
background.pd()
background.goto(400,-200)
background.goto(400,-350)
background.goto(-400,-350)
background.goto(-400,-200)
background.end_fill()
#sprite direction change
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
'''
def (fast_down):
global tetris
tetris.setheading(270)
tetris.forward(10)
'''
#turn right
def turn_right():
tetris.speed("fastest")
tetris.setheading(0)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#turn left
def turn_left():
tetris.speed("fastest")
tetris.setheading(180)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#down
#tetris container/backround
drawer.pensize(5)
drawer.speed("fastest")
drawer.penup()
drawer.goto(150, 200)
drawer.pendown()
drawer.setheading(270)
drawer.forward(400)
drawer.setheading(180)
drawer.forward(300)
drawer.setheading(90)
drawer.forward(400)
drawer.hideturtle()
#game WIP!!!!!!!!!!
y = 0
space = int(1)
tracer = True
def spawn_T():
new_T=rand.choice(Tshape)
tetris.shape(t_block_180)
tetris.pu()
tetris.goto(0, 200)
tetris.setheading(270)
tetris.forward(10)
'''
if ((abs(space - starty)) < 200):
tetris.forward(2)
else:
'''
tetris.stamp()
'''
space = space =+ 1
'''
tetris.hideturtle()
tetris.goto(0,200)
tetris.showturtle()
if (y == 0):
spawn_T()
#changeing the directions of the sprites
#events
wn.onkeypress(turn_right, "Right")
wn.onkeypress(turn_left, "Left")
wn.onkeypress(sprite_right, "a")
wn.onkeypress(sprite_left, "d")
'''
wn.onkeypress(fast_down, "s")
'''
wn.listen()
wn.mainloop()
Here is the google drive file https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link

I think the indentation is wrong here. Maybe try putting the last else-statement one tab further?

Please use elif instead of the else: if formulation to get away from the bewildering indentation - here's how it should look:
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
That said, because this is all the code you've provided, it's not possible to run it and examine why it's not working. Can you please provide an example of an implementation of these functions?

According to the documentation, shape() returns the current shape with no parameters, and sets it with one parameter. Therefore in:
if tetris.shape(s_block_normal):
shape(name) returns None, which is always False. So, if you change to:
if tetris.shape() == s_block_normal:
It should function as required.
Also, you can get rid of the if ladder completely by, for instance, something like:
next_left_shape = {s_block_normal: s_block_standing,
invert_s_block_normal: invert_s_block_standing,
... }
tetris.shape(next_left_shape[tetris.shape()])

Related

Trying to make a leveling system, however it only works once and then stops working?

I'm making a leveling system and it only levels me up once and then stops working. Once it levels me the xp doesn't reset and my level does not go up. Here's the code!
level = int(1)
crexp = int(260)
reqxp = int(100)
while crexp >= reqxp:
level = level+1
crexp = crexp-reqxp
reqxp = (reqxp/100)*120
continue
while 3 > 2:
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
The problem with your current code is that you are not rerunning the 'level up' part of the code. Python generally (when not in a while/for loop e.c.t) reads your code from top to bottom. This means by the time you get into the second while loop the first while loop has finished and will never be run again.
To fix this you want to tell python to recalculate the level and experience variables at certain points - the easiest way to do this is to make the first while loop into a function and call it at the start of the second while loop. You would get something like this -
def checkLevelUp(currentXp, requiredXp, currentLevel):
while currentXp >= requiredXp:
currentLevel = currentLevel+1
currentXp = currentXp-requiredXp
requiredXp = int(requiredXp * 1.2)
return currentLevel, currentXp, requiredXp
level = 1
crexp = 260
reqxp = 100
while True:
level, crexp, reqxp = checkLevelUp(crexp, reqxp, level)
pinput = input()
if pinput == "1":
crexp = crexp + 60
elif pinput == "2":
print(level)
elif pinput == "3":
print(crexp)
elif pinput == "4":
print(reqxp)
elif pinput == "5":
break
Note also the changes to calculating the next required xp - dividing by 100 and then multiplying by 120 is just the same as multiplying by 1.2.

Strange L-system in python turtle graphics

I tried to use the turtles module in Python 3 to recreate the fractal found here:
https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant
but whenever I try it it gives me a very strange result...
Here's my code:
import turtle
wn = turtle.Screen()
wn.bgcolor("white")
wn.screensize(10000, 10000)
tess = turtle.Turtle()
tess.color("lightgreen")
tess.pensize(1)
tess.speed(0)
tess.degrees()
inst = 'X'
steps = 3
for counter in range(steps):
_inst = ''
for chtr in inst:
if chtr == 'X':
_inst += 'F−[[X]+X]+F[+FX]−X'
elif chtr == 'F':
_inst += 'FF'
else:
_inst += chtr
inst = _inst
print(inst)
for chtr in inst:
if (chtr == 'F'):
tess.forward(25)
elif (chtr == '+'):
tess.right(25)
elif (chtr == '-'):
tess.left(25)
elif (chtr == '['):
angle = tess.heading()
pos = [tess.xcor(), tess.ycor()]
elif (chtr == ']'):
tess.setheading(angle)
tess.penup()
tess.goto(pos[0], pos[1])
tess.pendown()
wn.exitonclick()
I triple-checked everything and I seem to have no bugs - but it still does not work. What am I doing terribly wrong?
Thanks in advance for any help!
There are two issues in your code.
The first is that your code doesn't handle nested brackets properly. The inner opening bracket saves its state over the top of the previous state saved when the outer opening bracket was seen. This won't matter for immediately nested brackets like [[X]+X] (since both have the same starting state), but once you get more complicated nesting (as you will after a few substitution loops), the issue starts to make things go wrong.
To solve this you probably want to store your saved state values to a stack (a list can do). Push the values you want to save, and pop them back off when you're ready to restore them.
stack = [] # use a list for the stack
for chtr in inst:
if (chtr == 'F'):
tess.forward(25)
elif (chtr == '+'):
tess.right(25)
elif (chtr == '-'):
tess.left(25)
elif (chtr == '['):
angle = tess.heading()
pos = [tess.xcor(), tess.ycor()]
stack.append((angle, pos)) # push state to save
elif (chtr == ']'):
angle, pos = stack.pop() # pop state to restore
tess.setheading(angle)
tess.penup()
tess.goto(pos[0], pos[1])
tess.pendown()
The second issue is more trivial. Your parser looks for the "minus" character (-). But your pattern generating code uses a different, slightly longer kind of dash (−). Change one of them to match the other (it doesn't really matter which one) and your code will work as expected.
According to the Wikipedia page, the symbol '[' means to save the current state (angle and positions). The matching ']' means to restore the previously saved position. Because the '[' and ']' can be nested, a stack is needed.
from collections import deque
...
stack = deque()
for chtr in inst:
if (chtr == 'F'):
tess.forward(25)
elif (chtr == '+'):
tess.right(25)
elif (chtr == '-'):
tess.left(25)
elif (chtr == '['):
angle = tess.heading()
pos = [tess.xcor(), tess.ycor()]
stack.append((angle, pos)) ### New statement
elif (chtr == ']'):
angle, pos = stack.pop() ### New statement
tess.setheading(angle)
tess.penup()
tess.goto(pos[0], pos[1])
tess.pendown()
. . .

error making text based game spawn monster

I am making a text based game with my friend for a programming class, we are avoiding using object oriented stuff so please avoid those suggestions. to use the program I would normally do type "help" then I can go in any direction to move like "right", "left", "down" and "up" when I try to use those commands I get an error. this happend after I added the spawnMonster command part
#Connor and Griffin's text based adventure
import os
import random
############################
####---Variable setup---####
#########ADD COMMAND VARIATION############
#########ADD ITEM LISTS#################
commands = 1 #for debuging only please
maxHealth = 100 #Default begin health
health = 100 #Current health
mana = 0 #THERES NO MAGIC
mapS = [5, 5]
objects = {}
color = "0f"
output = "" #this is where whats happening is told to you
level = 1
canMove = 1
playerSym = "P"
# for activeQuests remember that if the value is 0 its not completed and if its 1 its completed
activeQuests = {"Journey To Riverwood": 0}
# Add new quest names above^
commandList = {"help", "legend", "color", "show inv", "quests", "console", "up", "left", "right", "down", "clear", "map"}
#Default inventory
inv = {"apple(s)":2, "shortsword":1, "gold":50,"cloth shirt":1,"pair of cloth pants":1,"pair of shoes":1}
clearedSpaces = []
##### "Name":baseDMG #####
monsters = {"Goblin":1, "Troll":3, "Bear":2, "Giant Spider": 1, "Bandit":1, "Goblin Chief":3}
###########################
###########################
##### Name:lv:monsterSpawnRate #####
zones = {"Forest":[1,90]}
#######################
#---Quest Log Stuff---#
def checkQuest():
for questn in activeQuests:
print("\n------", questn, "------")
if activeQuests[questn] == 0:
print("\nNot Complete")
else:
print("\nComplete")
######Description for quests######
if questn == "Journey To Riverwood":
print("""
Welcome to Connor and Griffins excellent adventure!
try out some of the commands like; help, quests,
color, inv or show inv. now using your new found
commands move to the city of riverwood.\n\n""")
#########################
#########################
############################
###---Scenes/Functions---###
def mapSize(x, y):
global mapS
mapS = [x, y]
####Ads point to map
def addObject(name, x, y, symbol):
objects[name] = [x, y, symbol]
legend[symbol] = name
#### Clears some variables
def roomStart():
global objects
objects = {}
global legend
legend = {"░":"Unknown area"}
global roomName
roomName = "BLANK"
def newArea():
for area in zones:
global spawnChance
spawnChance = zones[area][1]
def spawnMonster():
enemy, DMG = random.choice(monsters)
return enemy
def moveToNewSpace():
rand = random.randint(1,100)
if rand <= spawnChance:
global spawnedMonster
spawnMonster()
###Move player
def changePos(name, newx, newy):
objects[name][0] += newx
objects[name][1] += newy
global clearedSpaces
clearedSpaces.append([objects[name][0],objects[name][1]])
moveToNewSpace()
###First room
def roomBegin():
roomStart()
mapSize(15,10)
global roomName
roomName = "Forest"
newArea()
addObject("Riverwood",10,5,"R")
addObject("Griffin's House",2,2,"G")
addObject("Player",2,3,playerSym) #######Remember to make a "ChangePos" command to change the pos of the player when they move#######
clearedSpaces.append([2,3])
################### MAPPING HERE ##################
def makeMap():
print("\n------"+roomName+"------")
for y in range(mapS[1]):
line = ""
numy = y+1
for x in range(mapS[0]):
numx = x + 1
for place in objects:
if objects[place][:2] == [numx, numy]:
line += objects[place][2]
break
else:
if [numx, numy] in clearedSpaces:
line += " "
else:
line += "░"
print(line)
print("\n----Legend----\n")
for thing in legend:
print(thing + " - " + legend[thing])
############################
############################
#######################
###--- MAIN LOOP ---###
roomBegin()
while 1 == 1:
makeMap()
print("\n\n" + output + "\n\n")
print("\n\nHealth is at ",health,"/",maxHealth)
command = input("Enter action: ")
if command.lower() == "quests":
os.system("cls")
checkQuest()
elif command.lower() == "legend":
os.system("cls")
print("\n----Legend----\n")
for thing in legend:
print(thing + " - " + legend[thing])
elif command.lower() == "help":
os.system("cls")
print("\n\n------HelpMenu------\n")
for comd in commandList:
print(comd)
elif command.lower() == "color":
newc = input("new color: ")
os.system("color 0" + newc)
os.system("cls")
elif command.lower() == "show inv" or command.lower() == "inv" or command.lower() == "inventory":
os.system("cls")
print("\n------Inventory------\n")
for item in inv:
print(" ", inv[item]," ", item)
elif command.lower() == "console":
if commands == 1:
consolecmd = input("Enter a command: ")
os.system(consolecmd)
else:
print("Sorry, you dont have permition to use that command.")
elif command.lower() == "up":
if canMove == 1:
os.system("cls")
changePos("Player", 0,-1)
else:
os.system("cls")
output += "\nCant move that way right now!"
elif command.lower() == "down":
if canMove == 1:
os.system("cls")
changePos("Player", 0,1)
else:
os.system("cls")
output += "\nCant move that way right now!"
elif command.lower() == "left":
if canMove == 1:
os.system("cls")
changePos("Player", -1,0)
else:
os.system("cls")
output += "\nCant move that way right now!"
elif command.lower() == "right":
if canMove == 1:
os.system("cls")
output = "There are some trees here, and a small pond"
changePos("Player", 1,0)
else:
os.system("cls")
output += "\nCant move that way right now!"
elif command.lower() == "clear":
os.system("cls")
else:
os.system("cls")
print("Previous attempt was an invalid command, try again.")
#######END MAIN#######
######################
The random.choice function requires a sequence.
In a previous version of your code (or maybe it was code from a classmate of yours just having similar but not identical problems with similar code?), you had the monsters stored in a list, like [("Goblin", 1), ("Troll", 3), …]. For that code, random.choice works, because a list is a sequence.
But now you have a dict. And a dict is not a sequence.
You can get a list of all of the keys in a dict just by writing list(d). So, you could do this:
return random.choice(list(monsters))
But you're not actually getting any benefit from monsters being a dict from what I can tell, so why not just use a list in the first place?
monsters is a dictionary. It is being passed to random.choice(), however, random.choice() accepts a sequence as its argument (from which it randomly selects one element). This will not work for a dictionary and you will see a KeyError exception if you try.
Since you just want to return an enemy from spawnMonster() you can instead use the keys of monsters which is a list:
monsters = {"Goblin":1, "Troll":3, "Bear":2, "Giant Spider": 1, "Bandit":1, "Goblin Chief":3}
def spawnMonster():
return random.choice(monsters.keys())
Update
Since you are using Python 3 you can do this instead (also works in Python 2):
def spawnMonster():
return random.choice(tuple(monsters))

Monty Hall-Not Running

I'm not sure what seems to be the problem with my code, I need some help. When I try running my program, it says invalid syntax next to my first if, I thought I may be an indentation error but nothing is working.
Here is my code:
import random
def montyHall():
car = random.randint(1,3)
guess1 = random.randint(1,3)
for i in range(1,3):
if ((not(i == car) and not(i == guess1)):
return i
newGuess = not(i) and not(guess1)
if (newGuess == car):
stay = True
elif (guess1 == car):
switch = False
return strategyOne
NUM_OF_TRIALS = 1000
stay = 0
switch = 0
for i in range(NUM_OF_TRIALS):
if(montyHall()):
stay += 1
else:
switch += 1
print("Staying wins", stay/NUM_OF_TRIALS, "% of the time")
print("Switching wins", switch/NUM_OF_TRIALS, "% of the time")
To many brackets and you do not need brackets in python.
Try changing:
if ((not(i == car) and not(i == guess1)):
to
if i != car and i != guess1:

IndexError in unused conditional

def menurender():
global pos
global menulist
line1=menulist[pos]
if pos == len(menulist):
line2="back"
else:
line2=menulist[pos+1]
lcd.clear()
lcd.message(str(pos)+' ' +line1+ "\n"+str(pos+1)+' '+ line2)
In my block of code, I have a conditional in the menurender() function that checks to make sure that the list menulist has a valid index before referencing it, but i receive IndexError: list index out of range. I understand that the else statement is causing it, but I am confused because python shouldn't be executing it.
Full code
#!/usr/bin/python
#################################################
#IMPORTS#########################################
#################################################
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from Adafruit_I2C import Adafruit_I2C
#################################################
#OBJECTS#########################################
#################################################
lcd = Adafruit_CharLCDPlate()
#################################################
#VARIABLES#######################################
#################################################
#current button value
prevbutton = "NULL"
#for SELECT key and determining clicks
action = False
#variable for menu position
pos = 0
#on screen cursor 0 for top line, 1 for bottom line
cursor = 0
#Handles list structure and action when clicked
menulist= []
menulist.append("CPU")
menulist.append("RAM")
menulist.append("STORAGE")
menulist.append("NETWORK")
#get input from keys and return the currently pressed key
def buttonstatus():
bstatus = "Null"
if lcd.buttonPressed(lcd.SELECT) == True:
bstatus="SELECT"
elif lcd.buttonPressed(lcd.UP) == True:
bstatus="UP"
elif lcd.buttonPressed(lcd.DOWN) == True:
bstatus="DOWN"
elif lcd.buttonPressed(lcd.LEFT) == True:
bstatus="LEFT"
elif lcd.buttonPressed(lcd.RIGHT) == True:
bstatus="RIGHT"
return bstatus
#checks buttons pressed and converts that into action for top menu
def getinput():
global prevbutton
global pos
if buttonstatus() != prevbutton:
prevbutton = buttonstatus()
if buttonstatus() == "SELECT":
print "select"
elif buttonstatus() == "DOWN":
pos = pos + 1
elif buttonstatus() == "UP":
pos = pos -1
#elif buttonstatus() == "LEFT":
#print "left"
#elif buttonstatus() == "RIGHT":
#print "right"
#defines bounds for the position of the cursor
def posbounds():
global pos
global menulist
if pos < 0:
pos = 0
if pos == len(menulist):
pos = len(menulist)
#code renders the menu on the LCD
def menurender():
global pos
global menulist
line1=menulist[pos]
if pos == len(menulist):
line2="back"
else:
line2=menulist[pos+1]
lcd.clear()
lcd.message(str(pos)+' ' +line1+ "\n"+str(pos+1)+' '+ line2)
while True:
getinput()
posbounds()
menurender()
There are lots if values for pos != len(menulist) for which menulist[pos+1] gives an IndexError (including pos == len(menulist) - 1). You should check
if pos > (len(menulist) - 2):
You should probably change if pos == len(menulist): to if pos == len(menulist) - 1: if you want to check if pos is the index of the last element, or to if pos == len(menulist) - 2: if you want to check for the second to last element.
A better way of doing this may be by using a try ... except block.
try:
line2 = menulist[pos+1]
except IndexError:
# Out of range -> pos is greater than len(menulist)-1
line2 = 'back'
However - this doesn't seem lika a Pythonic way of doing anything at all in Python. Maybe you could tell us what you are trying to achieve, and someone here may propose a better way of doing it.

Categories

Resources