Firstly, I am new to python and gpiozero, so please forgive me. I am trying to modify the GPIO music box tutorial. The project has 7 buttons that I want to both trigger a sound and run a script to check the sequence of button presses. Once the correct sequence is achieved I then want it to play another sound file. Here is the code I have so far:
from gpiozero import Button
import time
song = ""
pygame.mixer.init()
pygame.init()
amaj = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/amaj.mp3")
bmaj = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/bmaj.mp3")
cshrpmin = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/cshrpmin.mp3")
dshrpdim = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/dshrpdim.mp3")
emaj = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/emaj.mp3")
fshrpmin = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/fshrpmin.mp3")
gshrpmin = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/gshrpmin.mp3")
successfulsong = pygame.mixer.Sound("/home/pi/gpio-music-box/samples/4chordsongshort.mp3")
a_button = Button(2)
b_button = Button(3)
c_button = Button(4)
d_button = Button(17)
e_button = Button(27)
f_button = Button(22)
g_button = Button(10)
## Assuming these would call a function to play the sound and check sequence.
a_button.when_pressed = amaj.play
b_button.when_pressed = bmaj.play
c_button.when_pressed = cshrpmin.play
d_button.when_pressed = dshrpdim.play
e_button.when_pressed = emaj.play
f_button.when_pressed = fshrpmin.play
g_button.when_pressed = gshrpmin.play
while True:
while len(song) < 4:
chord = input() # Used as placeholder for button press
chord = str(chord)
if (not song) and chord == "E":
song = (chord)
elif song == "E" and chord == "B":
song = (song+chord)
elif song == "EB" and chord == "C":
song = (song+chord)
elif song == "EBC" and chord == "A":
song = (song+chord)
else:
song = ""
print("You created the 4 chord song!")
successfulsong.play
time.sleep(5)
song = ""
I know that is clunky and there should be better ways to do much of this, but I can't for the life of me figure out how to accomplish the "while len(song)..." of the "if/elif/else" portions using a function and trying to add the button press as the variable. I'm really sorry if this is super vague. Any help is appreciated!
I have created a game called Tic Tac Toe. There are 2 players one of them are Xs one of them are Os all you have to do is get your symbol 3 in a row without the other person blocking you.
The Gui for the game looks like this:
Code:
from guizero import App, TextBox, PushButton, Text, info
empty = ' '
player = "X"
def clicked(z):
button = buttonlist[int(z)] # Finds out which button was pressed
global empty, player
if button.text != empty:
pass # If button already pushed do nothing
else:
# Marks button with user's go
button.text = player
# Switches players
if player == "X":
player = "O"
else:
player = "X"
return
def instructions():
info("Instructions","There are 2 players one of them are Xs one of them are Os. All you have to do is you have to try getting your symbol 3 times in a row without the other player blocking you")
def quit_game():
app.destroy()
app = App(title="Tic Tac Toe", layout="grid", width=200, height=250)
buttonlist = [] # Empty list to contain a list of Buttons
Player1_label = Text(app, text="Player 1", align="top", grid=[0, 0, 2 , 1])
Player1 = TextBox(app, text=empty, align="top", grid=[2, 0, 3, 1])# Player 1 enters the username
Player2_label = Text(app, text="Player 2", align="top", grid=[0, 1, 2 , 1])
Player2 = TextBox(app, text=empty, align="top", grid=[2, 1, 3, 1])# Player 2 enters the username
Instructions = PushButton(app, command=instructions, text="Instructions", grid=[0, 5, 3, 1])# Display the instructions
Quit = PushButton(app, command=quit_game ,text="Quit",grid=[10, 0, 3, 2])
# Create Buttons for game, in 3 rows of 3
z=0
for x in range(3):
for y in range(2, 5):
buttonlist.append(PushButton(app, text=empty, args=str(z), grid=[x, y], command=clicked))
z+=1
app.display()
The problem I have is in displaying who is the winner. I know how to make a window appear to show the winner and the line that does this is:
app.info("Tic Tac Toe Winner","The winner is" + Player1.value)
But the problem that i am having is knowing who is the winner at the end of the game so and displaying that they are the winner also I have a feeling that to find out the winner its got something to do with buttonlist list that i made but i just cannot figure out how to do it so I would appriciate if some one could help me.
Thanks
Nice game. To work with the game board, I would suggest to create an internal data representation rather than working with the gui elements all the time according to common practice.
The reason is, that if you work with the gui elements everywhere, it might be slower, as it is not the ideal data representation. You could not save the data with pickle etc and you also add a strong dependency to the gui framework you use.
E.g. if you later plan to convert it to a web application etc. you will have a very hard time.
So I just created a simple data representation in which I store the field in a two dimensional array.
# check_win checks if there are three markings
# in one row/column or diagonally
def check_win():
# the checks array is just a trick to
# reduce the amount of code,
# you could avoid it by just adding
# one nested loop where the outer iterates
# over y and the inner over x
# one with the outer on x and the inner on y
# and then two others with just one loop
# for the diagonals
# the body of the inner loops would
# esentially look the same as for the while
# loop below
checks= [(0, 0, 1, 1), (0, 2, 1, -1)]
for i in range(3):
checks.append((i, 0, 0, 1))
checks.append((0, i, 1, 0))
won= None
for y, x, incr_y, incr_x in checks:
player= field[y][x]
found= player is not None
while found and x < 3 and y < 3:
found= (player == field[y][x])
y+= incr_y
x+= incr_x
if found:
won= player
break
return won
# I also changed your clicked method a bit, so
# it calles the check_win method
# and also changed the signature, so
# it gets the y and x coordinate of the
# button which makes maintaining the
# field array inside the clicked method
# a bit simpler and also seems more natural
# to me
def clicked(y, x):
button = buttonlist[y][x] # Finds out which button was pressed
global empty, player
if button.text != empty:
pass # If button already pushed do nothing
else:
# Marks button with user's go
button.text = player
field[y][x] = player
# Switches players
if player == "X":
player = "O"
else:
player = "X"
won= check_win()
if won is not None:
print(f'Player {won} has won the game')
return
# now I initialize the field array
# it will contain None for an untouched
# cell and X/O if taken by the corresponding
# user
field= [[None] * 3 for i in range(3)]
buttonlist= list()
# to get the buttons to call the
# clicked function with the new
# signature and also maintain the
# buttons in a two dimensional array
# I changed the order of your loops
# and the args argument
for y in range(0, 3):
rowlist= list()
buttonlist.append(rowlist)
for x in range(3):
rowlist.append(PushButton(app, text=empty, args=(y, x), grid=[x, y+2], command=clicked))
z+=1
app.display()
# a plain vanilla version of check_win would look something like:
def check_win():
for start in range(3):
x= start
mark= field[0][x]
for y in range(1, 3):
if field[y][x] != mark:
# the sequence is not complete
mark= None
if mark is not None:
# player who set the mark won
return mark
y= start
mark= field[y][0]
for x in range(1, 3):
if field[y][x] != mark:
# the sequence is not complete
mark= None
if mark is not None:
# player who set the mark won
return mark
mark= field[0][0]
for x in range(1, 3):
if field[y][x] != mark:
# the sequence is not complete
mark= None
if mark is not None:
# player who set the mark won
return mark
mark= field[0][3]
for x in range(1, 3):
if field[y][2-x] != mark:
# the sequence is not complete
mark= None
if mark is not None:
# player who set the mark won
return mark
return None
I am currently making a burglar alarm for a school project. I am trying to make a button that will disable the alarm when pressed. I originally thought to have a variable change when the button shim is pressed but, while the rest of the activities in the if loop happen, the variable is not being changed.
My code looks like this:
while (check1 == 0):
if (bE == 0): #if button E has not been pressed
if (check() = 1): # a function that returns if there is moton
check1 = 1
#buttonshim.on_press(buttonshim.BUTTON_E)
def button_e(button, pressed):
buttonshim.set_pixel(0xff, 0x00, 0x00) #changes led to red no prob
bE = 1 #supposed to change variable to 1 not working
print "button e pressed" #prints out fine
time.sleep(sleeptime) #so it's not checking constantly
else:
check1=1 #so it breaks out of while loop is E is pressed
I had already defined check1 and bE as variables before this code segment.
This is not working properly and I was wondering if there is any way that I can detect if the led is red so I can make an if statement and set the variable through that?
The syntax error in your first line might be the issue. Same with your if .statements
while (check1 = 0): #should be while (check1 == 0):
# rest of the code
So in my tkinter python program I am calling on a command when a button is clicked. When that happens it runs a function but in the function I have it set a label to something on the first time the button is clicked and after that it should only update the said label. Basically after the attempt it changes the attempt to 1 ensuring the if statement will see that and not allow it to pass. However it keeps resetting and I don't know how to stop it. When you click the button no matter first or third the button resets and proof of that occurs because the h gets printed. It's as if the function restarts but it shouldn't since it's a loop for the GUI.
def fight(): #Sees which one is stronger if user is stronger he gets win if no he gets loss also displays enemy stats and removes used characters after round is finished
try:
attempt=0
namel = ""
namer=""
left = lbox.curselection()[0]
right = rbox.curselection()[0]
totalleft = 0
totalright = 0
if left == 0:
namel = "Rash"
totalleft = Rash.total
elif left==1:
namel = "Untss"
totalleft = Untss.total
elif left==2:
namel = "Illora"
totalleft = 60+35+80
if right == 0:
namer = "Zys"
totalright = Zys.total
elif right==1:
namer = "Eentha"
totalright = Eentha.total
elif right==2:
namer = "Dant"
totalright = Dant.total
lbox.delete(lbox.curselection()[0])
rbox.delete(rbox.curselection()[0])
print(namel)
print(namer)
if attempt == 0:
wins.set("Wins")
loss.set("Loss")
print("h")
attempt=1
if (totalleft>totalright):
wins.set(wins.get()+"\n"+namel)
loss.set(loss.get()+"\n"+namer)
else:
wins.set(wins.get()+"\n"+namer)
loss.set(loss.get()+"\n"+namel)
except IndexError:
pass
Also for those of you who saw my previous question I still need help with that I just also want to fix this bug too.
At beginning of function fight you set attempt = 0 so you reset it.
Besides attempt is local variable. It is created when you execute function fight and it is deleted when you leave function fight. You have to use global variable (or global IntVar)
attempt = 0
def fight():
global attempt
BTW: of you use only values 0/1 in attempt then you can use True/False.
attempt = False
def fight():
global attempt
...
if not attempt:
attempt = True
The following code is a python sprinting game. It was posted as an answer to my previous post, by #mango You have to tap 'a' and 'd' as fast as you can to run 100 meters. However, there are a few bugs...
1) If you hold down 'a' and 'd' at the same time, the game is completed as fast as possible and defeats the point of the game.
2) Like in my previous post, I would like to incorporate a scoring system into this code, however, due to my level of skill and experience with python, unfortunately, I am unable to do so, and would appreciate and suggestions.
Many Thanks
Previous code:
import msvcrt
import time
high_score = 50
name = "no-one"
while True:
distance = int(0)
print("\n--------------------------------------------------------------")
print('\n\nWelcome to the 100m sprint, tap a and d rapidly to move!')
print('* = 10m')
print("\n**Current record: " + str(high_score) + "s, by: " + name)
print('\nPress enter to start')
input()
print('Ready...')
time.sleep(1)
print('GO!')
start_time = time.time()
while distance < 100:
k1 = msvcrt.getch().decode('ASCII')
if k1 == 'a':
k2 = msvcrt.getch().decode('ASCII')
if k2 == 'd':
distance += 1
if distance == 50:
print("* You're halfway there!")
elif distance % 10 == 0:
print('*')
fin_time = time.time() - start_time
fin_time = round(fin_time,2)
print('Well done you did it in...'+str(fin_time))
if fin_time < high_score:
print("Well done you've got a new high score ")
name = input("Please enter your name : ")
This is the code that I recieved as feedback, I have made a few changes, but I am struggling witht the bugs that I listed before.
1) If you hold down 'a' and 'd' at the same time, the game is completed as fast as possible and defeats the point of the game.
2) Like in my previous post, I would like to incorporate a scoring system into this code, however, due to my level of skill and experience with python, unfortunately, I am unable to do so, and would appreciate and suggestions.
Many Thanks
# these are the modules we'll need
import sys
import tkinter as tk
class SprintGame(object):
# this represents the distance we'll allow our player to run
# NOTE: the distance is in meters
distance = 100
# this represents the stride length of the players legs
# NOTE: basically how far the player can travel in one footstep
stride = 1.5
# this represents the last key the user has pressed
lastKey = ""
# this represents wether or not the race has been completed
completed = False
# this function initiates as soon as the "sprint" variable is defined
def __init__(self):
# create the tk window
self.root = tk.Tk()
# set the tk window size
self.root.geometry('600x400')
# set the tk window title
self.root.title("Sprinting Game")
# bind the keypress event to the self.keypress handler
self.root.bind('<KeyPress>', self.keypress)
# center the window
self.centerWindow(self.root)
# insert the components
self.insertComponents()
# initial distance notice
self.output("{0}m left to go!".format(self.distance))
# start out wonderful game
self.start()
# this function centers the window
def centerWindow(self, window):
window.update_idletasks()
# get the screen width
width = window.winfo_screenwidth()
# get the screen height
height = window.winfo_screenheight()
# get the screen size
size = tuple(int(_) for _ in window.geometry().split('+') [0].split('x'))
# get the screen's dimensions
x = (width / 2) - (size[0] / 2)
y = (height / 2) - (size[1] / 2)
# set the geometry
window.geometry("%dx%d+%d+%d" % (size + (x, y)))
# this function replaces the old text in the textbox with new text
def output(self, text = ""):
self.text.delete('1.0', tk.END)
self.text.insert("end", text)
# this function handles key presses inside the tkinter window
def keypress(self, event):
# get the key and pass it over to self.logic
self.logic(event.char)
# this function handles game logic
def logic(self, key):
# convert key to a lower case string
key = str(key).lower()
# let us know how far we've got left
if key == "l":
self.output("{0}m left to go!".format(self.distance))
# restart the race
if key == "r":
# clear the output box
self.text.delete('1.0', tk.END)
# reset the distance
self.distance = 100
# reset the stride
self.stride = 1.5
# reset the last key
self.lastKey = ""
# set race completed to false
self.completed = False
# output restart notice
self.output("The Race Has Been Restarted.")
# don't bother with logic if race is completed
if self.completed == True:
return False
# check if distance is less than or equal to zero (meaning the race is over)
if self.distance <= 0:
# set the "self.completed" variable to True
self.completed = True
# let us know we've completed the race
self.output("Well done, you've completed the race!")
# return true to stop the rest of the logic
return True
# convert the key to lower case
key = key.lower()
# this is the quit function
if key == "q":
# lights out...
sys.exit(0)
# check if the key is a
if key == "a":
# set the last key to a so that we can decrement the "distance"
# variable if it is pressed next
self.lastKey = "a"
# only bother with "d" keypresses if the last key was "a"
if self.lastKey == "a":
# capture the "d" keypress
if key == "d":
# decrement the "distance" variable
self.distance -= self.stride
# let us know how far into the game we are
self.output("{0}m left to go!".format(self.distance))
# this function inserts the components into the window
def insertComponents(self):
# this component contains all of our output
self.text = tk.Text(self.root, background='#d6d167', foreground='#222222', font=('Comic Sans MS', 12))
# lets insert out text component
self.text.pack()
# this function opens the window and starts the game
def start(self):
self.root.mainloop()
# create a new instance of the game
Game = SprintGame()