def mainloop(self): print "MAIN LOOP" # satan machine for game while self.state is not QUIT: if self.state == MENU: print "MAIN MENU" options = [menu.Item("CBZT"), menu.Item(" "), menu.Option(SINGLEPLAYER,"SINGLE PLAYER",True), menu.Option(MULTIPLAYER,"MULTIPLAYER"), menu.Option(INSTRUCTIONS,"INSTRUCTIONS"), menu.Option(QUIT,"QUIT")] self.state = menu.launch(self.screen,options) elif self.state == SINGLEPLAYER: print "SINGLE PLAYER GAME" try: singleplayer.SinglePlayer(self.screen) except EndGame, e: print e.msg self.state = MENU elif self.state == MULTIPLAYER: print "MULTIPLAYER MENU" options = [menu.Item("MULTIPLAYER"), menu.Item(" "), menu.Option(MULTIPLAYER_LOCAL,"LOCAL",True), #menu.Option(HOST,"HOST",True), #menu.Option(CONNECT,"CONNECT"), menu.Option(MENU,"MAIN MENU")] self.state = menu.launch(self.screen,options)
def play(fps): # Set the width and height of the window width, height = 640, 480 # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Set pressed keys keys = [False, False, False, False] # Set player position playerpos=[100,100] # Make an list for the accuracy acc=[0,0] # Make an list for where the arrows are arrows=[] # Set the timer for spawning badgers badtimer=100 badtimer1=0 # Make an list for where the badgers are badguys=[[800,100]] # Set your health value healthvalue=194 # Set the wait times waitforexit=0 waitforarrows=0 waitforballoons=0 waitforballoons2=2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Set start ticks startticks = pygame.time.get_ticks() # Set title pygame.display.set_caption("Bunny and Badgers") # Load images # Load the players image player = pygame.image.load("resources/images/dude.png").convert_alpha() # Load the background image grass = pygame.image.load("resources/images/grass.png").convert() # Load the image of the castles castle = pygame.image.load("resources/images/castle.png").convert_alpha() # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png").convert_alpha() # Load the image for the badgers badguyimg1 = pygame.image.load("resources/images/badguy.png").convert_alpha() badguyimg2 = pygame.image.load("resources/images/badguy2.png").convert_alpha() badguyimg3 = pygame.image.load("resources/images/badguy3.png").convert_alpha() badguyimg4 = pygame.image.load("resources/images/badguy4.png").convert_alpha() badguyimg = badguyimg1 # Load the overlays greenoverlay = pygame.image.load("resources/images/greenoverlay.png").convert_alpha() redoverlay = pygame.image.load("resources/images/redoverlay.png").convert_alpha() # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png").convert_alpha() health = pygame.image.load("resources/images/health.png").convert_alpha() # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png").convert_alpha() balloon2 = pygame.image.load("resources/images/balloon2.png").convert_alpha() # Set positions castle1 = (0,height/16) castle2 = (0,height/3.5) castle3 = (0,height/2) castle4 = (0,height/1.4) # Create a clock clock = pygame.time.Clock() # Keep looping through running = 1 exitcode = 0 while running: badtimer-=1 # Draw the background for x in range(width/grass.get_width()+1): for y in range(height/grass.get_height()+1): screen.blit(grass,(x*100,y*100)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation if True: position = pygame.mouse.get_pos() angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) playerrot = pygame.transform.rotate(player, 360-angle*57.29) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) # Draw arrows for bullet in arrows: index=0 velx=math.cos(bullet[0])*10 vely=math.sin(bullet[0])*10 bullet[1]+=velx bullet[2]+=vely if bullet[1]<-64 or bullet[1]>width or bullet[2]<-64 or bullet[2]>height: arrows.pop(index) index+=1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) screen.blit(arrow1, (projectile[1], projectile[2])) # Change the image of the badgers if badguyimg == badguyimg1: badguyimg = badguyimg2 elif badguyimg == badguyimg2: badguyimg = badguyimg3 elif badguyimg == badguyimg3: badguyimg = badguyimg4 elif badguyimg == badguyimg4: badguyimg = badguyimg1 # Draw badgers if badtimer==0: badheight1 = height/9.6 badheight2 = height/1.1 badheight = random.randint(int(badheight1), int(badheight2)) badguys.append([width, badheight]) badtimer=100-(badtimer1*2) if badtimer1>=35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy[0]<-64: badguys.pop(index) badguy[0]-=7 # Attack castle badrect=pygame.Rect(badguyimg.get_rect()) badrect.top=badguy[1] badrect.left=badguy[0] if badrect.left<64: healthvalue -= random.randint(5,20) badguys.pop(index) # Check for collisions index1=0 for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if badrect.colliderect(bullrect): acc[0]+=1 badguys.pop(index) arrows.pop(index1) index1+=1 # Next bad guy index+=1 # Draw badgers for badguy in badguys: screen.blit(badguyimg, badguy) # Draw clock font = pygame.font.Font("freesansbold.ttf", 24) survivedtext = font.render(str((90000-pygame.time.get_ticks()+startticks)/60000)+":"+str((90000-pygame.time.get_ticks()+startticks)/1000%60).zfill(2), True, (0,0,0)) textRect = survivedtext.get_rect() textRect.topright=[width-5, 5] screen.blit(survivedtext, textRect) # Draw health bar screen.blit(healthbar, (5,5)) for health1 in range(healthvalue): screen.blit(health, (health1+8,8)) # Loop through the events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: # Move up if event.key in (K_w, K_UP): keys[0]=True # Move left elif event.key in (K_a, K_LEFT): keys[1]=True # Move down elif event.key in (K_s, K_DOWN): keys[2]=True # Move right elif event.key in (K_d, K_RIGHT): keys[3]=True # Quit by pressing back elif event.key==K_AC_BACK: menu.launch() if event.type == pygame.KEYUP: # Move up if event.key in (K_w, K_UP): keys[0]=False # Move left elif event.key in (K_a, K_LEFT): keys[1]=False # Move down elif event.key in (K_s, K_DOWN): keys[2]=False # Move right elif event.key in (K_d, K_RIGHT): keys[3]=False # Check if you pressed a mouse button for shooting arrows if event.type==pygame.MOUSEBUTTONDOWN: if waitforarrows == 0: position=pygame.mouse.get_pos() acc[1]+=1 arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32]) # Set wait time for arrows in frames waitforarrows=15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 if waitforarrows: waitforarrows-=1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons-=1 if balloon1display: screen.blit(balloon1, (playerpos[0]+10, playerpos[1]-60)) elif balloon2display: screen.blit(balloon2, (playerpos[0]+10, playerpos[1]-60)) else: balloon1display = False balloon2display = False # Move player # Up if keys[0]: playerpos[1]-=5 # Down elif keys[2]: playerpos[1]+=5 # Left if keys[1]: playerpos[0]-=5 # Right elif keys[3]: playerpos[0]+=5 # Win/Lose check # Win if (pygame.time.get_ticks()-startticks)>=90000: running=0 exitcode=1 # Lose if healthvalue<=0: running=0 exitcode=0 if acc[1]!=0: accuracy=acc[0]*1.0/acc[1]*100 else: accuracy=0 # Flip the display pygame.display.flip() # Lock fps clock.tick(fps) # Win/lose display # Lose if exitcode==0: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text gameover = bigfont.render("Game over!", True, (255,0,0)) gameoverRect = gameover.get_rect() gameoverRect.centerx = screen.get_rect().centerx gameoverRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw red overlay for x in range(width/redoverlay.get_width()+1): for y in range(height/redoverlay.get_height()+1): screen.blit(redoverlay,(x*100,y*100)) # Draw text screen.blit(gameover, gameoverRect) screen.blit(text, textRect) # Win else: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text youwin = bigfont.render("You win!", True, (0,255,0)) youwinRect = youwin.get_rect() youwinRect.centerx = screen.get_rect().centerx youwinRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw green overlay for x in range(width/greenoverlay.get_width()+1): for y in range(height/greenoverlay.get_height()+1): screen.blit(greenoverlay,(x*100,y*100)) # Draw text screen.blit(youwin, youwinRect) screen.blit(text, textRect) # Exit automatic when the game is stopped while 1: waitforexit+=1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if waitforexit == 1000: menu.launch() # Update the screen pygame.display.flip()
self.age = 0 def update(self, target_list, same_species_list): self.procreate(same_species_list) self.decide(target_list) Predator.update(self) self.image.fill((int(50 + 205*(1 - self.age / PREDATOR_LIFE_TIME)), 0, 0)) # Initialize PyGame pygame.init() pygame.display.set_caption(GAME_TITLE) screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # Launches an introductory menu menu.launch(screen) fish_list = pygame.sprite.Group() predator_list = pygame.sprite.Group() for i in range(N_FISH_START): fish = Fish() fish_list.add(fish) for i in range(N_PREDATOR_START): if np.random.uniform() > 0.5: predator = Dolphin() else: predator = Shark() predator_list.add(predator)
def play(): detector = dlib.get_frontal_face_detector() # Set the width and height of the window width, height = int(pygame.display.Info().current_w), int(pygame.display.Info().current_h) # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Initial camera cap = cv2.VideoCapture(0) # or 1 imRawWidth = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) imRawHeight = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) imWidth = 1080 #640 #360 imHeight = 960 #480 #240 cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, imWidth) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, imHeight) #imWidth = imRawWidth #imHeight = imRawHeight # Set playing time gaming_time = 90000 # Set level state level = 0 moving_speed = [5,7,9] # original: [3,5,7] score_factor = [1,2,3] candy_size_factor = [0.7,0.5,0.3] shit_size_factor = [0.2,0.3,0.4] # [0.2,0.3,0.5] leveltxt = ['EASY','HARD','CRAZY!!!'] # Make an list for the accuracy acc=[0,0,0] loss=[0,0,0] _color=(255,0,0) # Set your health value healthvalue=[194,194,194] # 194 blood_loss=20 # Set pressed keys keys = [False, False, False, False] # Flag for change player skin playerbadflag = 0 # Make an list for where the arrows are arrows=[] # Set the timer for spawning badgers badtimer=100 badtimer1=0 candytimer=100 candytimer1=0 # Make an list for where the badgers are badguys=[[800,100]] candies=[[800,100]] # Set the wait times waitforexit=0 waitforarrows=3 # 0 waitforballoons=0 waitforballoons2=2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Initialize the mixer (for sound) pygame.mixer.init() # Set title pygame.display.set_caption("Candy Mountain") # Load images # Load the background image grass = pygame.image.load("resources/images/BckGnd.jpg") #grass.png") # add at front grass = pygame.transform.scale(grass, (width, height)) # Load the image of the castles castle = pygame.image.load("resources/images/castle.png") # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png") # Load the image for the badgers badguyimg = pygame.image.load("resources/images/poopoo.png") #badguy.png") # Load the image for the candies candyimg = pygame.image.load("resources/images/candy.png") #badguy.png") # Load the overlays greenoverlay = pygame.image.load("resources/images/Win.jpg") #greenoverlay.png") redoverlay = pygame.image.load("resources/images/GameOver.jpg") #redoverlay.png") greenoverlay = pygame.transform.scale(greenoverlay, (width, height)) redoverlay = pygame.transform.scale(redoverlay, (width, height)) # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png") health = pygame.image.load("resources/images/health.png") # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png") balloon2 = pygame.image.load("resources/images/balloon2.png") # Load audio hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/ohShit.wav") #enemy.wav") candySound = pygame.mixer.Sound("resources/audio/candy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") takePicture = pygame.mixer.Sound("resources/audio/takePic.wav") loseGame = pygame.mixer.Sound("resources/audio/loseGame.wav") winGame = pygame.mixer.Sound("resources/audio/winGame.wav") # Set the audio volume hit.set_volume(0.40) enemy.set_volume(0.60) candySound.set_volume(0.40) shoot.set_volume(0.40) takePicture.set_volume(0.60) loseGame.set_volume(0.60) winGame.set_volume(0.60) # Set the background music pygame.mixer.music.load('resources/audio/mix90.mp3') #level_easy.mp3') #background.mp3') pygame.mixer.music.set_volume(0.50) # Set positions castle1 = (2*width/16, height-150) #castle1 = (0,height/16) castle2 = (6*width/16, height-150) #castle2 = (0,height/3.5) castle3 = (10*width/16, height-150) #castle3 = (0,height/2) castle4 = (14*width/16, height-150) #castle4 = (0,height/1.4) # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Capture frame-by-frame setting = 1 roi = [] _P,_Q,_R,_S = 0,0,0,0 while(setting): ret, frame = cap.read() img = frame.copy() gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # face detection faces = detector(img) for d in faces: #print "left,top,right,bottom:", d.left(), d.top(), d.right(), d.bottom() _P,_Q,_R,_S = d.left(), d.top(), d.right()-d.left(), d.bottom()-d.top() cv2.rectangle(img,(_P,_Q),(_P+_R,_Q+_S),(255,0,0),2) # set up the ROI for tracking roi = img[_Q:_Q+_S, _P:_P+_R] # Draw the background screen.blit(grass,(0,0)) ba = getFrame(True,cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) screen.blit(ba,(width/2-400,height/2-300)) # Flip the display pygame.display.flip() # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type == pygame.KEYDOWN: # select if event.key==K_s: takePicture.play() print "Selecting" setting = 0 # Load the players image player = getFrame(True,roi.copy()) #frame.copy()) playerBad = pygame.image.load("resources/images/shitFaceJustin.png") mainChar = player # Set player position playerpos = [width/2,height/2] faceCenter = playerpos # Keep looping through running = 1 exitcode = 0 # Set start ticks startticks = pygame.time.get_ticks() pygame.mixer.music.play(0, 0.0) while running: # Capture frame-by-frame ret, frame = cap.read() img = frame.copy() # Detect face faces = detector(img) for d in faces: #print "left,top,right,bottom:", d.left(), d.top(), d.right(), d.bottom() _P,_Q,_R,_S = d.left(), d.top(), d.right()-d.left(), d.bottom()-d.top() faceCenter=[(_P+_R/2), (_Q+_S/2)] #print faceCenter # Update player image if _P&_Q&_R&_S != 0: face = img[_Q:_Q+_S, _P:_P+_R, :] #print face.shape img2 = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) if img2 != None: player = getFrame(color,img2) # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() badtimer-=2 #1 candytimer-=1 # Clear the screen before drawing it again screen.fill(0) # Draw the background screen.blit(grass,(0,0)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation position = pygame.mouse.get_pos() #angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) #playerrot = pygame.transform.rotate(player, 360-angle*57.29) #playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) Wplayer = width - (float(faceCenter[0])/imWidth*width) #-playerpos[0]) Hplayer = float(faceCenter[1])/imHeight*height #-playerpos[1] playerpos = [Wplayer, Hplayer] #screen.blit(playerrot, playerpos1) if playerbadflag == 0: mainChar = player else: mainChar = pygame.transform.scale(playerBad, (_R, _S)) screen.blit(mainChar, playerpos) # Draw arrows for bullet in arrows: index=0 velx=math.cos(bullet[0])*30 # *10 vely=math.sin(bullet[0])*30 bullet[1]+=velx bullet[2]+=vely if bullet[1]<-64 or bullet[1]>width or bullet[2]<-64 or bullet[2]>height: arrows.pop(index) index+=1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) screen.blit(arrow1, (projectile[1], projectile[2])) # Draw badgers badguyImg = pygame.transform.scale(badguyimg, (int(badguyimg.get_width()*shit_size_factor[level]), int(badguyimg.get_height()*shit_size_factor[level]))) if badtimer==0: badwidth1 = width/5 #9.6 badwidth2 = 4*width/5 #1.1 badwidth = random.randint(int(badwidth1), int(badwidth2)) badguys.append([badwidth, 0]) # ([badwidth, height]) badtimer=100-(badtimer1*2) if badtimer1>=35: badtimer1=35 else: badtimer1+=5 #random.randint(3,7) #5 index=0 for badguy in badguys: if badguy[1]<-64: # if badguy reached, pop out badguys.pop(index) badguy[1]+=moving_speed[level] # move badguy # Attack castle badrect=pygame.Rect(badguyImg.get_rect()) badrect.top=badguy[1] badrect.left=badguy[0] if badrect.top>height-64: # top<64 hit.play() badguys.pop(index) # Check for collisions index1=0 # bullet collisions for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if badrect.colliderect(bullrect): hit.play() #enemy.play() #acc[level]+=1 badguys.pop(index) arrows.pop(index1) index1+=1 # main char. collisions mainrect=pygame.Rect(mainChar.get_rect()) mainrect.left=playerpos[0] mainrect.top=playerpos[1] if badrect.colliderect(mainrect): enemy.play() playerbadflag = 1 #loss[level]+=1 healthvalue[level] -= blood_loss #random.randint(5,20) badguys.pop(index) # Next bad guy index+=1 # Draw badgers for badguy in badguys: screen.blit(badguyImg, badguy) # Draw candies candyImg = pygame.transform.scale(candyimg, (int(candyimg.get_width()*candy_size_factor[level]), int(candyimg.get_height()*candy_size_factor[level]))) if candytimer==0: loss[level] += 1 candywidth1 = width/5#9.6 candywidth2 = 4*width/5#1.1 candywidth = random.randint(int(candywidth1), int(candywidth2)) candies.append([candywidth, 0]) # ([candywidth, height]) candytimer=100-(candytimer1*2) if candytimer1>=35: candytimer1=35 else: candytimer1+= 5#random.randint(3,7) # 5 #print str((gaming_time-pygame.time.get_ticks()+startticks)/1000%60) #print candytimer index=0 for candy in candies: if candy[1]<-64: # if candy reached, pop out candies.pop(index) candy[1]+=moving_speed[level] # move candy # Attack castle candyrect=pygame.Rect(candyImg.get_rect()) candyrect.top=candy[1] candyrect.left=candy[0] if candyrect.top>height+64: # top<64 hit.play() healthvalue[level] -= blood_loss #random.randint(5,20) candies.pop(index) # Check for collisions index1=0 # bullet collisions for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if candyrect.colliderect(bullrect): candySound.play() healthvalue[level] -= blood_loss #random.randint(5,20) candies.pop(index) arrows.pop(index1) index1+=1 # main char. collisions mainrect=pygame.Rect(mainChar.get_rect()) mainrect.left=playerpos[0] mainrect.top=playerpos[1] if candyrect.colliderect(mainrect): candySound.play() if loss[level] - 1 >= 0: acc[level]+=1 loss[level]-=1 playerbadflag = 0 candies.pop(index) # Next bad guy index+=1 # Draw badgers for candy in candies: screen.blit(candyImg, candy) # Draw clock, score and level font = pygame.font.Font("freesansbold.ttf", 48) font2 = pygame.font.Font("freesansbold.ttf", 56) survivedtext = font.render(str((gaming_time-pygame.time.get_ticks()+startticks)/60000)+":"+str((gaming_time-pygame.time.get_ticks()+startticks)/1000%60).zfill(2), True, (0,0,0)) scoretext = font.render("Score: "+str(acc[level])+" x " + str(score_factor[level]) + " = " + str(acc[level]*score_factor[level]), True, (0,0,0)) lvtext = font.render("Level: "+ leveltxt[level], True, (0,0,0)) textRect = survivedtext.get_rect() textRect2 = scoretext.get_rect() textRect3 = lvtext.get_rect() textRect.topright=[width-120, 5] # width-5 ,5 textRect2.topright=[width-120, 55] # width-5 ,5 textRect3.topleft=[20, 55] # width-5 screen.blit(survivedtext, textRect) screen.blit(scoretext, textRect2) screen.blit(lvtext, textRect3) # Draw health bar screen.blit(healthbar, (5,5)) for health1 in range(healthvalue[level]): screen.blit(health, (health1+8,8)) # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type==pygame.QUIT: # If it is stop the music and go back to the main menu pygame.mixer.music.stop() cap.release() cv2.destroyAllWindows() menu.launch() if event.type == pygame.KEYDOWN: # Move up if event.key==K_w: keys[0]=True elif event.key==K_UP: keys[0]=True # Move left elif event.key==K_a: keys[1]=True elif event.key==K_LEFT: keys[1]=True # Move down elif event.key==K_s: keys[2]=True elif event.key==K_DOWN: keys[2]=True # Move right elif event.key==K_d: keys[3]=True elif event.key==K_RIGHT: keys[3]=True # Quit by pressing escape elif event.key==K_ESCAPE: pygame.mixer.music.stop() cap.release() cv2.destroyAllWindows() menu.launch() # Fullscreen by pressing F4 elif event.key==K_F4: settings.changeFullscreen() if event.type == pygame.KEYUP: # Move up if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_UP: keys[0]=False # Move left elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_LEFT: keys[1]=False # Move down elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_DOWN: keys[2]=False # Move right elif event.key==pygame.K_d: keys[3]=False elif event.key==pygame.K_RIGHT: keys[3]=False # Check if you pressed a mouse button for shooting arrows if event.type==pygame.MOUSEBUTTONDOWN: if waitforarrows == 0: shoot.play() position=pygame.mouse.get_pos() arrows.append([math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)),playerpos[0]+32,playerpos[1]+32]) # Set wait time for arrows in frames waitforarrows=15 # 15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 if waitforarrows: waitforarrows-=1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons-=1 if balloon1display: screen.blit(balloon1, (playerpos[0]+10, playerpos[1]-60)) elif balloon2display: screen.blit(balloon2, (playerpos[0]+10, playerpos[1]-60)) else: balloon1display = False balloon2display = False # Move player # Up if keys[0]: playerpos[1]-=10 # 5 # Down elif keys[2]: playerpos[1]+=10 # Left if keys[1]: playerpos[0]-=10 # Right elif keys[3]: playerpos[0]+=10 # Win/Lose check # Win past_time = (pygame.time.get_ticks()-startticks) if past_time>=gaming_time: # 90000 running=0 exitcode=1 elif past_time>=gaming_time/3 and level == 0: # for simplicity, didn't add "and past_time<2*gaming_time/3" level = 1 badtimer=1 candytimer=1 for candy in candies: candies.pop(0) for badguy in badguys: badguys.pop(0) elif past_time>=2*gaming_time/3 and level == 1: level = 2 badtimer=1 candytimer=1 for candy in candies: candies.pop(0) for badguy in badguys: badguys.pop(0) # Lose if healthvalue[level]<=0: running=0 exitcode=0 # Final scores if running == 0: Score1 = "Easy: "+str(acc[0])+" x " + str(score_factor[0]) + " = " + str(acc[0]*score_factor[0]) Score2 = "Hard: "+str(acc[1])+" x " + str(score_factor[1]) + " = " + str(acc[1]*score_factor[1]) Score3 = "Crazy: "+str(acc[2])+" x " + str(score_factor[2]) + " = " + str(acc[2]*score_factor[2]) #if acc[1]!=0: # accuracy=acc[0]*1.0/acc[1]*100 #else: # accuracy=0 # Flip the display pygame.display.flip() # Stop the music pygame.mixer.music.stop() # Win/lose display # Lose if exitcode==0: # Change the text color _color = (255,255,255) # Draw red overlay screen.blit(redoverlay,(0, 0)) loseGame.play() # Win else: _color = (255,0,0) # Draw green overlay screen.blit(greenoverlay,(0, 0)) winGame.play() # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 48) # 24 bigfont = pygame.font.Font("freesansbold.ttf", 56) # 48 # Render text text1 = bigfont.render("Score:", True, _color) text2 = font.render(Score1, True, _color) text3 = font.render(Score2, True, _color) text4 = font.render(Score3, True, _color) textRect1 = text1.get_rect() textRect2 = text2.get_rect() textRect3 = text3.get_rect() textRect4 = text4.get_rect() textRect1.centerx = screen.get_rect().centerx-width/3 textRect1.centery = screen.get_rect().centery+60 textRect2.centerx = screen.get_rect().centerx-width/3 textRect2.centery = screen.get_rect().centery+110 textRect3.centerx = screen.get_rect().centerx-width/3 textRect3.centery = screen.get_rect().centery+160 textRect4.centerx = screen.get_rect().centerx-width/3 textRect4.centery = screen.get_rect().centery+210 # Draw text screen.blit(text1, textRect1) screen.blit(text2, textRect2) screen.blit(text3, textRect3) screen.blit(text4, textRect4) print "ACC: " + str(acc) print "LOSS: " + str(loss) # Exit automatic when the game is stopped while 1: waitforexit+=1 for event in pygame.event.get(): if event.type == pygame.QUIT: loseGame.stop() winGame.stop() cap.release() cv2.destroyAllWindows() pygame.quit() sys.exit() if waitforexit == 1500: loseGame.stop() winGame.stop() cap.release() cv2.destroyAllWindows() menu.launch() # Update the screen pygame.display.flip()
def play(): detector = dlib.get_frontal_face_detector() # Set the width and height of the window width, height = int(pygame.display.Info().current_w), int( pygame.display.Info().current_h) # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Initial camera cap = cv2.VideoCapture(0) # or 1 imRawWidth = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) imRawHeight = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) imWidth = 1080 #640 #360 imHeight = 960 #480 #240 cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, imWidth) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, imHeight) #imWidth = imRawWidth #imHeight = imRawHeight # Set playing time gaming_time = 90000 # Set level state level = 0 moving_speed = [5, 7, 9] # original: [3,5,7] score_factor = [1, 2, 3] candy_size_factor = [0.7, 0.5, 0.3] shit_size_factor = [0.2, 0.3, 0.4] # [0.2,0.3,0.5] leveltxt = ['EASY', 'HARD', 'CRAZY!!!'] # Make an list for the accuracy acc = [0, 0, 0] loss = [0, 0, 0] _color = (255, 0, 0) # Set your health value healthvalue = [194, 194, 194] # 194 blood_loss = 20 # Set pressed keys keys = [False, False, False, False] # Flag for change player skin playerbadflag = 0 # Make an list for where the arrows are arrows = [] # Set the timer for spawning badgers badtimer = 100 badtimer1 = 0 candytimer = 100 candytimer1 = 0 # Make an list for where the badgers are badguys = [[800, 100]] candies = [[800, 100]] # Set the wait times waitforexit = 0 waitforarrows = 3 # 0 waitforballoons = 0 waitforballoons2 = 2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Initialize the mixer (for sound) pygame.mixer.init() # Set title pygame.display.set_caption("Candy Mountain") # Load images # Load the background image grass = pygame.image.load( "resources/images/BckGnd.jpg") #grass.png") # add at front grass = pygame.transform.scale(grass, (width, height)) # Load the image of the castles castle = pygame.image.load("resources/images/castle.png") # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png") # Load the image for the badgers badguyimg = pygame.image.load("resources/images/poopoo.png") #badguy.png") # Load the image for the candies candyimg = pygame.image.load("resources/images/candy.png") #badguy.png") # Load the overlays greenoverlay = pygame.image.load( "resources/images/Win.jpg") #greenoverlay.png") redoverlay = pygame.image.load( "resources/images/GameOver.jpg") #redoverlay.png") greenoverlay = pygame.transform.scale(greenoverlay, (width, height)) redoverlay = pygame.transform.scale(redoverlay, (width, height)) # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png") health = pygame.image.load("resources/images/health.png") # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png") balloon2 = pygame.image.load("resources/images/balloon2.png") # Load audio hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/ohShit.wav") #enemy.wav") candySound = pygame.mixer.Sound("resources/audio/candy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") takePicture = pygame.mixer.Sound("resources/audio/takePic.wav") loseGame = pygame.mixer.Sound("resources/audio/loseGame.wav") winGame = pygame.mixer.Sound("resources/audio/winGame.wav") # Set the audio volume hit.set_volume(0.40) enemy.set_volume(0.60) candySound.set_volume(0.40) shoot.set_volume(0.40) takePicture.set_volume(0.60) loseGame.set_volume(0.60) winGame.set_volume(0.60) # Set the background music pygame.mixer.music.load( 'resources/audio/mix90.mp3') #level_easy.mp3') #background.mp3') pygame.mixer.music.set_volume(0.50) # Set positions castle1 = (2 * width / 16, height - 150) #castle1 = (0,height/16) castle2 = (6 * width / 16, height - 150) #castle2 = (0,height/3.5) castle3 = (10 * width / 16, height - 150) #castle3 = (0,height/2) castle4 = (14 * width / 16, height - 150) #castle4 = (0,height/1.4) # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Capture frame-by-frame setting = 1 roi = [] _P, _Q, _R, _S = 0, 0, 0, 0 while (setting): ret, frame = cap.read() img = frame.copy() gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # face detection faces = detector(img) for d in faces: #print "left,top,right,bottom:", d.left(), d.top(), d.right(), d.bottom() _P, _Q, _R, _S = d.left(), d.top( ), d.right() - d.left(), d.bottom() - d.top() cv2.rectangle(img, (_P, _Q), (_P + _R, _Q + _S), (255, 0, 0), 2) # set up the ROI for tracking roi = img[_Q:_Q + _S, _P:_P + _R] # Draw the background screen.blit(grass, (0, 0)) ba = getFrame(True, cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) screen.blit(ba, (width / 2 - 400, height / 2 - 300)) # Flip the display pygame.display.flip() # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type == pygame.KEYDOWN: # select if event.key == K_s: takePicture.play() print "Selecting" setting = 0 # Load the players image player = getFrame(True, roi.copy()) #frame.copy()) playerBad = pygame.image.load("resources/images/shitFaceJustin.png") mainChar = player # Set player position playerpos = [width / 2, height / 2] faceCenter = playerpos # Keep looping through running = 1 exitcode = 0 # Set start ticks startticks = pygame.time.get_ticks() pygame.mixer.music.play(0, 0.0) while running: # Capture frame-by-frame ret, frame = cap.read() img = frame.copy() # Detect face faces = detector(img) for d in faces: #print "left,top,right,bottom:", d.left(), d.top(), d.right(), d.bottom() _P, _Q, _R, _S = d.left(), d.top( ), d.right() - d.left(), d.bottom() - d.top() faceCenter = [(_P + _R / 2), (_Q + _S / 2)] #print faceCenter # Update player image if _P & _Q & _R & _S != 0: face = img[_Q:_Q + _S, _P:_P + _R, :] #print face.shape img2 = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) if img2 != None: player = getFrame(color, img2) # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() badtimer -= 2 #1 candytimer -= 1 # Clear the screen before drawing it again screen.fill(0) # Draw the background screen.blit(grass, (0, 0)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation position = pygame.mouse.get_pos() #angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) #playerrot = pygame.transform.rotate(player, 360-angle*57.29) #playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) Wplayer = width - (float(faceCenter[0]) / imWidth * width ) #-playerpos[0]) Hplayer = float(faceCenter[1]) / imHeight * height #-playerpos[1] playerpos = [Wplayer, Hplayer] #screen.blit(playerrot, playerpos1) if playerbadflag == 0: mainChar = player else: mainChar = pygame.transform.scale(playerBad, (_R, _S)) screen.blit(mainChar, playerpos) # Draw arrows for bullet in arrows: index = 0 velx = math.cos(bullet[0]) * 30 # *10 vely = math.sin(bullet[0]) * 30 bullet[1] += velx bullet[2] += vely if bullet[1] < -64 or bullet[1] > width or bullet[ 2] < -64 or bullet[2] > height: arrows.pop(index) index += 1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29) screen.blit(arrow1, (projectile[1], projectile[2])) # Draw badgers badguyImg = pygame.transform.scale( badguyimg, (int(badguyimg.get_width() * shit_size_factor[level]), int(badguyimg.get_height() * shit_size_factor[level]))) if badtimer == 0: badwidth1 = width / 5 #9.6 badwidth2 = 4 * width / 5 #1.1 badwidth = random.randint(int(badwidth1), int(badwidth2)) badguys.append([badwidth, 0]) # ([badwidth, height]) badtimer = 100 - (badtimer1 * 2) if badtimer1 >= 35: badtimer1 = 35 else: badtimer1 += 5 #random.randint(3,7) #5 index = 0 for badguy in badguys: if badguy[1] < -64: # if badguy reached, pop out badguys.pop(index) badguy[1] += moving_speed[level] # move badguy # Attack castle badrect = pygame.Rect(badguyImg.get_rect()) badrect.top = badguy[1] badrect.left = badguy[0] if badrect.top > height - 64: # top<64 hit.play() badguys.pop(index) # Check for collisions index1 = 0 # bullet collisions for bullet in arrows: bullrect = pygame.Rect(arrow.get_rect()) bullrect.left = bullet[1] bullrect.top = bullet[2] if badrect.colliderect(bullrect): hit.play() #enemy.play() #acc[level]+=1 badguys.pop(index) arrows.pop(index1) index1 += 1 # main char. collisions mainrect = pygame.Rect(mainChar.get_rect()) mainrect.left = playerpos[0] mainrect.top = playerpos[1] if badrect.colliderect(mainrect): enemy.play() playerbadflag = 1 #loss[level]+=1 healthvalue[level] -= blood_loss #random.randint(5,20) badguys.pop(index) # Next bad guy index += 1 # Draw badgers for badguy in badguys: screen.blit(badguyImg, badguy) # Draw candies candyImg = pygame.transform.scale( candyimg, (int(candyimg.get_width() * candy_size_factor[level]), int(candyimg.get_height() * candy_size_factor[level]))) if candytimer == 0: loss[level] += 1 candywidth1 = width / 5 #9.6 candywidth2 = 4 * width / 5 #1.1 candywidth = random.randint(int(candywidth1), int(candywidth2)) candies.append([candywidth, 0]) # ([candywidth, height]) candytimer = 100 - (candytimer1 * 2) if candytimer1 >= 35: candytimer1 = 35 else: candytimer1 += 5 #random.randint(3,7) # 5 #print str((gaming_time-pygame.time.get_ticks()+startticks)/1000%60) #print candytimer index = 0 for candy in candies: if candy[1] < -64: # if candy reached, pop out candies.pop(index) candy[1] += moving_speed[level] # move candy # Attack castle candyrect = pygame.Rect(candyImg.get_rect()) candyrect.top = candy[1] candyrect.left = candy[0] if candyrect.top > height + 64: # top<64 hit.play() healthvalue[level] -= blood_loss #random.randint(5,20) candies.pop(index) # Check for collisions index1 = 0 # bullet collisions for bullet in arrows: bullrect = pygame.Rect(arrow.get_rect()) bullrect.left = bullet[1] bullrect.top = bullet[2] if candyrect.colliderect(bullrect): candySound.play() healthvalue[level] -= blood_loss #random.randint(5,20) candies.pop(index) arrows.pop(index1) index1 += 1 # main char. collisions mainrect = pygame.Rect(mainChar.get_rect()) mainrect.left = playerpos[0] mainrect.top = playerpos[1] if candyrect.colliderect(mainrect): candySound.play() if loss[level] - 1 >= 0: acc[level] += 1 loss[level] -= 1 playerbadflag = 0 candies.pop(index) # Next bad guy index += 1 # Draw badgers for candy in candies: screen.blit(candyImg, candy) # Draw clock, score and level font = pygame.font.Font("freesansbold.ttf", 48) font2 = pygame.font.Font("freesansbold.ttf", 56) survivedtext = font.render( str((gaming_time - pygame.time.get_ticks() + startticks) / 60000) + ":" + str((gaming_time - pygame.time.get_ticks() + startticks) / 1000 % 60).zfill(2), True, (0, 0, 0)) scoretext = font.render( "Score: " + str(acc[level]) + " x " + str(score_factor[level]) + " = " + str(acc[level] * score_factor[level]), True, (0, 0, 0)) lvtext = font.render("Level: " + leveltxt[level], True, (0, 0, 0)) textRect = survivedtext.get_rect() textRect2 = scoretext.get_rect() textRect3 = lvtext.get_rect() textRect.topright = [width - 120, 5] # width-5 ,5 textRect2.topright = [width - 120, 55] # width-5 ,5 textRect3.topleft = [20, 55] # width-5 screen.blit(survivedtext, textRect) screen.blit(scoretext, textRect2) screen.blit(lvtext, textRect3) # Draw health bar screen.blit(healthbar, (5, 5)) for health1 in range(healthvalue[level]): screen.blit(health, (health1 + 8, 8)) # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type == pygame.QUIT: # If it is stop the music and go back to the main menu pygame.mixer.music.stop() cap.release() cv2.destroyAllWindows() menu.launch() if event.type == pygame.KEYDOWN: # Move up if event.key == K_w: keys[0] = True elif event.key == K_UP: keys[0] = True # Move left elif event.key == K_a: keys[1] = True elif event.key == K_LEFT: keys[1] = True # Move down elif event.key == K_s: keys[2] = True elif event.key == K_DOWN: keys[2] = True # Move right elif event.key == K_d: keys[3] = True elif event.key == K_RIGHT: keys[3] = True # Quit by pressing escape elif event.key == K_ESCAPE: pygame.mixer.music.stop() cap.release() cv2.destroyAllWindows() menu.launch() # Fullscreen by pressing F4 elif event.key == K_F4: settings.changeFullscreen() if event.type == pygame.KEYUP: # Move up if event.key == pygame.K_w: keys[0] = False elif event.key == pygame.K_UP: keys[0] = False # Move left elif event.key == pygame.K_a: keys[1] = False elif event.key == pygame.K_LEFT: keys[1] = False # Move down elif event.key == pygame.K_s: keys[2] = False elif event.key == pygame.K_DOWN: keys[2] = False # Move right elif event.key == pygame.K_d: keys[3] = False elif event.key == pygame.K_RIGHT: keys[3] = False # Check if you pressed a mouse button for shooting arrows if event.type == pygame.MOUSEBUTTONDOWN: if waitforarrows == 0: shoot.play() position = pygame.mouse.get_pos() arrows.append([ math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26)), playerpos[0] + 32, playerpos[1] + 32 ]) # Set wait time for arrows in frames waitforarrows = 15 # 15 if waitforballoons2: waitforballoons2 -= 1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2 = 2 if waitforarrows: waitforarrows -= 1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons -= 1 if balloon1display: screen.blit(balloon1, (playerpos[0] + 10, playerpos[1] - 60)) elif balloon2display: screen.blit(balloon2, (playerpos[0] + 10, playerpos[1] - 60)) else: balloon1display = False balloon2display = False # Move player # Up if keys[0]: playerpos[1] -= 10 # 5 # Down elif keys[2]: playerpos[1] += 10 # Left if keys[1]: playerpos[0] -= 10 # Right elif keys[3]: playerpos[0] += 10 # Win/Lose check # Win past_time = (pygame.time.get_ticks() - startticks) if past_time >= gaming_time: # 90000 running = 0 exitcode = 1 elif past_time >= gaming_time / 3 and level == 0: # for simplicity, didn't add "and past_time<2*gaming_time/3" level = 1 badtimer = 1 candytimer = 1 for candy in candies: candies.pop(0) for badguy in badguys: badguys.pop(0) elif past_time >= 2 * gaming_time / 3 and level == 1: level = 2 badtimer = 1 candytimer = 1 for candy in candies: candies.pop(0) for badguy in badguys: badguys.pop(0) # Lose if healthvalue[level] <= 0: running = 0 exitcode = 0 # Final scores if running == 0: Score1 = "Easy: " + str(acc[0]) + " x " + str( score_factor[0]) + " = " + str(acc[0] * score_factor[0]) Score2 = "Hard: " + str(acc[1]) + " x " + str( score_factor[1]) + " = " + str(acc[1] * score_factor[1]) Score3 = "Crazy: " + str(acc[2]) + " x " + str( score_factor[2]) + " = " + str(acc[2] * score_factor[2]) #if acc[1]!=0: # accuracy=acc[0]*1.0/acc[1]*100 #else: # accuracy=0 # Flip the display pygame.display.flip() # Stop the music pygame.mixer.music.stop() # Win/lose display # Lose if exitcode == 0: # Change the text color _color = (255, 255, 255) # Draw red overlay screen.blit(redoverlay, (0, 0)) loseGame.play() # Win else: _color = (255, 0, 0) # Draw green overlay screen.blit(greenoverlay, (0, 0)) winGame.play() # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 48) # 24 bigfont = pygame.font.Font("freesansbold.ttf", 56) # 48 # Render text text1 = bigfont.render("Score:", True, _color) text2 = font.render(Score1, True, _color) text3 = font.render(Score2, True, _color) text4 = font.render(Score3, True, _color) textRect1 = text1.get_rect() textRect2 = text2.get_rect() textRect3 = text3.get_rect() textRect4 = text4.get_rect() textRect1.centerx = screen.get_rect().centerx - width / 3 textRect1.centery = screen.get_rect().centery + 60 textRect2.centerx = screen.get_rect().centerx - width / 3 textRect2.centery = screen.get_rect().centery + 110 textRect3.centerx = screen.get_rect().centerx - width / 3 textRect3.centery = screen.get_rect().centery + 160 textRect4.centerx = screen.get_rect().centerx - width / 3 textRect4.centery = screen.get_rect().centery + 210 # Draw text screen.blit(text1, textRect1) screen.blit(text2, textRect2) screen.blit(text3, textRect3) screen.blit(text4, textRect4) print "ACC: " + str(acc) print "LOSS: " + str(loss) # Exit automatic when the game is stopped while 1: waitforexit += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: loseGame.stop() winGame.stop() cap.release() cv2.destroyAllWindows() pygame.quit() sys.exit() if waitforexit == 1500: loseGame.stop() winGame.stop() cap.release() cv2.destroyAllWindows() menu.launch() # Update the screen pygame.display.flip()
def play(): cnt = 0 dec = False eclipse = 0 dececc = False # Define varibale for Level isLevelOne = True # Define variables for freeze power timeForFreezePower = False freezePowerSent = False freezepowercord = [] freezePower = False freezeTimer = 10 # Define variables for bullet power timeForBulletPower = False bulletPowerSent = False bulletpowercord = [] bulletPower = False bulletTimer = 10 # Define variables for danger power timeForDangerPower = False dangerPowerSent = False dangerpowercord = [] dangerPower = False dangerTimer = 10 # Set the width and height of the window width, height = int(pygame.display.Info().current_w), int(pygame.display.Info().current_h) # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Initialize the joystick module pygame.joystick.init() # Check if there are any joysticks joystick_count = pygame.joystick.get_count() # If there are any joysticks, initialize the first one, else quit the joystick module if joystick_count: joystick = pygame.joystick.Joystick(0) joystick.init() JS = True # Set joystick position if JS: stick0 = "right" else: pygame.joystick.quit() JS = False # Set pressed keys keys = [False, False, False, False] JSkeys = [False, False, False, False] # Set player position playerpos=[100,100] # Make an list for the accuracy acc=[0,0] # Make an list for where the arrows are arrows=[] # Set the timer for spawning badgers badtimer=100 badtimer1=0 # Make an list for where the badgers are badguys=[[800,100]] # Set your health value healthvalue=194 # Set the wait times waitforexit=0 waitforarrows=0 waitforballoons=0 waitforballoons2=2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Set start ticks startticks = pygame.time.get_ticks() # Initialize the mixer (for sound) pygame.mixer.init() # Set title pygame.display.set_caption("Galaxy Wars") # Load images # Load the players image player = pygame.image.load("resources/images/dude.png") # Load the power freeze image power_freeze = pygame.image.load("resources/images/power_freeze.png") # Load thunder image thunder = pygame.image.load("resources/images/thunder.png") # Load backgrounds bgmorning = pygame.image.load("resources/images/bgmorning.jpg") # Load the power bullet image power_bullet = pygame.image.load("resources/images/power_bullet.png") # Load the power danger image power_danger = pygame.image.load("resources/images/power_danger.png") # Green Bullet bullet_green = pygame.image.load("resources/images/bullet_green.png") # Load the background image bgmain = pygame.image.load("resources/images/starfield.png") # Red Sun level 1 sunred = pygame.image.load("resources/images/SunRed.png") # Blue Sun Danger sunblue = pygame.image.load("resources/images/SunBlue.png") # Load the image of the castles castle = pygame.image.load("resources/images/castle.png") # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png") # Load the image for the badgers badguyimg1 = pygame.image.load("resources/images/badguy.png") badguyimg = badguyimg1 # Load the overlays greenoverlay = pygame.image.load("resources/images/greenoverlay.png") redoverlay = pygame.image.load("resources/images/redoverlay.png") # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png") health = pygame.image.load("resources/images/health.png") # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png") balloon2 = pygame.image.load("resources/images/balloon2.png") # Load audio hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/enemy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") # Set the audio volume hit.set_volume(0.15) enemy.set_volume(0.15) shoot.set_volume(0.15) # Set the background music pygame.mixer.music.load('resources/audio/background.mp3') pygame.mixer.music.play(-1, 0.0) pygame.mixer.music.set_volume(0.30) # Set positions castle1 = (0,height/16) castle2 = (0,height/3.5) castle3 = (0,height/2) castle4 = (0,height/1.4) # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Keep looping through running = 1 exitcode = 0 while running: # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() # Set joystick buttons, if there are any if JS: buttonUP = joystick.get_button(4) buttonRIGHT = joystick.get_button(5) buttonDOWN = joystick.get_button(6) buttonLEFT = joystick.get_button(7) buttonX = joystick.get_button(14) stick0a = joystick.get_axis(0) stick0b = joystick.get_axis(1) # Check for stick0's position if JS: if stick0a <= -0.5 and stick0b <= -0.5: stick0 = "leftup" elif stick0a <= -0.5 and stick0b >= 0.5: stick0 = "leftdown" elif stick0a >= 0.5 and stick0b <= -0.5: stick0 = "rightup" elif stick0a >= 0.5 and stick0b >= 0.5: stick0 = "rightdown" elif stick0a <= -0.5: stick0 = "left" elif stick0a >= 0.5: stick0 = "right" elif stick0b <= -0.5: stick0 = "up" elif stick0b >= 0.5: stick0 = "down" badtimer-=1 # Clear the screen before drawing it again screen.fill(0) # Draw the background if isLevelOne: screen.blit(bgmorning, (0, 0)) else: screen.blit(bgmain, (0,0)) if acc[0] > 25: isLevelOne = False if dangerPower and isLevelOne == False: eclipse += 10 if eclipse > 100: screen.blit(sunblue, (width // 2, 0)) else: screen.blit(sunred, (width // 2, 0)) if eclipse % 20 == 0: screen.blit(thunder, (width // 2, 0)) if eclipse > 200: eclipse = 0 else: screen.blit(sunred, (width // 2, 0)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation if JS == False: position = pygame.mouse.get_pos() angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) playerrot = pygame.transform.rotate(player, 360-angle*57.29) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif JS == True: if stick0 == "left": playerrot = pygame.transform.rotate(player, 180) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "right": playerrot = pygame.transform.rotate(player, 0) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "up": playerrot = pygame.transform.rotate(player, 90) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "down": playerrot = pygame.transform.rotate(player, 270) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "leftup": playerrot = pygame.transform.rotate(player, 135) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "leftdown": playerrot = pygame.transform.rotate(player, 225) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "rightup": playerrot = pygame.transform.rotate(player, 45) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "rightdown": playerrot = pygame.transform.rotate(player, 315) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) # Draw arrows for bullet in arrows: index=0 velx = 0 vely = 0 if bulletPower and dangerPower is False: velx=math.cos(bullet[0])*30 vely=math.sin(bullet[0])*30 elif dangerPower is False: velx=math.cos(bullet[0])*20 vely=math.sin(bullet[0])*20 elif dangerPower: velx=math.cos(bullet[0])*10 vely=math.sin(bullet[0])*10 bullet[1]+=velx bullet[2]+=vely if bullet[1]<-64 or bullet[1]>width or bullet[2]<-64 or bullet[2]>height: arrows.pop(index) index+=1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) bullet_green1 = pygame.transform.rotate(bullet_green, 360-projectile[0]*57.29) if bulletPower: screen.blit(bullet_green1, (projectile[1], projectile[2])) else: screen.blit(arrow1, (projectile[1], projectile[2])) # Draw badguys if badtimer==0: badheight1 = height/9.6 badheight2 = height/1.1 badheight = random.randint(int(badheight1), int(badheight2)) badguys.append([width, badheight]) badtimer=100-(badtimer1*2) if badtimer1>=35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy[0]<-64: badguys.pop(index) if freezePower is False and dangerPower is False: badguy[0]-=7 if cnt < 30 and dec is False: badguy[1] += 7 cnt += 1 else: dec = True cnt -= 1 badguy[1] -= 7 if cnt is 0: dec = False elif dangerPower: badguy[0] -= 20 xx = random.randint(0, 1) if cnt < 30 and dec is False: if xx == 1: badguy[1] += 7 cnt += 1 else: dec = True cnt -= 1 if xx == 1: badguy[1] -= 7 if cnt is 0: dec = False # Attack castle badrect=pygame.Rect(badguyimg.get_rect()) badrect.top=badguy[1] badrect.left=badguy[0] if badrect.left<64: hit.play() healthvalue -= random.randint(5,20) badguys.pop(index) # Check for collisions index1=0 for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if badrect.colliderect(bullrect): enemy.play() acc[0]+=1 if acc[0] % 3 == 0 and isLevelOne == False: timeForDangerPower = True else: timeForDangerPower = False if acc[0] % 5 == 0: timeForFreezePower = True else: timeForFreezePower = False if acc[0] % 7 == 0: timeForBulletPower = True else: timeForBulletPower = False badguys.pop(index) if bulletPower == False: arrows.pop(index1) index1+=1 # Next bad guy index+=1 # Draw badgers for badguy in badguys: screen.blit(badguyimg, badguy) # Draw power if power sent is true if dangerPowerSent: dangerpowercord[0] -= 7 screen.blit(power_danger, dangerpowercord) if dangerpowercord[0] < 0: dangerPowerSent = False if bulletPowerSent: bulletpowercord[0] -= 7 screen.blit(power_bullet, bulletpowercord) if bulletpowercord[0] < 0: bulletPowerSent = False if freezePowerSent: freezepowercord[0] -= 7 screen.blit(power_freeze, freezepowercord) if freezepowercord[0] < 0: freezePowerSent = False if timeForDangerPower and dangerPowerSent == False: powerheight1 = height/9.6 powerheight2 = height/1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) dangerpowercord = [width, playerpos[1]] print "dangerPowerSent" dangerPowerSent = True timeForDangerPower = False screen.blit(power_danger, dangerpowercord) if timeForBulletPower and bulletPowerSent == False: powerheight1 = height/9.6 powerheight2 = height/1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) bulletpowercord = [width, powerheight] print "bulletPowerSent" bulletPowerSent = True timeForBulletPower = False screen.blit(power_bullet, bulletpowercord) if timeForFreezePower and freezePowerSent == False: powerheight1 = height/9.6 powerheight2 = height/1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) freezepowercord = [width, powerheight] print "freezePowerSent" freezePowerSent = True timeForFreezePower = False screen.blit(power_freeze, freezepowercord) if dangerPower: dangerTimer += 10 if dangerTimer > 2000: dangerPower = False dangerTimer = 0 if bulletPower: bulletTimer += 10 if bulletTimer > 2000: bulletPower = False bulletTimer = 0 if freezePower: freezeTimer += 10 if freezeTimer > 1000: freezePower = False freezeTimer = 0 # Check if power is Taken if dangerPowerSent: dangerpowerRect = pygame.Rect(power_danger.get_rect()) playerRect = pygame.Rect(player.get_rect()) dangerpowerRect.top = dangerpowercord[1] dangerpowerRect.left = dangerpowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if dangerpowerRect.colliderect(playerRect): dangerPower = True dangerPowerSent = False if bulletPowerSent: bullpowerRect = pygame.Rect(power_bullet.get_rect()) playerRect = pygame.Rect(player.get_rect()) bullpowerRect.top = bulletpowercord[1] bullpowerRect.left = bulletpowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if bullpowerRect.colliderect(playerRect): bulletPower = True bulletPowerSent = False if freezePowerSent: powerRect = pygame.Rect(power_freeze.get_rect()) playerRect = pygame.Rect(player.get_rect()) powerRect.top = freezepowercord[1] powerRect.left = freezepowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if powerRect.colliderect(playerRect): freezePower = True print "Collision Detected" freezePowerSent = False # Draw clock font = pygame.font.Font("freesansbold.ttf", 24) survivedtext = font.render(str("Score: " + str(acc[0])) , True, (255,0,0)) leveltext = "" if isLevelOne: leveltext= font.render(str("Level: 1") , True, (0,0,255)) else: leveltext= font.render(str("Level: 2") , True, (0,0,255)) levelrect = leveltext.get_rect() levelrect.topleft = [250, 5] screen.blit(leveltext, levelrect) textRect = survivedtext.get_rect() textRect.topright=[width-5, 5] screen.blit(survivedtext, textRect) # Draw health bar screen.blit(healthbar, (5,5)) for health1 in range(healthvalue): screen.blit(health, (health1+8,8)) # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type==pygame.QUIT: # If it is stop the music and go back to the main menu pygame.mixer.music.stop() menu.launch() if event.type == pygame.KEYDOWN: # Move up if event.key==K_w: keys[0]=True elif event.key==K_UP: keys[0]=True # Move left elif event.key==K_a: keys[1]=True elif event.key==K_LEFT: keys[1]=True # Move down elif event.key==K_s: keys[2]=True elif event.key==K_DOWN: keys[2]=True # Move right elif event.key==K_d: keys[3]=True elif event.key==K_RIGHT: keys[3]=True # Quit by pressing escape elif event.key==K_ESCAPE: pygame.mixer.music.stop() menu.launch() # Fullscreen by pressing F4 elif event.key==K_F4: settings.changeFullscreen() elif event.key==pygame.K_SPACE: if waitforarrows == 0: shoot.play() position=pygame.mouse.get_pos() acc[1]+=1 arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32]) # Set wait time for arrows in frames waitforarrows=15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 if event.type == pygame.KEYUP: # Move up if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_UP: keys[0]=False # Move left elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_LEFT: keys[1]=False # Move down elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_DOWN: keys[2]=False # Move right elif event.key==pygame.K_d: keys[3]=False elif event.key==pygame.K_RIGHT: keys[3]=False if waitforarrows: waitforarrows-=1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons-=1 if balloon1display: screen.blit(balloon1, (playerpos[0]+10, playerpos[1]-60)) elif balloon2display: screen.blit(balloon2, (playerpos[0]+10, playerpos[1]-60)) else: balloon1display = False balloon2display = False # Check if there are any joysticks if JS: # Check if UP is pressed if buttonUP: JSkeys[0]=True # Check if RIGHT is pressed elif buttonRIGHT: JSkeys[3]=True # Check if DOWN is pressed elif buttonDOWN: JSkeys[2]=True # Check if LEFT is pressed elif buttonLEFT: JSkeys[1]=True else: JSkeys[0]=False JSkeys[1]=False JSkeys[2]=False JSkeys[3]=False # Check of X is pressed if buttonX: if waitforarrows == 0: shoot.play() acc[1]+=1 if stick0 == "left": arrows.append([3,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "right": arrows.append([0,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "up": arrows.append([-1.5,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "down": arrows.append([1.5,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "leftup": arrows.append([-2.25,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "leftdown": arrows.append([2.25,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "rightup": arrows.append([-0.75,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "rightdown": arrows.append([0.75,playerpos1[0]+32,playerpos1[1]+32]) # Set wait time for arrows in frames waitforarrows=15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 # Move player # Up if keys[0]: playerpos[1]-=5 # Down elif keys[2]: playerpos[1]+=5 # Left if keys[1]: playerpos[0]-=5 # Right elif keys[3]: playerpos[0]+=5 # Move player with JoyStick # Up if JSkeys[0]: playerpos[1]-=5 # Down elif JSkeys[2]: playerpos[1]+=5 # Left if JSkeys[1]: playerpos[0]-=5 # Right elif JSkeys[3]: playerpos[0]+=5 # Win/Lose check # Win # Lose if healthvalue<=0: running=0 exitcode=0 if acc[1]!=0: accuracy=acc[0]*1.0/acc[1]*100 else: accuracy=0 # Flip the display pygame.display.flip() # Stop the music pygame.mixer.music.stop() # Win/lose display # Lose if exitcode==0: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text gameover = bigfont.render("Game over!", True, (255,0,0)) gameoverRect = gameover.get_rect() gameoverRect.centerx = screen.get_rect().centerx gameoverRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw red overlay for x in range(width/redoverlay.get_width()+1): for y in range(height/redoverlay.get_height()+1): screen.blit(redoverlay,(x*100,y*100)) # Draw text screen.blit(gameover, gameoverRect) screen.blit(text, textRect) # Win else: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text youwin = bigfont.render("You win!", True, (0,255,0)) youwinRect = youwin.get_rect() youwinRect.centerx = screen.get_rect().centerx youwinRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw green overlay for x in range(width/greenoverlay.get_width()+1): for y in range(height/greenoverlay.get_height()+1): screen.blit(greenoverlay,(x*100,y*100)) # Draw text screen.blit(youwin, youwinRect) screen.blit(text, textRect) # Exit automatic when the game is stopped while 1: waitforexit+=1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if waitforexit == 1000: menu.launch() # Update the screen pygame.display.flip()
def launch(): # Initialize pygame pygame.init() # Set the width and height of the window width, height = pygame.display.Info().current_w, pygame.display.Info().current_h # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Set the window title pygame.display.set_caption("JoyStick Testing Module") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Initialize the joysticks pygame.joystick.init() # Get ready to print textPrint = TextPrint() # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # -------- Main Program Loop ----------- while True: # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN ) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() # EVENT PROCESSING STEP for event in pygame.event.get(): # User did something # Check if the event is the X button if event.type == pygame.QUIT: # If it is go back to the main menu menu.launch() # Check if a key is pressed elif event.type == pygame.KEYDOWN: # If pressed esc go back to the menu if event.key == K_ESCAPE: menu.launch() # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") # DRAWING STEP # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) textPrint.reset() # Get count of joysticks joystick_count = pygame.joystick.get_count() textPrint.Print(screen, "Number of joysticks: {}".format(joystick_count)) textPrint.indent() # For each joystick: for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() textPrint.Print(screen, "Joystick {}".format(i)) textPrint.indent() # Get the name from the OS for the controller/joystick name = joystick.get_name() textPrint.Print(screen, "Joystick name: {}".format(name)) # Usually axis run in pairs, up/down for one, and left/right for # the other. axes = joystick.get_numaxes() textPrint.Print(screen, "Number of axes: {}".format(axes)) textPrint.indent() for i in range(axes): axis = joystick.get_axis(i) textPrint.Print(screen, "Axis {} value: {:>6.3f}".format(i, axis)) textPrint.unindent() buttons = joystick.get_numbuttons() textPrint.Print(screen, "Number of buttons: {}".format(buttons)) textPrint.indent() for i in range(buttons): button = joystick.get_button(i) textPrint.Print(screen, "Button {:>2} value: {}".format(i, button)) textPrint.unindent() # Hat switch. All or nothing for direction, not like joysticks. # Value comes back in an array. hats = joystick.get_numhats() textPrint.Print(screen, "Number of hats: {}".format(hats)) textPrint.indent() for i in range(hats): hat = joystick.get_hat(i) textPrint.Print(screen, "Hat {} value: {}".format(i, str(hat))) textPrint.unindent() textPrint.unindent() # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Limit to 20 frames per second clock.tick(20)
def play(fps): # Set the width and height of the window width, height = int(pygame.display.Info().current_w), int(pygame.display.Info().current_h) # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Initialize the joystick module pygame.joystick.init() # Check if there are any joysticks joystick_count = pygame.joystick.get_count() # If there are any joysticks, initialize the first one, else quit the joystick module if joystick_count: joystick = pygame.joystick.Joystick(0) joystick.init() JS = True # Set joystick position if JS: stick0 = "right" else: pygame.joystick.quit() JS = False # Set pressed keys keys = [False, False, False, False] JSkeys = [False, False, False, False] # Set player position playerpos=[100,100] # Make an list for the accuracy acc=[0,0] # Make an list for where the arrows are arrows=[] # Set the timer for spawning badgers badtimer=100 badtimer1=0 # Make an list for where the badgers are badguys=[[800,100]] # Set your health value healthvalue=194 # Set the wait times waitforexit=0 waitforarrows=0 waitforballoons=0 waitforballoons2=2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Set start ticks startticks = pygame.time.get_ticks() # Initialize the mixer (for sound) pygame.mixer.init() # Set title pygame.display.set_caption("Bunny and Badgers") # Load images # Load the players image player = pygame.image.load("resources/images/dude.png").convert_alpha() # Load the background image grass = pygame.image.load("resources/images/grass.png").convert() # Load the image of the castles castle = pygame.image.load("resources/images/castle.png").convert_alpha() # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png").convert_alpha() # Load the image for the badgers badguyimg1 = pygame.image.load("resources/images/badguy.png").convert_alpha() badguyimg2 = pygame.image.load("resources/images/badguy2.png").convert_alpha() badguyimg3 = pygame.image.load("resources/images/badguy3.png").convert_alpha() badguyimg4 = pygame.image.load("resources/images/badguy4.png").convert_alpha() badguyimg = badguyimg1 # Load the overlays greenoverlay = pygame.image.load("resources/images/greenoverlay.png").convert_alpha() redoverlay = pygame.image.load("resources/images/redoverlay.png").convert_alpha() # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png").convert_alpha() health = pygame.image.load("resources/images/health.png").convert_alpha() # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png").convert_alpha() balloon2 = pygame.image.load("resources/images/balloon2.png").convert_alpha() # Load audio hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/enemy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") # Set the audio volume hit.set_volume(0.15) enemy.set_volume(0.15) shoot.set_volume(0.15) # Set the background music pygame.mixer.music.load("resources/audio/background.mp3") pygame.mixer.music.play(-1, 0.0) pygame.mixer.music.set_volume(0.30) # Set positions castle1 = (0,height/16) castle2 = (0,height/3.5) castle3 = (0,height/2) castle4 = (0,height/1.4) # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Create a clock clock = pygame.time.Clock() # Keep looping through running = 1 exitcode = 0 while running: # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() # Set joystick buttons, if there are any if JS: buttonUP = joystick.get_button(4) buttonRIGHT = joystick.get_button(5) buttonDOWN = joystick.get_button(6) buttonLEFT = joystick.get_button(7) buttonX = joystick.get_button(14) stick0a = joystick.get_axis(0) stick0b = joystick.get_axis(1) # Check for stick0's position if JS: if stick0a <= -0.5 and stick0b <= -0.5: stick0 = "leftup" elif stick0a <= -0.5 and stick0b >= 0.5: stick0 = "leftdown" elif stick0a >= 0.5 and stick0b <= -0.5: stick0 = "rightup" elif stick0a >= 0.5 and stick0b >= 0.5: stick0 = "rightdown" elif stick0a <= -0.5: stick0 = "left" elif stick0a >= 0.5: stick0 = "right" elif stick0b <= -0.5: stick0 = "up" elif stick0b >= 0.5: stick0 = "down" badtimer-=1 # Draw the background for x in range(width/grass.get_width()+1): for y in range(height/grass.get_height()+1): screen.blit(grass,(x*100,y*100)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation if JS == False: position = pygame.mouse.get_pos() angle = numpy.arctan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) playerrot = pygame.transform.rotate(player, 360-angle*57.29) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif JS == True: if stick0 == "left": playerrot = pygame.transform.rotate(player, 180) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "right": playerrot = pygame.transform.rotate(player, 0) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "up": playerrot = pygame.transform.rotate(player, 90) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "down": playerrot = pygame.transform.rotate(player, 270) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "leftup": playerrot = pygame.transform.rotate(player, 135) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "leftdown": playerrot = pygame.transform.rotate(player, 225) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "rightup": playerrot = pygame.transform.rotate(player, 45) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) elif stick0 == "rightdown": playerrot = pygame.transform.rotate(player, 315) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) # Draw arrows for bullet in arrows: index=0 velx=numpy.cos(bullet[0])*10 vely=numpy.sin(bullet[0])*10 bullet[1]+=velx bullet[2]+=vely if bullet[1]<-64 or bullet[1]>width or bullet[2]<-64 or bullet[2]>height: arrows.pop(index) index+=1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) screen.blit(arrow1, (projectile[1], projectile[2])) # Change the image of the badgers if badguyimg == badguyimg1: badguyimg = badguyimg2 elif badguyimg == badguyimg2: badguyimg = badguyimg3 elif badguyimg == badguyimg3: badguyimg = badguyimg4 elif badguyimg == badguyimg4: badguyimg = badguyimg1 # Draw badgers if badtimer==0: badheight1 = height/9.6 badheight2 = height/1.1 badheight = numpy.random.randint(int(badheight1), int(badheight2)+1) badguys.append([width, badheight]) badtimer=100-(badtimer1*2) if badtimer1>=35: badtimer1=35 else: badtimer1+=5 index=0 for badguy in badguys: if badguy[0]<-64: badguys.pop(index) badguy[0]-=7 # Attack castle badrect=pygame.Rect(badguyimg.get_rect()) badrect.top=badguy[1] badrect.left=badguy[0] if badrect.left<64: hit.play() healthvalue -= numpy.random.randint(5,21) badguys.pop(index) # Check for collisions index1=0 for bullet in arrows: bullrect=pygame.Rect(arrow.get_rect()) bullrect.left=bullet[1] bullrect.top=bullet[2] if badrect.colliderect(bullrect): enemy.play() acc[0]+=1 badguys.pop(index) arrows.pop(index1) index1+=1 # Next bad guy index+=1 # Draw badgers for badguy in badguys: screen.blit(badguyimg, badguy) # Draw clock font = pygame.font.Font("freesansbold.ttf", 24) survivedtext = font.render(str((90000-pygame.time.get_ticks()+startticks)/60000)+":"+str((90000-pygame.time.get_ticks()+startticks)/1000%60).zfill(2), True, (0,0,0)) textRect = survivedtext.get_rect() textRect.topright=[width-5, 5] screen.blit(survivedtext, textRect) # Draw health bar screen.blit(healthbar, (5,5)) for health1 in range(healthvalue): screen.blit(health, (health1+8,8)) # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type==pygame.QUIT: # If it is stop the music and go back to the main menu pygame.mixer.music.stop() menu.launch() if event.type == pygame.KEYDOWN: # Move up if event.key in (K_w, K_UP): keys[0]=True # Move left elif event.key in (K_a, K_LEFT): keys[1]=True # Move down elif event.key in (K_s, K_DOWN): keys[2]=True # Move right elif event.key in (K_d, K_RIGHT): keys[3]=True # Quit by pressing escape elif event.key==K_ESCAPE: pygame.mixer.music.stop() menu.launch() # Fullscreen by pressing F4 elif event.key==K_F4: settings.changeFullscreen() if event.type == pygame.KEYUP: # Move up if event.key in (K_w, K_UP): keys[0]=False # Move left elif event.key in (K_a, K_LEFT): keys[1]=False # Move down elif event.key in (K_s, K_DOWN): keys[2]=False # Move right elif event.key in (K_d, K_RIGHT): keys[3]=False # Check if you pressed a mouse button for shooting arrows if event.type==pygame.MOUSEBUTTONDOWN: if waitforarrows == 0: shoot.play() position=pygame.mouse.get_pos() acc[1]+=1 arrows.append([numpy.arctan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32]) # Set wait time for arrows in frames waitforarrows=15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = numpy.random.randint(1, 3) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 if waitforarrows: waitforarrows-=1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons-=1 if balloon1display: screen.blit(balloon1, (playerpos[0]+10, playerpos[1]-60)) elif balloon2display: screen.blit(balloon2, (playerpos[0]+10, playerpos[1]-60)) else: balloon1display = False balloon2display = False # Check if there are any joysticks if JS: # Check if UP is pressed if buttonUP: JSkeys[0]=True # Check if RIGHT is pressed elif buttonRIGHT: JSkeys[3]=True # Check if DOWN is pressed elif buttonDOWN: JSkeys[2]=True # Check if LEFT is pressed elif buttonLEFT: JSkeys[1]=True else: JSkeys[0]=False JSkeys[1]=False JSkeys[2]=False JSkeys[3]=False # Check of X is pressed if buttonX: if waitforarrows == 0: shoot.play() acc[1]+=1 if stick0 == "left": arrows.append([3,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "right": arrows.append([0,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "up": arrows.append([-1.5,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "down": arrows.append([1.5,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "leftup": arrows.append([-2.25,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "leftdown": arrows.append([2.25,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "rightup": arrows.append([-0.75,playerpos1[0]+32,playerpos1[1]+32]) elif stick0 == "rightdown": arrows.append([0.75,playerpos1[0]+32,playerpos1[1]+32]) # Set wait time for arrows in frames waitforarrows=15 if waitforballoons2: waitforballoons2-=1 else: # Choose balloon balloonnr = numpy.random.randint(1, 3) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2=2 # Move player # Up if keys[0]: playerpos[1]-=5 # Down elif keys[2]: playerpos[1]+=5 # Left if keys[1]: playerpos[0]-=5 # Right elif keys[3]: playerpos[0]+=5 # Move player with JoyStick # Up if JSkeys[0]: playerpos[1]-=5 # Down elif JSkeys[2]: playerpos[1]+=5 # Left if JSkeys[1]: playerpos[0]-=5 # Right elif JSkeys[3]: playerpos[0]+=5 # Win/Lose check # Win if (pygame.time.get_ticks()-startticks)>=90000: running=0 exitcode=1 # Lose if healthvalue<=0: running=0 exitcode=0 if acc[1]!=0: accuracy=acc[0]*1.0/acc[1]*100 else: accuracy=0 # Flip the display pygame.display.flip() # Lock fps clock.tick(fps) # Stop the music pygame.mixer.music.stop() # Win/lose display # Lose if exitcode==0: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text gameover = bigfont.render("Game over!", True, (255,0,0)) gameoverRect = gameover.get_rect() gameoverRect.centerx = screen.get_rect().centerx gameoverRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw red overlay for x in range(width/redoverlay.get_width()+1): for y in range(height/redoverlay.get_height()+1): screen.blit(redoverlay,(x*100,y*100)) # Draw text screen.blit(gameover, gameoverRect) screen.blit(text, textRect) # Win else: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text youwin = bigfont.render("You win!", True, (0,255,0)) youwinRect = youwin.get_rect() youwinRect.centerx = screen.get_rect().centerx youwinRect.centery = screen.get_rect().centery-24 text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery+24 # Draw green overlay for x in range(width/greenoverlay.get_width()+1): for y in range(height/greenoverlay.get_height()+1): screen.blit(greenoverlay,(x*100,y*100)) # Draw text screen.blit(youwin, youwinRect) screen.blit(text, textRect) # Exit automatic when the game is stopped while 1: waitforexit+=1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if waitforexit == 1000: menu.launch() # Update the screen pygame.display.flip()
def game(): import pygame, sys, pygame.mixer from pygame.locals import * import common_pygame import enemy import load_resources import random import ship import background import hud import bonus import menu import effects import particles import smoke import lasers import input import lib.eztext import scoreboard pygame = common_pygame.pygame screen= common_pygame.screen clock = common_pygame.clock #dictionnaries that will contain all our needed resources sounds = dict() single_sprites = dict() sprite_sequences = dict() #create the menu ( we create it here in order to let the menu object read the configuration, #to set the correct screen size menu=menu.Menu() #fill up our dictionnaries (sounds, single_sprites, sprite_sequences) = load_resources.load_resources(pygame) #sprite proprieties being used later laser_height = single_sprites['sprite_laser.png'].get_height() laser_width = single_sprites['sprite_laser.png'].get_width() #lasershoot_width = single_sprites['sprite_lasershoot.png'].get_width() #lasershoot_height = single_sprites['sprite_lasershoot.png'].get_height() #the ship's laser list laserlist = list() lasershoot = 7 tinyfont = pygame.font.Font(None, 16) font = pygame.font.Font(None,32) font2 = pygame.font.Font(None, 150) background = background.BackGen(single_sprites) hud= hud.Hud(single_sprites, menu, sounds) #start the menu menu.init2(single_sprites, sounds, background, hud) menu.launch(0) ship = ship.Ship(single_sprites, sounds, menu, sprite_sequences ) ship.setWeapon(1) ship_top = screen.get_height()-ship.height ship_left = screen.get_width()/2 - ship.width/2 decal_laser_ship_x = (ship.width /2) coord_laser_ship_y = -40 #the enemy laser system lasers = lasers.Lasers(single_sprites, ship) enemy_list = list() compteur = 0 countdown=0 #to know if it's ok to shoot compteur_shoot=int(0) nbAsteroids=0 #current_sprite=0 it=0 #bonus processing scoreBonus=bonus.Bonus(sounds, menu) thegame=True level =-1 spawnedBoss=False while thegame: compteur_shoot=compteur_shoot+1 #every 2 minutes, level up if compteur%(30*60)==0: level=level+1 #level 1 : 3 enemies every 3 seconds if level==1: if compteur%(3*20)==0: boolrand = bool(random.getrandbits(1)) for i in range(1): enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, i*80+250+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand \ , 0, menu)) #print (enemy_list[0].nbAsteroids) if level==2: if compteur%(2*60)==0: boolrand = bool(random.getrandbits(1)) for i in range(6): enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, i*80+190+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand \ , 0, menu)) #print (enemy_list[0].nbAsteroids) if level==3 and not spawnedBoss: enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, 400-single_sprites['boss1.png'].get_width()/2, -single_sprites['boss1.png'].get_height(),1 ,\ 2, menu)) spawnedBoss=True #if compteur%(1*60)==0: #boolrand = bool(random.getrandbits(1)) #for i in range(9): #enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, #i*80+80+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand , 0, menu)) #print (enemy_list[0].nbAsteroids) #new asteroids #if ((len(enemy_list)==0) or enemy_list[0].nbAsteroids<=2) and compteur%150==0: if compteur%150==0: boolrand = bool(random.getrandbits(1)) enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, random.randrange(0, screen.get_width()), -32,boolrand , 1, menu)) enemy_list[0].nbAsteroids=enemy_list[0].nbAsteroids+1 #if (len(enemy_list)>=0): #print( compteur = compteur +1 background.updatecompteur() clock.tick_busy_loop(30) screen.fill((0,0,0)) #blit the stars and the asteroids background.blitStars() background.blitPlanets() #show the fog background.blitFog() mouse_x,mouse_y=pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #elif event.type == MOUSEBUTTONDOWN: #sounds['laser.wav'].play() #laserlist.append( (ship.position_ship_x+ship.width/2 -laser_width/2 , #ship.position_ship_y-laser_height)) #lasershoot = 7 if pygame.key.get_pressed()[K_ESCAPE]: #launch menu with resume option menu.launch(1) if pygame.key.get_pressed()[K_LEFT]: if ship.currentspeed_x >=0: ship.currentspeed_x = -5 if ship.currentspeed_x > -20: ship.currentspeed_x = ship.currentspeed_x -1 elif pygame.key.get_pressed()[K_RIGHT]: if ship.currentspeed_x <= 0: ship.currentspeed_x = 5 if ship.currentspeed_x < 20: ship.currentspeed_x = ship.currentspeed_x +1 if pygame.key.get_pressed()[K_DOWN]: if ship.currentspeed_y <= 0: ship.currentspeed_y = 5 if ship.currentspeed_y < 20: ship.currentspeed_y = ship.currentspeed_y +1 elif pygame.key.get_pressed()[K_UP]: if ship.currentspeed_y >= 0: ship.currentspeed_y = -5 if ship.currentspeed_y > -20: ship.currentspeed_y = ship.currentspeed_y -1 if pygame.key.get_pressed()[K_LEFT] ==0 and pygame.key.get_pressed()[K_RIGHT]==0 \ and pygame.key.get_pressed()[K_UP] ==0 and pygame.key.get_pressed()[K_DOWN]==0: ship.currentspeed_y=0 ship.currentspeed_x=0 #are we shooting ? if pygame.key.get_pressed()[K_SPACE]: (compteur_shoot, laserlist) =ship.shoot(laserlist,compteur_shoot, laser_width, laser_height) #update the ships position ship.updatePosition() #blit the right thing ship.blit(compteur) #blit the laser shot fire #if lasershoot >= 0 : #screen.blit(single_sprites['sprite_lasershoot.png'],(ship.position_ship_x+ship.width/2 -lasershoot_width/2, #ship.position_ship_y )) #lasershoot = lasershoot -1 oldLasers = list() #blit the lasers for index in range(len(laserlist)): (currentx, currenty, lasertype) = laserlist[index] if currenty>=-40: #it's a normal laser if lasertype==1: screen.blit(single_sprites['sprite_laser_light.png'],(currentx-29-32,currenty-22-32)) screen.blit(single_sprites['sprite_laser.png'],(currentx,currenty)) currenty = currenty - 15 #it's a plasma ball else : screen.blit(single_sprites['ball1_light.png'],(currentx-10,currenty-10)) screen.blit(single_sprites['ball1.png'],(currentx,currenty)) currenty = currenty - 20 laserlist[index]=(currentx,currenty, lasertype) else: oldLasers.append((currentx,currenty, lasertype)) #purge old lasers for index in range(len(oldLasers)): laserlist.remove(oldLasers[index]) deadEnemies=list() #blit and process the enemies for index in range(len(enemy_list)): oldLasers=enemy_list[index].processHit(laserlist, ship) enemy_list[index].update(ship, lasers) if enemy_list[index].alive==False: deadEnemies.append(enemy_list[index]) #purge old lasers for index in range(len(oldLasers)): laserlist.remove(oldLasers[index]) #purge dead enemies for index in range(len(deadEnemies)): enemy_list.remove(deadEnemies[index]) #blit and process the enemy's lasers lasers.update() #blit the hud level = hud.blit(ship, level) #process ship hurt countdown = ship.processHurt(countdown) if (ship.life<=0): thegame=False #youlost = font2.render("Game over", True, (255,255, 255)) #presskey = font.render("press any key to quit", True, (255,255, 255)) #yourscore = font.render("Your score : "+ str(ship.score), True, (255,255, 255)) youlost = pygame.font.Font("BITSUMIS.TTF",105).render("Game over", True, (255,255, 255)) presskey = pygame.font.Font("BITSUMIS.TTF",23).render("press escape to quit", True, (255,255, 255)) yourscore = pygame.font.Font("BITSUMIS.TTF",30).render("Your score : "+ str(ship.score), True, (255,255, 255)) yourname = pygame.font.Font("BITSUMIS.TTF",55).render("Your name : ", True, (255,255, 255)) #play a the explosion sound menu.play_sound(sounds['explosion2.wav']) #blit the explosion screen.blit(sprite_sequences['sprite_explosion_list_asteroid.png'][3],\ (ship.position_ship_x-64,ship.position_ship_y-64)) #fade to red effects.fadeToColor(255, 0, 0) #scoreBonus.ProcessBonus(ship) particles.blitAndUpdate() smoke.blitAndUpdate() pygame.display.flip() exitloop = True exitcountdown =0 name = "" car = "" txtbx = lib.eztext.Input(maxlength=45, color=(255,50,50), prompt='Your name: ') txtbx.set_pos( 230,180) txtbx.set_font(pygame.font.Font("BITSUMIS.TTF",30)) nametyped = False scoreObj = scoreboard.ScoreBoard() while exitloop: exitcountdown =exitcountdown+ 1 clock.tick_busy_loop(30) screen.fill((0,0,0)) background.updatecompteur() background.blitStars() background.blitPlanets() #show the fog background.blitFog() screen.blit(youlost, (110,35 )) screen.blit(yourscore, (130,150 )) #screen.blit(yourname, (180,330 )) #screen.blit(pygame.font.Font("BITSUMIS.TTF",55)\ #.render(name, True, (255,0, 0)), (300, 330)) screen.blit(presskey, (270,520 )) #car = str(input.keyInput()) #if isinstance(car, str): #name = name + pygame.key.name(car) #print("name : " + name) #input.keyInput() if not nametyped: # update txtbx txtbx.update(pygame.event.get()) # blit txtbx on the sceen #if exitcountdown%20>10: #txtbx.draw(screen) if txtbx.hasTyped() ==False: if exitcountdown%20>10: txtbx.draw(screen) elif nametyped == False: txtbx.draw(screen) if exitcountdown==30: menu.play_sound(sounds["loser.wav"]) if exitcountdown>=30: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if pygame.key.get_pressed()[K_ESCAPE]: print("exiting") exit() exitloop=False if pygame.key.get_pressed()[K_RETURN]: if not nametyped: scoreObj.addScore(ship.score, txtbx.getText()) nametyped = True scoreObj.printScore() #if pygame.KEYDOWN: #print("exiting") #exit() pygame.display.flip()
def play(): cnt = 0 dec = False eclipse = 0 dececc = False # Define varibale for Level isLevelOne = True # Define variables for freeze power timeForFreezePower = False freezePowerSent = False freezepowercord = [] freezePower = False freezeTimer = 10 # Define variables for bullet power timeForBulletPower = False bulletPowerSent = False bulletpowercord = [] bulletPower = False bulletTimer = 10 # Define variables for danger power timeForDangerPower = False dangerPowerSent = False dangerpowercord = [] dangerPower = False dangerTimer = 10 # Set the width and height of the window width, height = int(pygame.display.Info().current_w), int( pygame.display.Info().current_h) # Create the window screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Initialize the joystick module pygame.joystick.init() # Check if there are any joysticks joystick_count = pygame.joystick.get_count() # If there are any joysticks, initialize the first one, else quit the joystick module if joystick_count: joystick = pygame.joystick.Joystick(0) joystick.init() JS = True # Set joystick position if JS: stick0 = "right" else: pygame.joystick.quit() JS = False # Set pressed keys keys = [False, False, False, False] JSkeys = [False, False, False, False] # Set player position playerpos = [100, 100] # Make an list for the accuracy acc = [0, 0] # Make an list for where the arrows are arrows = [] # Set the timer for spawning badgers badtimer = 100 badtimer1 = 0 # Make an list for where the badgers are badguys = [[800, 100]] # Set your health value healthvalue = 194 # Set the wait times waitforexit = 0 waitforarrows = 0 waitforballoons = 0 waitforballoons2 = 2 # Set displaying balloon on/off balloon1display = False balloon2display = False # Set start ticks startticks = pygame.time.get_ticks() # Initialize the mixer (for sound) pygame.mixer.init() # Set title pygame.display.set_caption("Galaxy Wars") # Load images # Load the players image player = pygame.image.load("resources/images/dude.png") # Load the power freeze image power_freeze = pygame.image.load("resources/images/power_freeze.png") # Load thunder image thunder = pygame.image.load("resources/images/thunder.png") # Load backgrounds bgmorning = pygame.image.load("resources/images/bgmorning.jpg") # Load the power bullet image power_bullet = pygame.image.load("resources/images/power_bullet.png") # Load the power danger image power_danger = pygame.image.load("resources/images/power_danger.png") # Green Bullet bullet_green = pygame.image.load("resources/images/bullet_green.png") # Load the background image bgmain = pygame.image.load("resources/images/starfield.png") # Red Sun level 1 sunred = pygame.image.load("resources/images/SunRed.png") # Blue Sun Danger sunblue = pygame.image.load("resources/images/SunBlue.png") # Load the image of the castles castle = pygame.image.load("resources/images/castle.png") # Load the image for the arrows arrow = pygame.image.load("resources/images/bullet.png") # Load the image for the badgers badguyimg1 = pygame.image.load("resources/images/badguy.png") badguyimg = badguyimg1 # Load the overlays greenoverlay = pygame.image.load("resources/images/greenoverlay.png") redoverlay = pygame.image.load("resources/images/redoverlay.png") # Load the healthbar images healthbar = pygame.image.load("resources/images/healthbar.png") health = pygame.image.load("resources/images/health.png") # Load the text balloons balloon1 = pygame.image.load("resources/images/balloon1.png") balloon2 = pygame.image.load("resources/images/balloon2.png") # Load audio hit = pygame.mixer.Sound("resources/audio/explode.wav") enemy = pygame.mixer.Sound("resources/audio/enemy.wav") shoot = pygame.mixer.Sound("resources/audio/shoot.wav") # Set the audio volume hit.set_volume(0.15) enemy.set_volume(0.15) shoot.set_volume(0.15) # Set the background music pygame.mixer.music.load('resources/audio/background.mp3') pygame.mixer.music.play(-1, 0.0) pygame.mixer.music.set_volume(0.30) # Set positions castle1 = (0, height / 16) castle2 = (0, height / 3.5) castle3 = (0, height / 2) castle4 = (0, height / 1.4) # Set display mode prevFS = settings.getFullscreen() if settings.getFullscreen() == True: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) elif settings.getFullscreen() == False: screen = pygame.display.set_mode((width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) # Keep looping through running = 1 exitcode = 0 while running: # Set display mode if changed if prevFS != settings.getFullscreen(): if settings.getFullscreen() == True: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN) prevFS = settings.getFullscreen() elif settings.getFullscreen() == False: screen = pygame.display.set_mode( (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF) prevFS = settings.getFullscreen() # Set joystick buttons, if there are any if JS: buttonUP = joystick.get_button(4) buttonRIGHT = joystick.get_button(5) buttonDOWN = joystick.get_button(6) buttonLEFT = joystick.get_button(7) buttonX = joystick.get_button(14) stick0a = joystick.get_axis(0) stick0b = joystick.get_axis(1) # Check for stick0's position if JS: if stick0a <= -0.5 and stick0b <= -0.5: stick0 = "leftup" elif stick0a <= -0.5 and stick0b >= 0.5: stick0 = "leftdown" elif stick0a >= 0.5 and stick0b <= -0.5: stick0 = "rightup" elif stick0a >= 0.5 and stick0b >= 0.5: stick0 = "rightdown" elif stick0a <= -0.5: stick0 = "left" elif stick0a >= 0.5: stick0 = "right" elif stick0b <= -0.5: stick0 = "up" elif stick0b >= 0.5: stick0 = "down" badtimer -= 1 # Clear the screen before drawing it again screen.fill(0) # Draw the background if isLevelOne: screen.blit(bgmorning, (0, 0)) else: screen.blit(bgmain, (0, 0)) if acc[0] > 25: isLevelOne = False if dangerPower and isLevelOne == False: eclipse += 10 if eclipse > 100: screen.blit(sunblue, (width // 2, 0)) else: screen.blit(sunred, (width // 2, 0)) if eclipse % 20 == 0: screen.blit(thunder, (width // 2, 0)) if eclipse > 200: eclipse = 0 else: screen.blit(sunred, (width // 2, 0)) # Draw the castles screen.blit(castle, castle1) screen.blit(castle, castle2) screen.blit(castle, castle3) screen.blit(castle, castle4) # Set player position and rotation if JS == False: position = pygame.mouse.get_pos() angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26)) playerrot = pygame.transform.rotate(player, 360 - angle * 57.29) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif JS == True: if stick0 == "left": playerrot = pygame.transform.rotate(player, 180) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "right": playerrot = pygame.transform.rotate(player, 0) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "up": playerrot = pygame.transform.rotate(player, 90) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "down": playerrot = pygame.transform.rotate(player, 270) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "leftup": playerrot = pygame.transform.rotate(player, 135) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "leftdown": playerrot = pygame.transform.rotate(player, 225) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "rightup": playerrot = pygame.transform.rotate(player, 45) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) elif stick0 == "rightdown": playerrot = pygame.transform.rotate(player, 315) playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2) screen.blit(playerrot, playerpos1) # Draw arrows for bullet in arrows: index = 0 velx = 0 vely = 0 if bulletPower and dangerPower is False: velx = math.cos(bullet[0]) * 30 vely = math.sin(bullet[0]) * 30 elif dangerPower is False: velx = math.cos(bullet[0]) * 20 vely = math.sin(bullet[0]) * 20 elif dangerPower: velx = math.cos(bullet[0]) * 10 vely = math.sin(bullet[0]) * 10 bullet[1] += velx bullet[2] += vely if bullet[1] < -64 or bullet[1] > width or bullet[ 2] < -64 or bullet[2] > height: arrows.pop(index) index += 1 for projectile in arrows: arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29) bullet_green1 = pygame.transform.rotate( bullet_green, 360 - projectile[0] * 57.29) if bulletPower: screen.blit(bullet_green1, (projectile[1], projectile[2])) else: screen.blit(arrow1, (projectile[1], projectile[2])) # Draw badguys if badtimer == 0: badheight1 = height / 9.6 badheight2 = height / 1.1 badheight = random.randint(int(badheight1), int(badheight2)) badguys.append([width, badheight]) badtimer = 100 - (badtimer1 * 2) if badtimer1 >= 35: badtimer1 = 35 else: badtimer1 += 5 index = 0 for badguy in badguys: if badguy[0] < -64: badguys.pop(index) if freezePower is False and dangerPower is False: badguy[0] -= 7 if cnt < 30 and dec is False: badguy[1] += 7 cnt += 1 else: dec = True cnt -= 1 badguy[1] -= 7 if cnt is 0: dec = False elif dangerPower: badguy[0] -= 20 xx = random.randint(0, 1) if cnt < 30 and dec is False: if xx == 1: badguy[1] += 7 cnt += 1 else: dec = True cnt -= 1 if xx == 1: badguy[1] -= 7 if cnt is 0: dec = False # Attack castle badrect = pygame.Rect(badguyimg.get_rect()) badrect.top = badguy[1] badrect.left = badguy[0] if badrect.left < 64: hit.play() healthvalue -= random.randint(5, 20) badguys.pop(index) # Check for collisions index1 = 0 for bullet in arrows: bullrect = pygame.Rect(arrow.get_rect()) bullrect.left = bullet[1] bullrect.top = bullet[2] if badrect.colliderect(bullrect): enemy.play() acc[0] += 1 if acc[0] % 3 == 0 and isLevelOne == False: timeForDangerPower = True else: timeForDangerPower = False if acc[0] % 5 == 0: timeForFreezePower = True else: timeForFreezePower = False if acc[0] % 7 == 0: timeForBulletPower = True else: timeForBulletPower = False badguys.pop(index) if bulletPower == False: arrows.pop(index1) index1 += 1 # Next bad guy index += 1 # Draw badgers for badguy in badguys: screen.blit(badguyimg, badguy) # Draw power if power sent is true if dangerPowerSent: dangerpowercord[0] -= 7 screen.blit(power_danger, dangerpowercord) if dangerpowercord[0] < 0: dangerPowerSent = False if bulletPowerSent: bulletpowercord[0] -= 7 screen.blit(power_bullet, bulletpowercord) if bulletpowercord[0] < 0: bulletPowerSent = False if freezePowerSent: freezepowercord[0] -= 7 screen.blit(power_freeze, freezepowercord) if freezepowercord[0] < 0: freezePowerSent = False if timeForDangerPower and dangerPowerSent == False: powerheight1 = height / 9.6 powerheight2 = height / 1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) dangerpowercord = [width, playerpos[1]] print "dangerPowerSent" dangerPowerSent = True timeForDangerPower = False screen.blit(power_danger, dangerpowercord) if timeForBulletPower and bulletPowerSent == False: powerheight1 = height / 9.6 powerheight2 = height / 1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) bulletpowercord = [width, powerheight] print "bulletPowerSent" bulletPowerSent = True timeForBulletPower = False screen.blit(power_bullet, bulletpowercord) if timeForFreezePower and freezePowerSent == False: powerheight1 = height / 9.6 powerheight2 = height / 1.1 powerheight = random.randint(int(powerheight1), int(powerheight2)) freezepowercord = [width, powerheight] print "freezePowerSent" freezePowerSent = True timeForFreezePower = False screen.blit(power_freeze, freezepowercord) if dangerPower: dangerTimer += 10 if dangerTimer > 2000: dangerPower = False dangerTimer = 0 if bulletPower: bulletTimer += 10 if bulletTimer > 2000: bulletPower = False bulletTimer = 0 if freezePower: freezeTimer += 10 if freezeTimer > 1000: freezePower = False freezeTimer = 0 # Check if power is Taken if dangerPowerSent: dangerpowerRect = pygame.Rect(power_danger.get_rect()) playerRect = pygame.Rect(player.get_rect()) dangerpowerRect.top = dangerpowercord[1] dangerpowerRect.left = dangerpowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if dangerpowerRect.colliderect(playerRect): dangerPower = True dangerPowerSent = False if bulletPowerSent: bullpowerRect = pygame.Rect(power_bullet.get_rect()) playerRect = pygame.Rect(player.get_rect()) bullpowerRect.top = bulletpowercord[1] bullpowerRect.left = bulletpowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if bullpowerRect.colliderect(playerRect): bulletPower = True bulletPowerSent = False if freezePowerSent: powerRect = pygame.Rect(power_freeze.get_rect()) playerRect = pygame.Rect(player.get_rect()) powerRect.top = freezepowercord[1] powerRect.left = freezepowercord[0] playerRect.top = playerpos[1] playerRect.left = playerpos[0] if powerRect.colliderect(playerRect): freezePower = True print "Collision Detected" freezePowerSent = False # Draw clock font = pygame.font.Font("freesansbold.ttf", 24) survivedtext = font.render(str("Score: " + str(acc[0])), True, (255, 0, 0)) leveltext = "" if isLevelOne: leveltext = font.render(str("Level: 1"), True, (0, 0, 255)) else: leveltext = font.render(str("Level: 2"), True, (0, 0, 255)) levelrect = leveltext.get_rect() levelrect.topleft = [250, 5] screen.blit(leveltext, levelrect) textRect = survivedtext.get_rect() textRect.topright = [width - 5, 5] screen.blit(survivedtext, textRect) # Draw health bar screen.blit(healthbar, (5, 5)) for health1 in range(healthvalue): screen.blit(health, (health1 + 8, 8)) # Loop through the events for event in pygame.event.get(): # Check if the event is the X button if event.type == pygame.QUIT: # If it is stop the music and go back to the main menu pygame.mixer.music.stop() menu.launch() if event.type == pygame.KEYDOWN: # Move up if event.key == K_w: keys[0] = True elif event.key == K_UP: keys[0] = True # Move left elif event.key == K_a: keys[1] = True elif event.key == K_LEFT: keys[1] = True # Move down elif event.key == K_s: keys[2] = True elif event.key == K_DOWN: keys[2] = True # Move right elif event.key == K_d: keys[3] = True elif event.key == K_RIGHT: keys[3] = True # Quit by pressing escape elif event.key == K_ESCAPE: pygame.mixer.music.stop() menu.launch() # Fullscreen by pressing F4 elif event.key == K_F4: settings.changeFullscreen() elif event.key == pygame.K_SPACE: if waitforarrows == 0: shoot.play() position = pygame.mouse.get_pos() acc[1] += 1 arrows.append([ math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)), playerpos1[0] + 32, playerpos1[1] + 32 ]) # Set wait time for arrows in frames waitforarrows = 15 if waitforballoons2: waitforballoons2 -= 1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2 = 2 if event.type == pygame.KEYUP: # Move up if event.key == pygame.K_w: keys[0] = False elif event.key == pygame.K_UP: keys[0] = False # Move left elif event.key == pygame.K_a: keys[1] = False elif event.key == pygame.K_LEFT: keys[1] = False # Move down elif event.key == pygame.K_s: keys[2] = False elif event.key == pygame.K_DOWN: keys[2] = False # Move right elif event.key == pygame.K_d: keys[3] = False elif event.key == pygame.K_RIGHT: keys[3] = False if waitforarrows: waitforarrows -= 1 waitforballoons = waitforarrows # Display balloon if waitforballoons: waitforballoons -= 1 if balloon1display: screen.blit(balloon1, (playerpos[0] + 10, playerpos[1] - 60)) elif balloon2display: screen.blit(balloon2, (playerpos[0] + 10, playerpos[1] - 60)) else: balloon1display = False balloon2display = False # Check if there are any joysticks if JS: # Check if UP is pressed if buttonUP: JSkeys[0] = True # Check if RIGHT is pressed elif buttonRIGHT: JSkeys[3] = True # Check if DOWN is pressed elif buttonDOWN: JSkeys[2] = True # Check if LEFT is pressed elif buttonLEFT: JSkeys[1] = True else: JSkeys[0] = False JSkeys[1] = False JSkeys[2] = False JSkeys[3] = False # Check of X is pressed if buttonX: if waitforarrows == 0: shoot.play() acc[1] += 1 if stick0 == "left": arrows.append( [3, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "right": arrows.append( [0, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "up": arrows.append( [-1.5, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "down": arrows.append( [1.5, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "leftup": arrows.append( [-2.25, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "leftdown": arrows.append( [2.25, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "rightup": arrows.append( [-0.75, playerpos1[0] + 32, playerpos1[1] + 32]) elif stick0 == "rightdown": arrows.append( [0.75, playerpos1[0] + 32, playerpos1[1] + 32]) # Set wait time for arrows in frames waitforarrows = 15 if waitforballoons2: waitforballoons2 -= 1 else: # Choose balloon balloonnr = random.randint(1, 2) if balloonnr == 1: balloon1display = True elif balloonnr == 2: balloon2display = True waitforballoons2 = 2 # Move player # Up if keys[0]: playerpos[1] -= 5 # Down elif keys[2]: playerpos[1] += 5 # Left if keys[1]: playerpos[0] -= 5 # Right elif keys[3]: playerpos[0] += 5 # Move player with JoyStick # Up if JSkeys[0]: playerpos[1] -= 5 # Down elif JSkeys[2]: playerpos[1] += 5 # Left if JSkeys[1]: playerpos[0] -= 5 # Right elif JSkeys[3]: playerpos[0] += 5 # Win/Lose check # Win # Lose if healthvalue <= 0: running = 0 exitcode = 0 if acc[1] != 0: accuracy = acc[0] * 1.0 / acc[1] * 100 else: accuracy = 0 # Flip the display pygame.display.flip() # Stop the music pygame.mixer.music.stop() # Win/lose display # Lose if exitcode == 0: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text gameover = bigfont.render("Game over!", True, (255, 0, 0)) gameoverRect = gameover.get_rect() gameoverRect.centerx = screen.get_rect().centerx gameoverRect.centery = screen.get_rect().centery - 24 text = font.render("Accuracy: " + str(accuracy) + "%", True, (255, 0, 0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery + 24 # Draw red overlay for x in range(width / redoverlay.get_width() + 1): for y in range(height / redoverlay.get_height() + 1): screen.blit(redoverlay, (x * 100, y * 100)) # Draw text screen.blit(gameover, gameoverRect) screen.blit(text, textRect) # Win else: # Initialize the font pygame.font.init() # Set font font = pygame.font.Font("freesansbold.ttf", 24) bigfont = pygame.font.Font("freesansbold.ttf", 48) # Render text youwin = bigfont.render("You win!", True, (0, 255, 0)) youwinRect = youwin.get_rect() youwinRect.centerx = screen.get_rect().centerx youwinRect.centery = screen.get_rect().centery - 24 text = font.render("Accuracy: " + str(accuracy) + "%", True, (0, 255, 0)) textRect = text.get_rect() textRect.centerx = screen.get_rect().centerx textRect.centery = screen.get_rect().centery + 24 # Draw green overlay for x in range(width / greenoverlay.get_width() + 1): for y in range(height / greenoverlay.get_height() + 1): screen.blit(greenoverlay, (x * 100, y * 100)) # Draw text screen.blit(youwin, youwinRect) screen.blit(text, textRect) # Exit automatic when the game is stopped while 1: waitforexit += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if waitforexit == 1000: menu.launch() # Update the screen pygame.display.flip()
#!/usr/bin/env python2 import menu # Launch menu menu.launch()
import menu # Launch menu menu.launch()
menu.Option(MULTIPLAYER_LOCAL,"LOCAL",True), #menu.Option(HOST,"HOST",True), #menu.Option(CONNECT,"CONNECT"), menu.Option(MENU,"MAIN MENU")] self.state = menu.launch(self.screen,options) elif self.state == MULTIPLAYER_LOCAL: print "MULTIPLAYER LOCAL" try: multiplayer.MultiPlayerLocal(self.screen) except EndGame, e: print e.msg self.state = MENU elif self.state == HOST: print "HOST GAME" options = [menu.Option(MULTIPLAYER,"BACK")] self.state = menu.launch(self.screen,options) elif self.state == CONNECT: print "CONNECT TO GAME" options = [menu.Option(MULTIPLAYER,"BACK")] self.state = menu.launch(self.screen,options) elif self.state == INSTRUCTIONS: print "INSTRUCTIONS" options = [menu.Item(" CONTROLS "), menu.Item(" "), menu.Item(" PLAYER 1 "), menu.Item(" UP : W "), menu.Item(" DOWN : S "), menu.Item(" "), menu.Item(" PLAYER 2 "), menu.Item(" UP : UP ARROW "), menu.Item("DOWN : DOWN ARROW"),
pygame.display.flip() BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 192, 203) BLUE = (176, 196, 222) YELLOW = (218, 165, 32) # Initialize Pygame pygame.init() pygame.display.set_caption(GAME_TITLE) screen = pygame.display.set_mode((300, 300)) # Launch the menu and receives instructions over which player starts first HUMAN_STARTS = menu.launch(screen) # Launch the game running = True while running: # AI makes the first move if it starts first if not HUMAN_STARTS: AI = Player(CODE_PLAYER_1) Human = Player(CODE_PLAYER_2) board.decide(greedy=True) else: AI = Player(CODE_PLAYER_2) Human = Player(CODE_PLAYER_1) # Update the screen
import streamlit as st import menu as main_menu if __name__ == "__main__": #create the dashboard heading st.title('STN Project') st.markdown('## Simulate news spreading info over a social network') st.markdown('Using data gathered from twitter and simulated') st.markdown('<-- Open side menu to run functionalities') main_menu.launch()