Advertisement
davidhellam

Python: Emoji Final Game

Aug 17th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.03 KB | None | 0 0
  1. import os
  2. from random import shuffle,randrange
  3. from guizero import App, Box, Picture, Text, info, PushButton, yesno, Window
  4.  
  5. # set the path to the emoji folder on your computer
  6. emojis_dir = "emojis"
  7. # create a list of the locations of the emoji images
  8. emojis = [os.path.join(emojis_dir, f) for f in os.listdir(emojis_dir) if os.path.isfile(os.path.join(emojis_dir, f))]
  9. # shuffle the emojis
  10.  
  11. blank = "25fb.png"
  12. start = "25b6.png"
  13. alert = "26a0.png"
  14. correct = "2705.png"
  15. usedemojis = []
  16.  
  17. gameOn = False
  18.  
  19. app = App("Emoji Match Game",width=720, height=420)
  20.  
  21. #initialise other windows for game
  22. helpwindow = Window(app, title="Help Screen", width=600, height=400)
  23. hswindow = Window(app, title="High Scores", width=600, height=400)
  24. addHSwindow = Window(app, title="Add a new high score", width=600, height=400)
  25.  
  26. #functions for adding high scores
  27. def closeAddHS():
  28.     addHSwindow.hide()
  29.  
  30. def newHighScore(topscore):
  31.     ahs_score.value = topscore
  32.     openAddHS()
  33.  
  34. def openAddHS():
  35.     #makes the add high score window main focus until new score added
  36.     addHSwindow.show(wait=True)
  37.  
  38. def addKey(event_data):
  39.     #adds 3 letters for each high score recorded
  40.     key_pressed = event_data.widget
  41.     chars=[]
  42.     for count in range(0,3):
  43.         chars.append(ahs_name.value[count])
  44.     chars[ahs_name.pointer]=key_pressed.text
  45.     ahs_name.value=chars[0]+chars[1]+chars[2]
  46.     ahs_name.pointer=(ahs_name.pointer+1)%3
  47.    
  48. def addScore():
  49.     #appends high score to textfile
  50.     with open("hiscores.txt", "a") as f:
  51.         f.write(ahs_name.value+str(ahs_score.value)+"\n")
  52.         f.close()
  53.     addHSwindow.hide()
  54.  
  55. #functions for high score screen
  56. def closeHS():
  57.     hswindow.hide()
  58.  
  59. def openHS():
  60.     read_scores()
  61.     hswindow.show()
  62.  
  63. def read_scores():
  64.     #reads and separates high scores and names
  65.     names = []
  66.     scores = []
  67.     with open("hiscores.txt", "r") as f:
  68.         allscores = f.readlines()
  69.     for count in range(len(allscores)):
  70.         allscores[count].replace("\n","")
  71.         names.append(allscores[count][0:3])
  72.         scores.append(int(allscores[count][3:]))
  73.        
  74.     #does a bubble sort - bit of overkill really as only newest high scores are recorded
  75.     sorted_data = []
  76.     for i in range(len(scores)):
  77.         sorted_data.append(scores[i])
  78.  
  79.     done_sorting = False
  80.     k = 0
  81.     swaps = 0
  82.     while not done_sorting:
  83.         done_sorting = True
  84.         k = k+1
  85.         for j in range(len(sorted_data)-k):
  86.             if (sorted_data[j]>sorted_data[j+1]):
  87.                 temp = sorted_data[j]
  88.                 sorted_data[j] = sorted_data[j+1]
  89.                 sorted_data[j+1] = temp
  90.                 done_sorting = False
  91.                 swaps = swaps + 1
  92.    
  93.     leader_score=[]
  94.     leader_label=[]
  95.     for count in range (len(sorted_data)-3,len(sorted_data)):
  96.         leader_score.append(sorted_data[count])
  97.         for count2 in range (len(scores)):
  98.            
  99.             if scores[count2] == sorted_data[count]:
  100.                 leader_label.append(names[count2])
  101.                
  102.     #displays three highest scores
  103.     hs_label1.value = leader_label[2]
  104.     hs_label2.value = leader_label[1]
  105.     hs_label3.value = leader_label[0]
  106.     hs_score1.value = leader_score[2]
  107.     hs_score2.value = leader_score[1]
  108.     hs_score3.value = leader_score[0]  
  109.    
  110. #functions for help screen
  111. def closeHelp():
  112.     helpwindow.hide()
  113.  
  114. def openHelp():
  115.     helpwindow.show()
  116.  
  117. #re-initialise scores and emoji for a new game
  118. def startAgain():    
  119.     roundno.value="0"
  120.     P1_score.value = "0"
  121.     P2_score.value = "0"
  122.     for i in range (len(usedemojis)):
  123.         emojis.append(usedemojis.pop())
  124.     startbutton.show()
  125.  
  126. #counts down time
  127. def doTime():
  128.     if (int(timeleft.value)>0 and feedback.value != "Match Found!" and timeleft.timeout==False):
  129.         timeleft.value=str(int(timeleft.value)-1)
  130.     else:
  131.         timeleft.value=str(int(timeleft.value)-0)
  132.         #what happens when out of time
  133.         if (int(timeleft.value)==0 and timeleft.timeout == False):
  134.             timeleft.timeout=True
  135.             extratime = yesno("Time Over","No time left - would you like to continue?")
  136.             if extratime:
  137.                 timeleft.hide()
  138.             else:
  139.                 startbutton.show()
  140.                
  141. #sets up the emoji for game        
  142. def initialicon():
  143.     leftset=[]
  144.     rightset=[]
  145.  
  146.     shuffle(emojis)
  147.  
  148.     for count in range(0,9):
  149.         leftset.append(emojis[count])
  150.         rightset.append(emojis[count+8])
  151.  
  152.     shuffle(leftset)
  153.     shuffle(rightset)
  154.  
  155.     myemojis = []
  156.  
  157.     for count in range(0,9):
  158.         myemojis.append(leftset[count])
  159.  
  160.     myemojis.append(blank)
  161.     myemojis.append(blank)
  162.  
  163.     for count in range(0,9):
  164.         myemojis.append(rightset[count])
  165.  
  166.     return(myemojis)
  167.  
  168. #when start button is pressed
  169. def doStart():
  170.     if int(roundno.value)<10:
  171.         myemojis = initialicon()
  172.         for count in range(0,20):
  173.             pictures[count].image = myemojis[count]
  174.         feedback.value=""
  175.         roundno.value=str(int(roundno.value)+1)
  176.         timeleft.value=str(int(30))
  177.         P1_score.bonus = 10
  178.         P2_score.bonus = 10
  179.         startbutton.hide()
  180.         timeleft.show()
  181.         timeleft.timeout=False
  182.  
  183. #testing for a match
  184. def testmatch():
  185.     if (pictures[9].image == pictures[10].image):
  186.         feedback.value= "Match Found!"
  187.         timeleft.hide()
  188.         #removes matched emoji from current list
  189.         usedemojis.append(pictures[9].value)
  190.         emojis.remove(pictures[9].value)
  191.         #adding to score and setting up for next round
  192.         if (int(roundno.value)%2==1):
  193.             P1_score.value=str(int(P1_score.value)+int(P1_score.bonus)+int(timeleft.value))
  194.             startbutton.bg=(127,255,255)
  195.             startbutton.text="Player 2 Start"
  196.         else:
  197.             P2_score.value=str(int(P2_score.value)+int(P2_score.bonus)+int(timeleft.value))
  198.             startbutton.bg=(255,127,255)
  199.             startbutton.text="Player 1 Start"
  200.         #testing for end of game
  201.         if (int(roundno.value) == 10):
  202.             if (int(P1_score.value)>int(P2_score.value)):
  203.                 winner = "winner is Player 1"
  204.                 topscore = int(P1_score.value)
  205.             elif (int(P1_score.value)<int(P2_score.value)):
  206.                 winner = "winner is Player 2"
  207.                 topscore = int(P2_score.value)
  208.             else:
  209.                 winner = "result is a draw"
  210.                 topscore = int(P1_score.value)
  211.             info("The End","Well done, the "+ winner)
  212.             read_scores()
  213.             if (int(topscore) > int(hs_score1.value)):
  214.                 newHighScore(topscore)
  215.             anothergame = yesno("Another Game?","Would you like to play another game?")
  216.             if anothergame:
  217.                 startAgain()
  218.         else:
  219.             #on to the next round
  220.             startbutton.show()
  221.     else:
  222.         #what happens if they don't match?
  223.         if((pictures[9].image != blank) and (pictures[10].image != blank)):
  224.             feedback.value="Not a Match!"
  225.             if (int(roundno.value)%2==1):
  226.                 P1_score.bonus=int(P1_score.bonus)-1
  227.             else:
  228.                 P2_score.bonus=int(P2_score.bonus)-1
  229.  
  230. # clicking on the left and right hand grids              
  231. def leftselected(event_data):
  232.     pic_clicked = event_data.widget
  233.     pictures[9].image = pic_clicked.image
  234.     testmatch()
  235.  
  236. def rightselected(event_data):
  237.     pic_clicked = event_data.widget
  238.     pictures[10].image = pic_clicked.image
  239.     testmatch()
  240.  
  241. # call to set up the first two grids of emojis
  242. myemojis = initialicon()
  243.  
  244. # create the help window
  245. helpwindow.hide()
  246. help_box=Box(helpwindow, width= 600, height=400, layout="grid")
  247. help_title=Text(help_box, text="Emoji Game Help", size=24, grid = [0,0,3,1])
  248. help_body1=Text(help_box, text="This is a two-player game.\nEach player takes turns to find matching emoji.", grid = [0,1,3,1])
  249. help_body2=Text(help_box, text="You see two grids of nine randomly arranged emoji.\nOnly one emoji will be the same in both grids.", grid = [0,2,3,1])
  250. help_body3=Text(help_box, text="You have 30 seconds to locate and click on the two emoji which are the same.", grid = [0,3,3,1])
  251. help_body4=Text(help_box, text="If you don\'t make any mistakes, you get a bonus of 10 points.", grid = [0,4,3,1])
  252. help_body5=Text(help_box, text="You take it in turns to play five rounds each.\nYour score for each round will be added to a cumulative total.", grid = [0,5,3,1])
  253. help_body6=Text(help_box, text="The player with the highest cumulative total wins.", grid = [0,6,3,1])
  254. help_close=PushButton(help_box, text="Close Help", align="right" ,grid=[2,7,1,1])
  255.  
  256. #help window functions
  257. help_close.when_clicked=closeHelp
  258.  
  259. #create High Score display
  260. hswindow.hide()
  261. hs_box=Box(hswindow, width= 600, height=400, layout="grid")
  262. hs_title=Text(hs_box, text="Emoji Game High Scores", size=24, grid = [0,0,3,1])
  263. hs_label1=Text(hs_box, text="---", size=18, grid=[0,1,1,1])
  264. hs_label2=Text(hs_box, text="---", size=18, grid=[0,2,1,1])
  265. hs_label3=Text(hs_box, text="---", size=18, grid=[0,3,1,1])
  266. hs_score1=Text(hs_box, text="0", size=18, grid=[1,1,1,1])
  267. hs_score2=Text(hs_box, text="0", size=18, grid=[1,2,1,1])
  268. hs_score3=Text(hs_box, text="0", size=18, grid=[1,3,1,1])
  269.  
  270. hs_close=PushButton(hs_box, text="Close\nHigh Score\nDisplay", align="right" ,grid=[2,4,1,1])
  271.  
  272. #high score display window functions
  273. hs_close.when_clicked=closeHS
  274.  
  275. #create form for adding new high score
  276. addHSwindow.hide()
  277. ahs_box=Box(addHSwindow, width= 600, height=400, layout="grid")
  278. ahs_title=Text(ahs_box, text="Emoji Game : New High Score", size=24, grid = [0,0,15,1])
  279. ahs_label=Text(ahs_box, text="Name: ", size=18, grid=[0,1,3,1])
  280. ahs_name = Text(ahs_box,text="***",size=18,grid=[3,1,3,1])
  281. ahs_score_label= Text(ahs_box,text="Score: ",size=18,grid=[6,1,3,1])
  282. ahs_score= Text(ahs_box,text="0",size=18,grid=[9,1,3,1])
  283. ahs_info1=Text(ahs_box,text="We have a new High Score!\nClick on three keys for your name.",size=8,grid=[0,2,15,1])
  284. ahs_info2=Text(ahs_box,text="Click on the [ENTER] button when finished.",size=8,grid=[0,3,15,1])
  285. ahs_key=[]
  286. for x in range(0,13):
  287.     for y in range (4,6):
  288.         counter=x+(y-4)*13
  289.         character=chr(65+counter)
  290.         key=PushButton(ahs_box,text=character,grid=[x,y])
  291.         ahs_key.append(key)
  292. key=PushButton(ahs_box,text='.',grid=[13,4])
  293. ahs_key.append(key)
  294. key=PushButton(ahs_box,text='-',grid=[14,4])
  295. ahs_key.append(key)
  296. enterkey=PushButton(ahs_box,text="Enter",grid=[13,5,2,1])
  297. ahs_name.pointer=0
  298. for count in range(0,28):
  299.     ahs_key[count].when_clicked=addKey
  300. enterkey.when_clicked=addScore
  301. # create a box to house the grid
  302. pictures_box = Box(app, layout="grid")
  303.  
  304. header=Text(pictures_box, text="Emoji Match Game", size=28, grid=[0,0,8,1])
  305.  
  306. # create an empty list to which pictures will be added
  307. pictures = []
  308. for x in range(0,3):
  309.     for y in range(1,4):
  310.         # put the pictures into the list
  311.         picture = Picture(pictures_box, grid=[x,y])
  312.         pictures.append(picture)
  313.  
  314. #these are the two images which display which emoji have been clicked on
  315. picture = Picture(pictures_box, grid=[3,4])
  316. pictures.append(picture)
  317. picture = Picture(pictures_box, grid=[4,4])
  318. pictures.append(picture)
  319.  
  320. for x in range(5,8):
  321.     for y in range(1,4):
  322.         # put the pictures into the list
  323.         picture = Picture(pictures_box, grid=[x,y])
  324.         pictures.append(picture)
  325. # for each picture in the list
  326. counter = 0
  327.  
  328. for picture in pictures:
  329.     # sets all 18 images in the grids and the two status images to blank
  330.     pictures[counter].image = blank
  331.     counter=counter+1
  332. #display score
  333. P1_label=Text(pictures_box, text="Player 1\nScore:", size=10, align="right",grid=[0,4])
  334. P1_score=Text(pictures_box, text="0", size=20, align="left", grid=[1,4])
  335. P2_label=Text(pictures_box, text="Player 2\nScore:", size=10, align="right",grid=[6,4])
  336. P2_score=Text(pictures_box, text="0", size=20, align="left", grid=[7,4])
  337.  
  338. #display tiemr and round
  339. time_label=Text(pictures_box, text="Time:", size=8,align="right",grid=[3,1])
  340. timeleft=Text(pictures_box, text="30", size=8,align="left",grid=[4,1])
  341. round_label=Text(pictures_box, text="Round:", align="right",size=8,grid=[3,3])
  342. roundno=Text(pictures_box, text="0", size=8,align="left",grid=[4,3])
  343.  
  344. #help screen button
  345. helpbutton=PushButton(pictures_box,text="Help", grid=[7,5])
  346. helpbutton.when_clicked=openHelp
  347.  
  348. # high score display button
  349. hsbutton=PushButton(pictures_box,text="High\nScore", grid=[0,5])
  350. hsbutton.when_clicked=openHS
  351.  
  352.  
  353. # display feedback for matching
  354. feedback=Text(pictures_box, text="",size=14, align="bottom" , grid=[3,5,2,1])
  355.  
  356. #start button initialised for Player 1
  357. startbutton = PushButton(pictures_box, text="Player 1 Start", grid=[3,2,2,1])
  358. startbutton.bg=(255,128,255)
  359. startbutton.when_clicked = doStart
  360.  
  361. # set up emoji as buttons
  362. for count in range(0,9):
  363.     pictures[count].when_clicked = leftselected
  364.  
  365. for count in range(11,20):
  366.     pictures[count].when_clicked = rightselected
  367.  
  368. #timer functions
  369. timeleft.timeout=True
  370. timeleft.hide()
  371. timeleft.repeat(1000,doTime)
  372.  
  373. app.display()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement