Heretic Curse
20-08-2013, 07:34
salve, stavo cercando di dividere il codice che sto scrivendo in più file, ma al momento senza successo :(
Sostanzialmente ho spostato tutte le funzioni in un file di nome basePPT, all'interno della classe basePPT. Poi, nel file contenente il codice in cui voglio utilizzare le funzioni, ho scritto
from basePPT import basePPT
Tuttavia non funzionano.
basePPT.py e il file in cui utilizzi la classe sono nella stessa directory?
Posta un po' di codice, il ragionamento è corretto ma c'è qualcosa di sbagliato nell'implementazione :D
Heretic Curse
20-08-2013, 10:31
Si sono nella stessa directory.
Questo è parte il codice che utilizza la classe:
import sys, pygame, random
from pygame.locals import *
from basePPT import basePPT
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, CHORD
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
FPSCLOCK = pygame.time.Clock()
BASICFONT = pygame.font.Font('freesansbold.ttf', 20)
pygame.display.set_caption('Perfect Pitch Trainer')
lastNote = None # to track the last played note
lesson_Button = pygame.Rect(30, 30, 30, 30) # to start the lesson mode
instructions_Button = pygame.Rect(30, 70, 30, 30) # to show the game instructions
voidStr_Button = pygame.Rect(30, 110, 30, 30) # to generate guitar void strings
mute_Button = pygame.Rect(30, 150, 30, 30) # to stop all the active sounds
while True: # main game loop
# set the display
DISPLAYSURF.fill(BGCOLOR)
generateFretBoard()
makeButton('Lessons', lesson_Button, DARKGREEN)
makeButton('Sound Stop', mute_Button, DARKGREEN)
makeButton('Guitar Void String', voidStr_Button, DARKGREEN)
makeButton('Instructions', instructions_Button, DARKGREEN)
showLastNotes(LASTNOTELIST)
checkForQuit()
for event in pygame.event.get():
# check if the player is doing a chord
if event.type == KEYDOWN:
if event.key == K_c:
CHORD = True
if event.type == KEYUP:
if event.key == K_c:
CHORD = False
# check what the mouse is clicking
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
for OCTAVE in OCTAVELIST:
checkPressedFret((mousex, mousey), OCTAVE)
for OCTAVE in sOCTAVELIST:
checkPressedFretS((mousex, mousey), OCTAVE)
mousePos((mousex, mousey))
FPSCLOCK.tick()
pygame.display.update()
Questa è parte della classe:
class basePPT:
def showLastNotes(lastNoteList):
toplefty = 190
for note in lastNoteList:
lastNoteText = BASICFONT.render(note, True, GOLD, BGCOLOR)
lastNoteRect = lastNoteText.get_rect()
lastNoteRect.topleft = (30, toplefty)
toplefty += 30
DISPLAYSURF.blit(lastNoteText, lastNoteRect)
def makeButton(text, Rect, color):
# used to generate the function's button
pygame.draw.rect(DISPLAYSURF, BLACK, Rect)
pygame.draw.rect(DISPLAYSURF, DARKGREEN, Rect, 1)
textSurf = BASICFONT.render(text, True, RED, BGCOLOR)
textRect = textSurf.get_rect()
textRect.topleft = Rect.topright
DISPLAYSURF.blit(textSurf, textRect)
def mousePos((mousex, mousey)):
# generate a red spot to show better what the mouse is clicking
pygame.draw.circle(DISPLAYSURF, RED, (mousex, mousey), 10)
pygame.display.update()
pygame.time.wait(100)
def lastNotePatcher(lastNote):
# patch the LASTNOTELIST, which contains the last 3 notes
global LASTNOTELIST, FIRSTCHORDNOTE
if CHORD == True:
if FIRSTCHORDNOTE == False:
LASTNOTELIST = [lastNote] + LASTNOTELIST
FIRSTCHORDNOTE = True
elif FIRSTCHORDNOTE == True:
LASTNOTELIST[0] += " " + lastNote
else:
LASTNOTELIST = [lastNote] + LASTNOTELIST
FIRSTCHORDNOTE = False
if len(LASTNOTELIST) == 4:
del LASTNOTELIST[3]
def generateFretBoard():
# generate the fretboard
drawWood()
generateWhiteFrets(WHITESTARTCOORDX, OCTAVE1)
generateWhiteFrets(WHITESTARTCOORDX + OCTAVELENGHT, OCTAVE2)
generateWhiteFrets(WHITESTARTCOORDX + (OCTAVELENGHT * 2), OCTAVE3)
generateWhiteFrets(WHITESTARTCOORDX + (OCTAVELENGHT * 3), OCTAVE4)
generateBlackFrets(BLACKSTARTCOORDX, OCTAVE1S)
generateBlackFrets(BLACKSTARTCOORDX + OCTAVELENGHT, OCTAVE2S)
generateBlackFrets(BLACKSTARTCOORDX + (OCTAVELENGHT * 2), OCTAVE3S)
generateBlackFrets(BLACKSTARTCOORDX + (OCTAVELENGHT * 3), OCTAVE4S)
def terminate():
pygame.quit()
sys.exit()
def drawWood():
pygame.draw.rect(DISPLAYSURF, BROWN, (WHITESTARTCOORDX, WINDOWHEIGHT - 180, OCTAVELENGHT * 4, 44))
pygame.draw.rect(DISPLAYSURF, FIREBRICK, (WHITESTARTCOORDX, WINDOWHEIGHT - 180, OCTAVELENGHT * 4, 45), 1)
def checkForQuit():
for event in pygame.event.get(QUIT): # get all the QUIT events
terminate() # terminate if any QUIT events are present
for event in pygame.event.get(KEYUP): # get all the KEYUP events
if event.key == K_ESCAPE:
terminate() # terminate if the KEYUP event was for the Esc key
pygame.event.post(event) # put the other KEYUP event objects back
def generateWhiteFrets(WHITESTARTCOORDX, OCTAVE):
for i in range(0,7):
fret = pygame.Rect(WHITESTARTCOORDX, WINDOWHEIGHT - 135, WHITEFRETWIDTH, WHITEFRETHEIGHT)
pygame.draw.rect(DISPLAYSURF, WHITE, fret)
associateWhiteNote(fret, OCTAVE, i)
WHITESTARTCOORDX += WHITEFRETWIDTH + 1 # + 1 to separate frets
def generateBlackFrets(BLACKSTARTCOORDX, OCTAVE):
for i in range(0,6):
if i == 2:
BLACKSTARTCOORDX += BLACKGAPSIZE
else:
fret = pygame.Rect(BLACKSTARTCOORDX, WINDOWHEIGHT - 135, BLACKFRETWIDTH, BLACKFRETHEIGHT)
pygame.draw.rect(DISPLAYSURF, BLACK, fret)
associateBlackNote(fret, OCTAVE, i)
BLACKSTARTCOORDX += BLACKGAPSIZE
def associateWhiteNote(fret, OCTAVE, index):
if index == 0:
OCTAVE['C'] = fret
elif index == 1:
OCTAVE['D'] = fret
elif index == 2:
OCTAVE['E'] = fret
elif index == 3:
OCTAVE['F'] = fret
elif index == 4:
OCTAVE['G'] = fret
elif index == 5:
OCTAVE['A'] = fret
elif index == 6:
OCTAVE['B'] = fret
def associateBlackNote(fret, OCTAVE, index):
if index == 0:
OCTAVE['C#'] = fret
if index == 1:
OCTAVE['D#'] = fret
if index == 3:
OCTAVE['F#'] = fret
if index == 4:
OCTAVE['G#'] = fret
if index == 5:
OCTAVE['A#'] = fret
In ogni caso finché tenevo le funzioni nello stesso file il software funzionava (anche se non l'ho finito al momento)
Mmm, principalmente non funziona perchè nel main non viene dichiarata alcuna istanza della classe basePPT. :D
Ma soprattutto, perchè hai racchiuso tutti i metodi nella classe basePPT? Ad occhio non ce n'era alcun bisogno..
Heretic Curse
20-08-2013, 14:12
Giusto per avere il codice un po' più in ordine :/ comunque è vero, il problema è quello :D
Il punto è che anche facendo
from basePPT import *
non funziona. Ergo dovrò scrivere basePPT davanti a ogni funzione richiamata...
Comunque il codice al momento e sulle 460 righe, ma credo di non essere ancora a metà della sua stesura definitiva, quindi credo che per una lunghezza simile dividere il codice potrebbe essere una buona idea. Non dico sia una lunghezza assurda, ma neanche troppo breve. Sbaglio?
Bah, se non hai necessità di estendere (aka personalizzare) la classe la trovo una cosa inutile :D
Praticamente stai usando la classe come namespace... il namespace in questo caso è già il modulo, quindi è inutile crearne uno ulteriore. :)
Per quanto riguarda l'organizzazione, personalmente penso che la cosa dipenda da quello che fa il codice.
Sempre attenzione all'import *, non sai mai bene quello che viene importato e corri il rischio di "mettere in ombra" oggetti locali.
Heretic Curse
20-08-2013, 14:47
Ok, ho capito che in questo caso la classe è un po' uno spreco.
Tuttavia non ho ancora ben chiaro se esiste o meno un modo per farmi tenere le funzioni separate dal resto e permettermi di usare senza scrivere basePPT ogni volta. Puoi spiegarmi per favore? :D
Inoltre sai perché non funziona import * in questo caso?
import crea, nel namespace attuale, un riferimento a ciò che viene definito nel top level del modulo importato, quindi per accedere a tutto quello che è all'interno di classi o simili devi passare attraverso tale riferimento.
A questo punto hai queste alternative:
- Scrivi le funzioni nel top level del modulo (quindi non all'interno di classi o simili) e le importi con from basePPT import *. In questo modo potrai chiamarle senza anteporre basePPT
- Le dichiari all'interno di una classe (magari statiche col decorator @staticmethod) e le usi attraverso il nome della classe, quindi basePPT.nome_metodo()
A te scegliere quale. :D
Heretic Curse
20-08-2013, 18:36
Beh, la seconda :D Scherzo.
Grazie mille ;) sto avendo ancora qualche problemino per via di variabili come DISPLAYSURF, ma questi dovrei riuscire a risolverli.
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.