Best Python code snippet using fMBT_python
game.py
Source:game.py
1import pygame, sys, json, ctypes, random, linecache2from pygame.locals import *3from random import randrange4user32 = ctypes.windll.user32567#setup wordcount (used to gen max random number later to fetch words)8file = open("./resources/data/words.txt", "r")9line_count = 010for line in file:11 if line != "\n":12 line_count += 113file.close()1415#check resolution settings16f = open("./resources/data/settings.json", "r")17data = json.load(f)18f.close()19if data['resolution'] == 0:20 data['resolution'] = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)21 f = open("./resources/data/settings.json", "w")22 json.dump(data, f)23 f.close()2425#start game engine & clock26mainClock = pygame.time.Clock()27pygame.init()2829#set window settings30pygame.display.set_caption('Typing Fever')31screensize = data['resolution'][0], data['resolution'][1]32if data['fullscreen'] == "yes":33 screen = pygame.display.set_mode((screensize),FULLSCREEN,32)34else:35 screen = pygame.display.set_mode((screensize),0,32)36pygame.mouse.set_visible(0)37bg = pygame.image.load("./resources/images/bg.jpg")3839#set sounds40menusound = pygame.mixer.Sound('./resources/sounds/menu.wav')41menusound.set_volume(int(data['sfx'])/100)42hitsound = pygame.mixer.Sound('./resources/sounds/hit.wav')43hitsound.set_volume(int(data['sfx'])/100)44killsound = pygame.mixer.Sound('./resources/sounds/kill.wav')45killsound.set_volume(int(data['sfx'])/100)46backgroundmusic = pygame.mixer.music.load('./resources/sounds/bgm.mp3')47pygame.mixer.music.set_volume(int(data['bgm'])/100)48pygame.mixer.music.play(-1)495051#set font52def font(size):53 return pygame.font.Font("./resources/fonts/RobotCrush.ttf", size)5455#text drawer56def draw_text(text, font, color, surface, x, y):57 textobj = font.render(text, 1, color)58 textrect = textobj.get_rect(center=(x, y))59 surface.blit(textobj, textrect)6061#create our starting menu screen62def startMenu(selected):63 while True:64 #create background65 screen.fill((0,0,0))66 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))67 #title68 draw_text('TYPING FEVER', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))69 #menu handler70 if selected == 0:71 draw_text('>S T A R T', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/2.8))72 draw_text('LEADERBOARDS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.15))73 draw_text('OPTIONS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.7))74 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))75 elif selected == 1:76 draw_text('START', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.8))77 draw_text('>L E A D E R B O A R D S', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/2.15))78 draw_text('OPTIONS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.7))79 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))80 elif selected == 2:81 draw_text('START', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.8))82 draw_text('LEADERBOARDS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.15))83 draw_text('>O P T I O N S', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.7))84 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))85 elif selected == 3:86 draw_text('START', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.8))87 draw_text('LEADERBOARDS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.15))88 draw_text('OPTIONS', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.7))89 draw_text('>Q U I T', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.4))90 #event handler91 for event in pygame.event.get():92 if event.type == KEYDOWN:93 if event.key == K_RETURN or event.key == K_SPACE:94 if selected == 0:95 menusound.play()96 start(0)97 elif selected == 1:98 menusound.play()99 leaderboards(0)100 elif selected == 2:101 menusound.play()102 options(0)103 elif selected == 3:104 pygame.quit()105 sys.exit()106 elif event.key == K_DOWN or event.key == K_s:107 if selected < 3:108 menusound.play()109 selected = selected + 1110 elif selected == 3:111 menusound.play()112 selected = 0113 elif event.key == K_UP or event.key == K_w:114 if selected > 0:115 menusound.play()116 selected = selected - 1117 elif selected == 0:118 menusound.play()119 selected = 3120 #gametick and display updater121 pygame.display.update()122 mainClock.tick(60)123124def options(selected):125 #setup all variables and fetch data from json file126 active = True127 f = open("./resources/data/settings.json", "r")128 data = json.load(f)129 bgmval = data['bgm']130 sfxval = data['sfx']131 fullscreenval = data['fullscreen']132 resolutions = ["1920x1080", "1600x900", "1366x768", "1280x720", "1920x1200", "1680x1050", "1440x900", "1024x768"]133 currentres = str(data['resolution'][0])+"x"+str(data['resolution'][1])134 resindex = 0135 for i in range(len(resolutions)):136 if resolutions[i] == currentres:137 resindex = i138 break139 while active:140 #create background141 screen.fill((0,0,0))142 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))143 #title144 draw_text('OPTIONS', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))145 if selected == 0:146 draw_text('>B G M: '+bgmval, font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/3.1))147 draw_text('SFX: '+sfxval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))148 draw_text('FULLSCREEN: '+fullscreenval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))149 draw_text('RESOLUTION: '+resolutions[resindex], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))150 draw_text('SAVE AND QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))151 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))152 elif selected == 1:153 draw_text('BGM: '+bgmval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))154 draw_text('>S F X: '+sfxval, font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/2.4))155 draw_text('FULLSCREEN: '+fullscreenval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))156 draw_text('RESOLUTION: '+resolutions[resindex], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))157 draw_text('SAVE AND QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))158 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))159 elif selected == 2:160 draw_text('BGM: '+bgmval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))161 draw_text('SFX: '+sfxval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))162 draw_text('>F U L L S C R E E N: '+fullscreenval, font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.95))163 draw_text('RESOLUTION: '+resolutions[resindex], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))164 draw_text('SAVE AND QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))165 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))166 elif selected == 3:167 draw_text('BGM: '+bgmval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))168 draw_text('SFX: '+sfxval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))169 draw_text('FULLSCREEN: '+fullscreenval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))170 draw_text('>R E S O L U T I O N: '+resolutions[resindex], font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.65))171 draw_text('SAVE AND QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))172 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))173 elif selected == 4:174 draw_text('BGM: '+bgmval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))175 draw_text('SFX: '+sfxval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))176 draw_text('FULLSCREEN: '+fullscreenval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))177 draw_text('RESOLUTION: '+resolutions[resindex], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))178 draw_text('>S A V E A N D Q U I T', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.4))179 draw_text('QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))180 elif selected == 5:181 draw_text('BGM: '+bgmval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))182 draw_text('SFX: '+sfxval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))183 draw_text('FULLSCREEN: '+fullscreenval, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))184 draw_text('RESOLUTION: '+resolutions[resindex], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))185 draw_text('SAVE AND QUIT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.4))186 draw_text('>Q U I T', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.2))187 #event handler188 for event in pygame.event.get():189 if event.type == KEYDOWN:190 if event.key == K_RETURN or event.key == K_SPACE:191 if selected == 4:192 menusound.play()193 data['bgm'] = bgmval194 data['sfx'] = sfxval195 newres = list(map(int, resolutions[resindex].split("x")))196 f = open("./resources/data/settings.json", "w")197 json.dump(data, f)198 f.close()199 if fullscreenval != data['fullscreen']:200 restart(0, fullscreenval, newres)201 active = False202 startMenu(0)203 elif newres != data['resolution']:204 restart(0, fullscreenval, newres)205 active = False206 startMenu(0)207 pygame.mixer.music.set_volume(int(data['bgm'])/100)208 menusound.set_volume(int(data['sfx'])/100)209 hitsound.set_volume(int(data['sfx'])/100)210 killsound.set_volume(int(data['sfx'])/100)211 active = False212 startMenu(0)213 elif selected == 5:214 menusound.play()215 active = False216 startMenu(0)217 elif event.key == K_RIGHT or event.key == K_d:218 if selected == 0:219 if int(bgmval) < 100:220 bgmval = str(int(bgmval) + 10)221 pygame.mixer.music.set_volume(int(bgmval)/100)222 menusound.play()223 elif selected == 1:224 if int(sfxval) < 100:225 sfxval = str(int(sfxval) + 10)226 menusound.set_volume(int(sfxval)/100)227 hitsound.set_volume(int(sfxval)/100)228 killsound.set_volume(int(sfxval)/100)229 menusound.play()230 elif selected == 2:231 if fullscreenval == "yes":232 menusound.play()233 fullscreenval = "no"234 elif fullscreenval == "no":235 menusound.play()236 fullscreenval = "yes"237 elif selected == 3:238 if resindex < len(resolutions)-1:239 menusound.play()240 resindex = resindex +1241 elif event.key == K_LEFT or event.key == K_a:242 if selected == 0:243 if int(bgmval) > 0:244 bgmval = str(int(bgmval) - 10)245 pygame.mixer.music.set_volume(int(bgmval)/100)246 menusound.play()247 elif selected == 1:248 if int(sfxval) > 0:249 sfxval = str(int(sfxval) - 10)250 menusound.set_volume(int(sfxval)/100)251 hitsound.set_volume(int(sfxval)/100)252 killsound.set_volume(int(sfxval)/100)253 menusound.play()254 elif selected == 2:255 if fullscreenval == "yes":256 menusound.play()257 fullscreenval = "no"258 elif fullscreenval == "no":259 menusound.play()260 fullscreenval = "yes"261 elif selected == 3:262 if resindex > 0:263 menusound.play()264 resindex = resindex -1265 elif event.key == K_DOWN or event.key == K_s:266 if selected < 5:267 menusound.play()268 selected = selected + 1269 elif selected == 5:270 menusound.play()271 selected = 0272 elif event.key == K_UP or event.key == K_w:273 if selected > 0:274 menusound.play()275 selected = selected - 1276 elif selected == 0:277 menusound.play()278 selected = 5279 #gametick and display updater280 pygame.display.update()281 mainClock.tick(60)282283def restart(selected, fullscreenval, newres):284 #define vars285 active = True286 while active:287 #create background288 screen.fill((0,0,0))289 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))290 draw_text('OPTIONS', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))291 draw_text('SOME CHANGES NEED A RESTART TO TAKE EFFECT', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3.1))292 if selected == 0:293 draw_text('>O K A Y<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.95))294 draw_text('UNDO CHANGES', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))295 if selected == 1:296 draw_text('OKAY', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))297 draw_text('>U N D O C H A N G E S<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.65))298 #event handler299 for event in pygame.event.get():300 if event.type == KEYDOWN:301 if event.key == K_RETURN or event.key == K_SPACE:302 if selected == 0:303 menusound.play()304 f = open("./resources/data/settings.json", "r")305 data = json.load(f)306 f.close()307 data['fullscreen'] = fullscreenval308 data['resolution'] = newres309 f = open("./resources/data/settings.json", "w")310 json.dump(data, f)311 f.close()312 active = False313 startMenu(0)314 elif selected == 1:315 menusound.play()316 active = False317 startMenu(0)318 elif event.key == K_DOWN or event.key == K_s:319 if selected < 1:320 menusound.play()321 selected = selected + 1322 elif selected == 1:323 menusound.play()324 selected = 0325 elif event.key == K_UP or event.key == K_w:326 if selected > 0:327 menusound.play()328 selected = selected - 1329 elif selected == 0:330 menusound.play()331 selected = 1332 #gametick and display updater333 pygame.display.update()334 mainClock.tick(60)335336def start(selected):337 #define vars338 active = True339 difficulties = ['E A S Y', 'M E D I U M', 'H A R D', 'I M P O S S I B L E', 'easy', 'medium', 'hard', 'impossible']340 index = 0341 while active:342 #create background343 screen.fill((0,0,0))344 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))345 draw_text('DIFFICULTY', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))346 if selected == 0:347 draw_text('>'+difficulties[index]+'<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.95))348 draw_text('BACK', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.65))349 elif selected == 1:350 draw_text(difficulties[index+4], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))351 draw_text('>B A C K<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.65))352 #event handler353 for event in pygame.event.get():354 if event.type == KEYDOWN:355 if event.key == K_RETURN or event.key == K_SPACE:356 if selected == 0:357 menusound.play()358 active = False359 play(index)360 elif selected == 1:361 menusound.play()362 active = False363 startMenu(0)364 elif event.key == K_RIGHT or event.key == K_d:365 if selected == 0:366 if index < 3:367 menusound.play()368 index = index +1369 elif index == 3:370 menusound.play()371 index = 0372 elif event.key == K_LEFT or event.key == K_a:373 if selected == 0:374 if index > 0:375 menusound.play()376 index = index - 1377 elif index == 0:378 menusound.play()379 index = 3380 elif event.key == K_DOWN or event.key == K_s:381 if selected < 1:382 menusound.play()383 selected = selected + 1384 elif selected == 1:385 menusound.play()386 selected = 0387 elif event.key == K_UP or event.key == K_w:388 if selected > 0:389 menusound.play()390 selected = selected - 1391 elif selected == 0:392 menusound.play()393 selected = 1394 #gametick and display updater395 pygame.display.update()396 mainClock.tick(60)397398def spawn():399 #return array consisting of random word from file, random color as well as random x and y coordinates400 word = linecache.getline('./resources/data/words.txt', random.randint(1, line_count)).rstrip('\n')401 return [pygame.font.Font("./resources/fonts/Inlanders.otf", 60).render(word, 1, (randrange(255),randrange(255),255)), randrange(screensize[0]-500), (randrange(800)*-1), word]402403def play(difficulty):404 #define vars405 active = True406 enemies = []407 health = 3408 score = 0409 typed = ""410 spawnspeed = int(10000/(int(difficulty)+1))411 scrollspeed = 1412 #create event timer413 SPAWNEVENT = pygame.USEREVENT+1414 pygame.time.set_timer(SPAWNEVENT, spawnspeed)415 enemies.append(spawn())416 while active:417 #create background418 screen.fill((0,0,0))419 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))420 #draw stats and heads-up display421 draw_text("Health: "+str(health), font(60), (255,51,0), screen, (screensize[0]/10), (screensize[1]/8))422 draw_text("Score: "+str(score), font(60), (255,51,0), screen, (screensize[0]/10), (screensize[1]/15))423 draw_text(">"+typed, font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.1))424 #animate enemies425 for i in range(len(enemies)):426 screen.blit(enemies[i][0], (enemies[i][1],enemies[i][2]))427 enemies[i][2]+=scrollspeed428 #check if enemy passed screen429 if enemies[i][2] > screensize[1]+100:430 #if enemy passed screen, reset speed, clear all enemies, play hit sound and remove health431 hitsound.play()432 enemies = []433 spawnspeed = int(10000/(int(difficulty)+1))434 scrollspeed = 1435 health -= 1436 break437 #check if game lost438 if health <= -1:439 #game lost, switch to save score menu and pass final score440 active = False441 savescore(score, difficulty)442 #event handler443 for event in pygame.event.get():444 if event.type == SPAWNEVENT:445 enemies.append(spawn())446 elif event.type == KEYDOWN:447 if event.key == K_ESCAPE:448 active = False449 startMenu(0)450 elif event.key == K_RETURN:451 #check if typed word is an enemy452 for n in range(len(enemies)):453 if typed == enemies[n][3]:454 #remove enemy, increase spawn and scroll speeds, add score and play kill sound455 killsound.play()456 enemies.pop(n)457 score += 100458 spawnspeed -= randrange(10)459 scrollspeed += ((difficulty/10000)+0.05)460 pygame.time.set_timer(SPAWNEVENT, spawnspeed)461 break462 #reset typed word463 typed = ""464 elif event.key == K_BACKSPACE:465 typed = typed[:-1]466 else:467 typed += event.unicode468 #gametick and display updater469 pygame.display.update()470 mainClock.tick(60)471472def savescore(score, difficulty):473 active = True474 f = open("./resources/data/scores.json", "r")475 data = json.load(f)476 f.close()477 pushDownAmount = 0478 difficulties = ['easy', 'medium', 'hard', 'impossible']479 selected = 0480 newscore = False481 setname = False482 name = ""483 for obj in data[difficulties[difficulty]]:484 if score > data[difficulties[difficulty]][obj]['score']:485 pushDownAmount = int(obj)486 break487 while active:488 #create background489 screen.fill((0,0,0))490 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))491 #check if new high-score492 if pushDownAmount == 0:493 draw_text('GAME OVER', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))494 draw_text('>B A C K<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.95))495 else:496 draw_text('GAME OVER', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))497 draw_text('NEW HIGH-SCORE!', font(80), (255,255,255), screen, (screensize[0]/2), (screensize[1]/4))498 draw_text('ENTER YOUR NAME', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.3))499 if selected == 0:500 draw_text('>'+name, font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.95))501 draw_text('SAVE', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.75))502 elif selected == 1:503 draw_text(name, font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.95))504 draw_text('>S A V E<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.75))505 newscore = True506 #event handler507 for event in pygame.event.get():508 if event.type == KEYDOWN:509 if event.key == K_RETURN or event.key == K_SPACE:510 if newscore == False:511 active = False512 startMenu(0)513 else:514 if selected == 0:515 setname = True516 if selected == 1:517 pushDownAmount = int(pushDownAmount)518 if pushDownAmount == 1:519 data[difficulties[difficulty]]["5"]['score'] = data[difficulties[difficulty]]["4"]['score']520 data[difficulties[difficulty]]["5"]['name'] = data[difficulties[difficulty]]["4"]['name']521 data[difficulties[difficulty]]["4"]['score'] = data[difficulties[difficulty]]["3"]['score']522 data[difficulties[difficulty]]["4"]['name'] = data[difficulties[difficulty]]["3"]['name']523 data[difficulties[difficulty]]["3"]['score'] = data[difficulties[difficulty]]["2"]['score']524 data[difficulties[difficulty]]["3"]['name'] = data[difficulties[difficulty]]["2"]['name']525 data[difficulties[difficulty]]["2"]['score'] = data[difficulties[difficulty]]["1"]['score']526 data[difficulties[difficulty]]["2"]['name'] = data[difficulties[difficulty]]["1"]['name']527 data[difficulties[difficulty]]["1"]['score'] = score528 data[difficulties[difficulty]]["1"]['name'] = name529 elif pushDownAmount == 2:530 data[difficulties[difficulty]]["5"]['score'] = data[difficulties[difficulty]]["4"]['score']531 data[difficulties[difficulty]]["5"]['name'] = data[difficulties[difficulty]]["4"]['name']532 data[difficulties[difficulty]]["4"]['score'] = data[difficulties[difficulty]]["3"]['score']533 data[difficulties[difficulty]]["4"]['name'] = data[difficulties[difficulty]]["3"]['name']534 data[difficulties[difficulty]]["3"]['score'] = data[difficulties[difficulty]]["2"]['score']535 data[difficulties[difficulty]]["3"]['name'] = data[difficulties[difficulty]]["2"]['name']536 data[difficulties[difficulty]]["2"]['score'] = score537 data[difficulties[difficulty]]["2"]['name'] = name538 elif pushDownAmount == 3:539 data[difficulties[difficulty]]["5"]['score'] = data[difficulties[difficulty]]["4"]['score']540 data[difficulties[difficulty]]["5"]['name'] = data[difficulties[difficulty]]["4"]['name']541 data[difficulties[difficulty]]["4"]['score'] = data[difficulties[difficulty]]["3"]['score']542 data[difficulties[difficulty]]["4"]['name'] = data[difficulties[difficulty]]["3"]['name']543 data[difficulties[difficulty]]["3"]['score'] = score544 data[difficulties[difficulty]]["3"]['name'] = name545 elif pushDownAmount == 4:546 data[difficulties[difficulty]]["5"]['score'] = data[difficulties[difficulty]]["4"]['score']547 data[difficulties[difficulty]]["5"]['name'] = data[difficulties[difficulty]]["4"]['name']548 data[difficulties[difficulty]]["4"]['score'] = score549 data[difficulties[difficulty]]["4"]['name'] = name550 elif pushDownAmount == 4:551 data[difficulties[difficulty]]["5"]['score'] = score552 data[difficulties[difficulty]]["5"]['name'] = name553 f = open("./resources/data/scores.json", "w")554 json.dump(data, f)555 f.close()556 setname = False557 active = False558 startMenu(0)559 elif event.key == K_DOWN:560 if selected < 1:561 menusound.play()562 selected = selected + 1563 elif selected == 1:564 menusound.play()565 selected = 0566 elif event.key == K_UP:567 if selected > 0:568 menusound.play()569 selected = selected - 1570 elif selected == 0:571 menusound.play()572 selected = 1573 elif event.key == K_BACKSPACE:574 name = name[:-1]575 else:576 if len(name) < 3:577 name += event.unicode578 #gametick and display updater579 pygame.display.update()580 mainClock.tick(60)581582 583def leaderboards(selected):584 active = True585 f = open("./resources/data/scores.json", "r")586 data = json.load(f)587 f.close()588 difficulties = ['E A S Y', 'M E D I U M', 'H A R D', 'I M P O S S I B L E', 'easy', 'medium', 'hard', 'impossible']589 difficultiesNonText = ['easy', 'medium', 'hard', 'impossible']590 index = 0591 while active:592 #create background593 screen.fill((0,0,0))594 screen.blit(pygame.transform.scale(bg, screensize), (0, 0))595 #title and table key setup596 draw_text('LEADRBOARDS', font(150), (255,255,255), screen, (screensize[0]/2), (screensize[1]/8))597 draw_text('RANK', font(80), (255,255,255), screen, (screensize[0]/3), (screensize[1]/4))598 draw_text('NAME', font(80), (255,255,255), screen, (screensize[0]/2), (screensize[1]/4))599 draw_text('SCORE', font(80), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/4))600 #display scores601 draw_text('1st', font(60), (255,255,255), screen, (screensize[0]/3), (screensize[1]/3))602 draw_text(data[difficultiesNonText[index]]["1"]["name"], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/3))603 draw_text(str(data[difficultiesNonText[index]]["1"]["score"]), font(60), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/3))604 draw_text('2nd', font(60), (255,255,255), screen, (screensize[0]/3), (screensize[1]/2.4))605 draw_text(data[difficultiesNonText[index]]["2"]["name"], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2.4))606 draw_text(str(data[difficultiesNonText[index]]["2"]["score"]), font(60), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/2.4))607 draw_text('3rd', font(60), (255,255,255), screen, (screensize[0]/3), (screensize[1]/2))608 draw_text(data[difficultiesNonText[index]]["3"]["name"], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/2))609 draw_text(str(data[difficultiesNonText[index]]["3"]["score"]), font(60), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/2))610 draw_text('4th', font(60), (255,255,255), screen, (screensize[0]/3), (screensize[1]/1.7))611 draw_text(data[difficultiesNonText[index]]["4"]["name"], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.7))612 draw_text(str(data[difficultiesNonText[index]]["4"]["score"]), font(60), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/1.7))613 draw_text('5th', font(60), (255,255,255), screen, (screensize[0]/3), (screensize[1]/1.5))614 draw_text(data[difficultiesNonText[index]]["5"]["name"], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.5))615 draw_text(str(data[difficultiesNonText[index]]["5"]["score"]), font(60), (255,255,255), screen, (screensize[0]/1.5), (screensize[1]/1.5))616617 #change mode scores618 if selected == 0:619 draw_text('>'+difficulties[index]+'<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.3))620 draw_text('BACK', font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.2))621 elif selected == 1:622 draw_text(difficulties[index+4], font(60), (255,255,255), screen, (screensize[0]/2), (screensize[1]/1.3))623 draw_text('>B A C K<', font(60), (255,51,0), screen, (screensize[0]/2), (screensize[1]/1.2))624 #event handler625 for event in pygame.event.get():626 if event.type == KEYDOWN:627 if event.key == K_RETURN or event.key == K_SPACE:628 if selected == 1:629 menusound.play()630 active = False631 startMenu(0)632 elif event.key == K_RIGHT or event.key == K_d:633 if selected == 0:634 if index < 3:635 menusound.play()636 index = index +1637 elif index == 3:638 menusound.play()639 index = 0640 elif event.key == K_LEFT or event.key == K_a:641 if selected == 0:642 if index > 0:643 menusound.play()644 index = index - 1645 elif index == 0:646 menusound.play()647 index = 3648 elif event.key == K_DOWN or event.key == K_s:649 if selected < 1:650 menusound.play()651 selected = selected + 1652 elif selected == 1:653 menusound.play()654 selected = 0655 elif event.key == K_UP or event.key == K_w:656 if selected > 0:657 menusound.play()658 selected = selected - 1659 elif selected == 0:660 menusound.play()661 selected = 1662 #gametick and display updater663 pygame.display.update()664 mainClock.tick(60)665 666#start game
...
MainMenu.py
Source:MainMenu.py
1'''2Created on 07/02/201334@author: Simon5'''6#from zModule import * #includes pygame, os, sys and pygame.locals7import pygame, os8import sys910class MainMenu:1112 def __init__(self):13 pathWork = os.getcwd()14 pathMenu = os.path.join(pathWork, os.path.join("images","menu"))15 self.pathPapers = os.path.join(pathMenu, "papers")16 self.background = pygame.image.load(os.path.join(pathMenu, "background.png"))1718 self.Clock = pygame.time.Clock()19 self.timer = 020 self.aniTimer = 021 self.aniRunning = True2223 self.menuItems = {}24 self.current = 025 self.following = 126 self.sprites = pygame.sprite.RenderUpdates()27# self.set_items()28 self.initiative = True29 self.screenSize = (0,0)30 print "Finished initializing MainMenu..."3132 def controller(self, screen, event):33 screenSize = screen.get_size()34 tick = self.Clock.tick()35 self.timer += tick36 updates = []37 if self.initiative:38 self.menuItems[0].rect.topleft = [0,0]39 self.menuItems[0].rect = self.menuItems[0].rect.move(screenSize[0]*0.5-self.menuItems[0].rect.width*0.5,screenSize[1]*0.06)40 self.sprites.add(self.menuItems[0])41 self.sprites.clear(screen, self.bg)42 updates += self.sprites.draw(screen)43 self.initiative = False44 if self.aniRunning and self.timer >= 2000:45 self.animation(tick, screenSize, self.current, self.following)46 self.sprites.add(self.menuItems[self.current])47 self.sprites.add(self.menuItems[self.following])48 self.sprites.clear(screen, self.bg)49 updates += self.sprites.draw(screen)5051 pygame.display.update(updates)52 return screen5354 def set_items(self, screenSize = (800,600)):55 self.sprites.empty()56 counter = 057 for element in os.listdir(self.pathPapers):58 path = os.path.join(self.pathPapers, element)59 element = pygame.image.load(path)60 size = element.get_size()61 ratio = size[0]/float(size[1])62 height = int(screenSize[1]-(screenSize[1]*0.1))63 width = int(height * ratio)64 element = pygame.transform.smoothscale(element, (width, height))65 sprite = pygame.sprite.Sprite()66 sprite.image = element67 sprite.rect = sprite.image.get_rect()68 try:69 ratio2 = (self.menuItems[counter].rect[0]+self.screenSize[0])/float(self.menuItems[counter].rect[0])70 sprite.rect[0] = screenSize[0]/ratio271 sprite.rect[1] = screenSize[1]*0.0672 except:73 print "error"74 sprite.rect = sprite.rect.move(screenSize[0],screenSize[1]*0.06)75 self.menuItems[counter] = sprite76 counter += 177# self.initiative = True78 self.screenSize = screenSize7980 def animation(self, tick, screenSize, current, following):81 curSprite = self.menuItems[current]82 folSprite = self.menuItems[following]83 curSprite.rect = curSprite.rect.move(-screenSize[0]*3*(tick/1000.0), 0)84 folSprite.rect = folSprite.rect.move(-screenSize[0]*3*(tick/1000.0), 0)85 self.menuItems[current] = curSprite86 self.menuItems[following] = folSprite87 left = folSprite.rect.topleft[0]88 width = folSprite.rect.width89 if left <= (screenSize[0]*0.5)-(width*0.5):90 folSprite.rect = folSprite.rect.move((left-(screenSize[0]*0.5-width*0.5))*-1,0)91 self.aniRunning = False9293 def set_background(self, screen, refresh=False):94 if refresh:95 size = screen.get_size()96 print size97 self.bg = pygame.transform.smoothscale(self.background, size)98 screen.blit(self.bg, (0,0))99 return screen100 try:101 self.bg102 return True103 except:104 size = screen.get_size()105 self.bg = pygame.transform.smoothscale(self.background, size)106 return False107108109110# def controller(self, screen, event):111# pygame.mouse.set_visible(True)112# screenSize = list(screen.get_size())113# size = list(self.background.get_size())114# if screenSize[0] != size[0] or screenSize[1] != size[1]:115# self.bgresize = pygame.transform.smoothscale(self.background, screenSize)116# screen.blit(self.bgresize, (0,0))117# screen = self.draw_paper(screen)118# return screen119#120# def draw_paper(self, screen):121# screenSize = list(screen.get_size())122# size = list(self.texture1.get_size())123# if size[1] != int(screenSize[1]*0.7):124# y = int(screenSize[1]*0.7)125# ratio = float(size[0]*0.7)/size[1]126# x = size[0]*ratio127# self.tx1resize = pygame.transform.smoothscale(self.texture1, (x,y))128# size = list(self.tx1resize.get_size())129# halfsize = [size[0]*0.5, size[1]*0.5]130# mid = [screenSize[0]*0.5 - halfsize[0], screenSize[1]*0.5 - halfsize[1]]131# screen.blit(self.tx1resize, (mid))
...
pygamewithgui.py
Source:pygamewithgui.py
1import pygame2from pygame import *3import random as r 4import time, sys5pygame.init()6RUNNING = True7DISPLAY_SIZE = pygame.display.get_desktop_sizes()[0]8LIST_DISPLAY_SIZE = list(DISPLAY_SIZE)9DISPLAYSURF = pygame.display.set_mode(tuple(map(lambda i, j: i - j, DISPLAY_SIZE, (2,60))),pygame.RESIZABLE)10SCREENSIZE = DISPLAYSURF.get_size()11FONT = pygame.font.SysFont('Tahoma',int((SCREENSIZE[0]+SCREENSIZE[1])/40),False,False)12WHITE = pygame.Color(255,255,255) 13BLACK = pygame.Color(0,0,0)14TIMEDELAY = pygame.time.get_ticks()15ESC = False16HOVER = False17playerpos = (0,int(SCREENSIZE[1]/20))18DELAY2 = pygame.time.get_ticks()19movementdistx = 3520movementdisty = 3521movementspd = 10022collectables = []23def update():24 global HOVER, RUNNING, pressed_keys, playerpos, DELAY2, movementdist, movementspd, kpl, collectables25 SCREENSIZE = DISPLAYSURF.get_size()26 27 pressed_keys = pygame.key.get_pressed()28 if pressed_keys[K_a] and pygame.time.get_ticks()>=DELAY2+movementspd and playerpos[0]>=movementdistx:29 DELAY2 = pygame.time.get_ticks()30 playerpos = (playerpos[0]-movementdistx,playerpos[1])31 if pressed_keys[K_d] and pygame.time.get_ticks()>=DELAY2+movementspd and playerpos[0]<=SCREENSIZE[0]-movementdistx:32 DELAY2 = pygame.time.get_ticks()33 playerpos = (playerpos[0]+movementdistx,playerpos[1])34 if pressed_keys[K_s] and pygame.time.get_ticks()>=DELAY2+movementspd and playerpos[1]<=SCREENSIZE[1]-movementdisty:35 DELAY2 = pygame.time.get_ticks()36 playerpos = (playerpos[0],playerpos[1]+movementdisty)37 if pressed_keys[K_w] and pygame.time.get_ticks()>=DELAY2+movementspd and playerpos[1]>=int(SCREENSIZE[1]/20)+movementdisty:38 DELAY2 = pygame.time.get_ticks()39 playerpos = (playerpos[0],playerpos[1]-movementdisty)40 41 if playerpos[0]>SCREENSIZE[0]-25: playerpos = (playerpos[0]-25,playerpos[1])42 if playerpos[1]>SCREENSIZE[1]-35: playerpos = (playerpos[0],playerpos[1]-35)43 44 DISPLAYSURF.fill(WHITE)45 pygame.draw.rect(DISPLAYSURF,pygame.Color(127,127,127),(0,0,SCREENSIZE[0],int(SCREENSIZE[1]/20)),0)46 47 pygame.draw.rect(DISPLAYSURF,pygame.Color(255,0,0),(playerpos[0]+5,playerpos[1],15,15),0)48 pygame.draw.rect(DISPLAYSURF,pygame.Color(0,255,0),(playerpos[0],playerpos[1]+10,5,15),0)49 pygame.draw.rect(DISPLAYSURF,pygame.Color(0,255,0),(playerpos[0]+20,playerpos[1]+10,5,15),0)50 pygame.draw.rect(DISPLAYSURF,pygame.Color(255,255,0),(playerpos[0]+5,playerpos[1]+15,7.5,20),0)51 pygame.draw.rect(DISPLAYSURF,pygame.Color(0,255,255),(playerpos[0]+12.5,playerpos[1]+15,8,20),0)52 53 # collectables54 if len(collectables)<1:55 collectables.append([r.randrange(0,SCREENSIZE[0],25),r.randrange(int(SCREENSIZE[1]/20),SCREENSIZE[1],35)])56 [pygame.draw.rect(DISPLAYSURF,pygame.Color(255,0,0),(i[0],i[1],25,35),0) for i in collectables]57 58 [collectables.remove(i) if playerpos[0]>i[0]-30 and playerpos[0]<i[0]+25 and playerpos[1]>i[1]-15 and playerpos[1]<i[1]+35 else "" for i in collectables]59 60 if ESC:61 if not HOVER:62 FONT = pygame.font.SysFont('Tahoma',int((SCREENSIZE[0]+SCREENSIZE[1])/40),False,False)63 pygame.draw.rect(DISPLAYSURF, pygame.Color(100,100,100), (2/6*SCREENSIZE[0],SCREENSIZE[1]/2-int(SCREENSIZE[1]/20),2/6*SCREENSIZE[0],SCREENSIZE[1]/10),0)64 buttontext = FONT.render("Escape",True,(0,0,0))65 DISPLAYSURF.blit(buttontext, (2/6*SCREENSIZE[0]+2/24*SCREENSIZE[0],SCREENSIZE[1]/2-int(SCREENSIZE[1]/20)))66 MOUSELOCATION = pygame.mouse.get_pos()67 if MOUSELOCATION[0]>2/6*SCREENSIZE[0] and MOUSELOCATION[0]<2/6*SCREENSIZE[0]+2/6*SCREENSIZE[0] and MOUSELOCATION[1]>SCREENSIZE[1]/2-int(SCREENSIZE[1]/20) and MOUSELOCATION[1]<SCREENSIZE[1]/2-int(SCREENSIZE[1]/20)+SCREENSIZE[1]/10:68 HOVER = True69 if HOVER:70 FONT = pygame.font.SysFont('Tahoma',int((SCREENSIZE[0]+SCREENSIZE[1])/35),False,False)71 pygame.draw.rect(DISPLAYSURF, pygame.Color(100,100,100), (5/18*SCREENSIZE[0],SCREENSIZE[1]/2-SCREENSIZE[1]/15,8/18*SCREENSIZE[0],SCREENSIZE[1]*2/15),0)72 buttontext = FONT.render("Escape",True,(0,0,0))73 DISPLAYSURF.blit(buttontext, (2/6*SCREENSIZE[0]+2/24*SCREENSIZE[0],SCREENSIZE[1]/2-int(SCREENSIZE[1]/20)))74 MOUSELOCATION = pygame.mouse.get_pos()75 if not (MOUSELOCATION[0]>5/18*SCREENSIZE[0] and MOUSELOCATION[0]<5/18*SCREENSIZE[0]+3/18*SCREENSIZE[0] and MOUSELOCATION[1]>SCREENSIZE[1]/2-SCREENSIZE[1]/15 and MOUSELOCATION[1]<SCREENSIZE[1]/2-SCREENSIZE[1]/15+SCREENSIZE[1]*2/15):76 HOVER = False77 for event in pygame.event.get():78 if event.type == MOUSEBUTTONDOWN: 79 RUNNING = False80 pygame.display.update()81while RUNNING:82 pressed_keys = pygame.key.get_pressed()83 for event in pygame.event.get(): 84 if event.type == pygame.QUIT: RUNNING = False85 if pressed_keys[K_ESCAPE] and not ESC and pygame.time.get_ticks()>TIMEDELAY+500: 86 ESC = True87 TIMEDELAY = pygame.time.get_ticks()88 if pressed_keys[K_ESCAPE] and ESC and pygame.time.get_ticks()>TIMEDELAY+500: 89 ESC = False90 TIMEDELAY = pygame.time.get_ticks()91 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!