moyenne.py

Created by stimorol

Created on July 08, 2024

6.51 KB

Programme de calcul de moyenne à partir des notes entrées par l’utilisateur. L’utilisateur peut entrer ses notes, classées par matière. Il est possible de supprimer des notes ou des matières (avec la touche supprimer en haut a droite). Utiliser la touche maison pour revenir au menu principal. Enfin, le programme sauvegarde automatiquement les notes entrées par l’utilisateur.


from kandinsky import fill_rect as rect, draw_string as txt
from random import choice
from ion import keydown as key
from time import sleep

# STARTED 02.03.23
# ENDED 05.03.23

try:
  from kandinsky import draw_line as line
except:
  from kandinsky import set_pixel as px
  def line(x0,y0,x1,y1,color):
    h=((x1-x0)**2+(y1-y0)**2)**0.5
    cos=(x1-x0)/h
    sin=(y1-y0)/h
    for p in range(int(h)+1):
      px(x0+int(cos*p),y0+int(sin*p),color)
  
try:
  from kandinsky import draw_line as line, get_palette as palette
except:
  def palette():
    return {'Toolbar':(120, 160, 200)}

subjectsSav='subjects.moy'
gradeSav='grades.moy'

def save(subjects,grades):
  for sav in [[subjectsSav,subjects],[gradeSav,grades]]:
    with open(str(sav[0]),'w') as f:
      f.write(str(sav[1]))
def load():
  try:
    with open(subjectsSav,'r') as f:subjects=eval(f.readline())
    with open(gradeSav,'r') as f:grades=eval(f.readline())
    return subjects,grades
  except:
    input('\n\n\n\n\n   Bienvenue !\n\nCe programme sert a calculer ta moyenne.\nTu peux ajouter des notes (une note,\nle bareme et le coeficient), ou des\nmatieres.\n\nJ\'espere qu\'il te sera utile !\n')
    return {},{}
def moy(subjects,grades): # Calculation of average per grade and global average
  avgSub,nsub={},[]
  for name in subjects:
    if grades[name]!=[]:nsub+=[name]
  for sub in nsub:
    total,div=0,0
    for grade in grades[sub]:
      if grade[1]!=0:
        total+=grade[0]/grade[1]*20*grade[2]
        div+=grade[2]
    if div!=0:avgSub[sub]=round(total/div,1)
    else:avgSub[sub]=0
  avg=sum([subjects[sub]*(sum(avgSub.values())/len(avgSub)) for sub in subjects.keys()])/sum(list(subjects.values()))
  for name in subjects:
    if grades[name]==[]:avgSub[name]='?'
  return avgSub,avg

# ALL THE SMALL FUNCTIONS

bgCol=palette()['Toolbar']
bgTxt=(83,122,205)
thx=['All good!','Perfect!','Copy that.','Done!','Houston, we don\'t have any problem.','Have a good day!','We love you!','We know you are doing your best!','Continue like that!','<3',':D','The dev is beautiful']
frame=lambda x,y,col: rect(44+x*78,128+y*44,36,19,col)
new=lambda: rect(0,0,322,222,bgCol)
gradeCol=lambda g:(150-int(g*6.25),int(g*8),0) if type(g)!=str else (0,)*3
r=lambda t:str(t) if type(t)!=int else str(int(t))
def inp(txt,nat,defVal):
  out=input(txt)
  if out=='':return defVal
  return nat(out)
def wait():
  while key(4):pass
def gradient(mode):
  nr,ng,nb=(255-bgCol[0])//10,(255-bgCol[1])//10,(255-bgCol[2])//10
  val=[bgCol,(255,)*3][mode]
  for i in range(10):rect(0,0,322,222,(val[0]+[nr*i,-nr*i][mode],val[1]+[ng*i,-ng*i][mode],val[2]+[nb*i,-nb*i][mode]));sleep(.025)

# START OF USEFUL FUNCTIONS:
  # main: main screen w/ all subjects
  # sub: for the infos on a subject (grades...)
# For each, there is a global func. and a draw func

def draw_main(sel):
  if sel==0:col=bgTxt;rect(246,60,44,20,(0,)*3)
  else:col=bgCol;rect(246,60,44,20,bgCol)
  rect(205,42,83,36,col)
  txt('+',210,52,(0,)*3,col)
  txt('Add\nsubject',230,45,(0,)*3,col,1)
  for i,name in enumerate(subjects.keys()):
    col=bgCol
    if i==sel-1:col=bgTxt;rect(8,111+i*30,2,25,(0,)*3)
    rect(10-2*(i!=(sel-1)),111+i*30,297+2*(i!=(sel-1)),25,col)
    txt(name,20,111+i*30+6,(0,)*3,col,1)
    txt('c. '+r(subjects[name]),175,111+i*30+6,(0,)*3,col,1)
    txt('m. '+r(avgSub[name]),240,111+i*30+6,(0,)*3,col,1)
def draw_sub(name,sel,x=0,y=0):
  if sel[0]==-1 or sel[1]==-1:col=bgTxt;rect(238,60,36,20,(0,)*3)
  else:col=bgCol;rect(238,60,36,20,bgCol)
  rect(205,42,67,36,col)
  txt('+',210,52,(0,)*3,col)
  txt('add\ngrade',230,45,(0,)*3,col,1)
  for grade in grades[name]:
    if sel==[x,y]:col=bgTxt;frame(x,y,(0,)*3)
    else:col=bgCol;frame(x,y,bgCol)
    rect(10+x*78,111+y*44,68,34,col)
    txt(r(grade[0])+'/'+r(grade[1]),17+x*78,116+y*44,gradeCol(grade[0]/grade[1]*20),col,1)
    txt('coef '+r(grade[2]),17+x*78,128+y*44,'black',col,1)
    x+=1
    if x==4:x,y=0,y+1
def edit_mat(name,sel=[0,-1]):
  new()
  txt(name+': '+str(avgSub[name]),25,40,gradeCol(avgSub[name]),bgCol)
  txt('coef '+str(subjects[name]),25,60,(0,)*3,bgCol,1)
  draw_sub(name,sel)
  while not (key(4) or key(6) or key(17)):
    for k in [0,3]:
      if key(k):
        if sel[1]!=-1:sel[0]=sel[0]+[-1,1][bool(k)]
        else:sel=[0,0]
        if sel[0]==4:sel=[0,sel[1]+1]
        elif sel[0]<0:sel=[3,max(-1,sel[1]-1)]
        elif sel[1]==int(len(grades[name])/4):sel[0]=min(sel[0],len(grades[name])%4-1)
        draw_sub(name,sel)
    for k in [1,2]:
      if key(k):
        sel[1]=max(-1,min(int(len(grades[name])/4),sel[1]+['I <3 u',-1,1][k]))
        if sel[1]==int(len(grades[name])/4):sel[0]=min(sel[0],len(grades[name])%4-1)
        draw_sub(name,sel)
    sleep(.1)
  if key(4) and -1 in sel:grades[name]=new_grade(name);gradient(0)
  elif key(17):grades[name].pop(sel[1]*4+sel[0])
  main()
def new_grade(name,newGrade=[0,0,0]):
  global grades,avgSub,avg
  for i,t in enumerate(['\n'*15+'Adding a new '+name+' grade !\n\nEnter your grade: ','Now the scale of the mark: ','And finally the coeficient: ']):newGrade[i]=inp(t,float,1)
  print('\n\n'+choice(thx)+'\n\n')
  grades[name]+=[newGrade]
  save(subjects,grades)
  avgSub,avg=moy(subjects,grades)
  sleep(.25)
  gradient(1)
  edit_mat(name)
def main(sel=0):
  new()
  global subjects,grades,avg
  txt('AVERAGE: '+r(avg),25,50,gradeCol(avg),bgCol)
  if sel==0:col=bgTxt;rect(246,60,44,20,(0,)*3)
  else:col=bgCol
  rect(205,42,83,36,col)
  txt('+',210,52,(0,)*3,col)
  txt('Add\nsubject',230,45,(0,)*3,col,1)
  draw_main(sel)
  wait()
  while not (key(4) or key(17)):
    for k in [1,2]:
      if key(k):
        sel=max(0,min(sel+[-1,1][k-1],len(subjects)))
        draw_main(sel)
    sleep(.1)
  wait()
  if key(17):
    sub=list(subjects.keys())[sel-1]
    if input('\n\n\n --- SUPPRESSION DE '+sub+'\nEtes vous sur ? (yep/non)\n')=='yep':
      wait()
      subjects.pop(sub)
      grades.pop(sub)
      avgSub,avg=moy(subjects,grades)
      save(subjects,grades)
    sel=-1
    main()
  if sel==0:
    gradient(0)
    name=inp('\n'*15+' --- Adding a new subject !\n\nEnter the subject name: ',str,'???')
    coef=inp('And now the coeficient of this subject: ',float,0)
    print('\n\n'+choice(thx)+'\n\n')
    subjects[name],grades[name]=coef,[]
    save(subjects,grades)
    new_grade(name)
  elif sel>0:edit_mat(list(subjects.keys())[sel-1])

#  %LOADING OF GRADES
subjects,grades=load()
if subjects!={}:avgSub,avg=moy(subjects,grades)
else:avg,avgSub='?','?'

try:main()
except KeyboardInterrupt:
  print('\n'*10,' --- EXITING THE PROGRAM\n\nAverage:',avg,'\n')
  for name in subjects:print(name,':',avgSub[name])
  print('\n',choice(thx[4:]))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.