def main(): game = imports.ini.Game() game.create() player = imports.person.Person("spritePlayer.png") musica = music.Music() musica.playSong() map1 = map.Map() map1.create() while not game.gameOverBool: keys = game.getKey() player.move(keys) game.drawMap(map1) game.draw(player) game.update() game.destroy()
def initGame(self): if self.mode == self.c.SINGLE: self.printText("Level %d-%d" % (self.stage,self.level),(40,15)) self.field = board.Board(self.stage, self.level) self.timer = 3*60+1 elif self.mode == self.c.MULTI: self.printText("Multiplayer",(40,15)) self.field = board.Board(0,0) self.timer = 5*60+1 self.drawBoard() self.drawInterface() self.updateTimer() # players do not have to be reinitialized in single player after the first time if self.firstRun: self.firstRun = False self.initPlayers() else: self.resetPlayerPosition(self.user,False) # no enemies in multiplayer if self.mode == self.c.SINGLE: self.initEnemies() # music player mp = music.Music() mp.playMusic(self.mode) self.runGame()
def init_game(self): if self.mode == self.c.SINGLE: self.print_text("Level %d-%d" % (self.stage, self.level), (40, 15)) self.field = board.Board(self.stage, self.level) self.timer = 3 * 60 + 1 elif self.mode == self.c.MULTI: self.print_text("Multiplayer", (40, 15)) self.field = board.Board(0, 0) self.timer = 5 * 60 + 1 self.draw_board() self.draw_interface() self.update_timer() # Players do not have to be reinitialized in single player after the first time if self.first_run: self.first_run = False self.init_players() else: self.reset_player_position(self.user, False) # No enemies in multiplayer if self.mode == self.c.SINGLE: self.init_enemies() # Music player mp = music.Music() mp.play_music(self.mode) self.run_game()
def __init__(self, debug=False): self.music = music.Music() config = Config('pi.ini') self.password = config('keyserver', 'password') self.debug = debug self.filelog = filelog.Log() self.log('KeyPadServer Start', True)
def initGame(self): if self.mode == self.c.START: self.printText("Level %d-%d" % (self.stage, self.level), (40, 15)) self.field = board.Board(self.stage, self.level) self.timer = 3 * 60 + 1 self.drawBoard() self.drawInterface() self.updateTimer() #player doesn't have to be reinitialized after the first time if self.firstRun: self.firstRun = False self.initPlayers() else: self.resetPlayerPosition(self.user, False) if self.mode == self.c.START: self.initEnemies() #music player mp = music.Music() mp.playMusic(self.mode) self.runGame()
def victory(self): self.gameIsActive = False self.user.setScore(500) self.level += 1 if self.level > 6: self.stage += 1 self.level = 1 mp = music.Music() mp.playSound("victory") time.sleep(2)
def reset(self): self.sfx = music.Music() self.sfx.play_sfx() self.speed = 1 self.tunnel = tunnel.Tunnel() self.score = 0 self.is_paused = False self.plane = plane.Plane() self.jump_velo = -1 self.is_game_over = False
def __init__(self): print("Creating..") self.x = 400 self.y = 300 self.speed = 150 self.head_frame = 0 self.body_frame = 0 self.tear_image_head = load_image('../resource/Issac.png') self.triple_image_head = load_image('../resource/Issac_Triple.png') self.razor_image_head = load_image('../resource/Issac_Razor.png') self.image_body = load_image('../resource/Issac.png') self.hit_image = load_image('../resource/hit.png') self.tear_image = load_image('../resource/Tear_Item.png') self.triple_image = load_image('../resource/Triple_Item.png') self.razor_image = load_image('../resource/Razor_Item.png') self.head_state = 5 self.body_state = ISSAC_IMAGE_DOWN self.direction = ISSAC_DIRECTION_DOWN self.isMove = False self.isLeft = False self.isRight = False self.isUp = False self.isDown = False self.tearlist = [] self.tear_shoot_cooltime_count = 0 self.isCoolTime = False self.eye_flicker = 0 self.bomb_num = 5 self.bomblist = [] self.life = 9 self.key_num = 0 self.weapon_kind = Issac.TEAR self.ID = ID.ISSAC self.isHit = False self.hit_frame = 0 self.hit_count = ISSAC_HIT_COUNT self.isGetItem = False self.get_item_frame = 0 self.isSpaceDown = False self.slow = False self.issac_music = music.Music()
def victory(self): self.gameActive = False self.user.setScore(1000) #score when level is won self.level += 1 if self.level > 6: self.stage += 1 self.level = 1 mp = music.Music() mp.playSound("victory") print 'victory fanfare' time.sleep(5) #time for victory fanfare to finish
def main(): wav_player = music.Music() wav_player.SDcard_init() while True: if wav_player.index is not wav_player.last_index: wav_player.Display_list() wav_player.index = wav_player.last_index wav_player.Keyboard_scanf() if wav_player.play_status == 1: wav_player.Audio_init() wav_player.Audio_play() wav_player.Audio_close()
def __init__(self): print("Creating Bomb") self.x = 0 self.y = 0 self.bomb_frame = 0 self.bomb_explosion_frame = 0 self.bomb_image = load_image('../resource/Bomb.png') self.bomb_explosion_image = load_image('../resource/BombExplosion.png') self.isExplode = False self.isEnd = False self.count = 0 self.ID = ID.BOMB self.damage = 5 self.bomb_music = music.Music()
def enter(): global play_UI, monster_data, play_music, win_image, lose_image #open_canvas() play_UI = UI.UI() play_issac = issac.Issac() play_room = room.Room() play_music = music.Music() win_image = load_image('../resource/Win.png') lose_image = load_image('../resource/Lose.png') play_UI.SetData(play_issac.GetBombNum(), play_issac.GetLifeNum(), play_issac.GetKeyNum(), play_issac.GetWeaponKind()) game_world.add_object(play_issac, game_world.LAYER_ISSAC) game_world.add_object(play_UI, game_world.LAYER_BG) game_world.add_object(play_room, game_world.LAYER_BG) play_music.PlayStage1BGM() ready_game()
def activateBomb(self, bomb): if not bomb.triggered: bomb.explode() self.triggerBombChain(bomb) self.bombs.remove(bomb) tile = self.field.getTile(bomb.position) tile.bomb = None self.blit(tile.getImage(), bomb.position) self.resetTiles.append(bomb.position) mp = music.Music() mp.playSound("bomb") explosion = pygame.image.load(self.c.IMAGE_PATH + "explosion_a.png").convert() self.blit(explosion, bomb.position)
def __init__(self): # Consts self._PLAYGROUND_WIDTH = 10 # PLGR - short for playground self._PLAYGROUND_HEIGHT = 20 self._MARGIN = 20 self._SCALE = 30 # px self._WIDTH = self._SCALE * self._PLAYGROUND_WIDTH * 2 + 2 * self._MARGIN # *2, bo pole na wynik, menu self._HEIGHT = self._SCALE * self._PLAYGROUND_HEIGHT + 2 * self._MARGIN self._FPS = 30 self._RUNNING = True self._PAUSED = False self._SWAPPED = False self._SCORES = False self._MOVE_SIDE_TIME = time() self._MOVE_DOWN_TIME = time() self._MOVE_SIDE_SPEED = 0 self._MOVE_DOWN_SPEED = 0.4 self._HIDE_REFALL = 0 self._SCORE = 0 self._LEVEL = 1 # initialization pygame.init() # Pygame self.musicplayer = ms.Music() # Music self.screen = pygame.display.set_mode((self._WIDTH, self._HEIGHT)) # Screen self.clock = pygame.time.Clock() # clock pygame.display.set_caption( "Tetris - Adrian Janakiewicz (C) 2017 _FPS: {:.2f}".format(self.clock.get_fps())) # Window caption self.playground = pg.Playground(self.screen, self._PLAYGROUND_WIDTH, self._PLAYGROUND_HEIGHT, self._SCALE, self._MARGIN) self.utility_window = ud.UtilityWindow(self.screen, self._PLAYGROUND_WIDTH, self._PLAYGROUND_HEIGHT, self._SCALE, self._MARGIN) self.scores_screen = sc.Scores(self.screen, self._WIDTH, self._HEIGHT) self.falling = bl.Tetromino(-5, 3) self.next_piece = bl.Tetromino(2, 13) self.utility_window.next_piece = self.next_piece
def reset(self): self.score = 0 self.is_game_over = False self.all_sprites = pygame.sprite.Group() self.hero_bullets = pygame.sprite.Group() self.enermy_bullets = pygame.sprite.Group() self.heros = pygame.sprite.Group() self.enermys = pygame.sprite.Group() self.bomb_props = pygame.sprite.Group() self.bullet_props = pygame.sprite.Group() self.m = music.Music() self.game_helper = hit.GameHelper() # self.game_over_button = Npc.Button("gameover.png") # self.game_over_button_clicked = False # 初始化英雄 self.__init_hero()
def initGame(self): """ Begin game mode with correct stats for board """ if self.mode == self.c.SINGLE: self.printText("Level %d-%d" % (self.stage, self.level), (40, 15)) self.field = board.Board(self.stage, self.level) self.timer = 3 * 60 + 1 elif self.mode == self.c.MULTI: self.printText("Multiplayer", (40, 15)) self.field = board.Board(0, 0) self.timer = 5 * 60 + 1 self.drawBoard() self.drawInterface() self.updateTimer() self.move_dict = { 0: pygame.K_BACKSPACE, 1: pygame.K_UP, 2: pygame.K_DOWN, 3: pygame.K_LEFT, 4: pygame.K_RIGHT, 5: pygame.K_SPACE } # Players do not have to be reinitialized in single player after the first time if self.firstRun: self.firstRun = False self.initPlayers() else: self.resetPlayerPosition(self.user, False) # No enemies in multiplayer if self.mode == self.c.SINGLE: self.initEnemies(self.level * 2 + 1) # Music player mp = music.Music() mp.playMusic(self.mode) self.runGame()
def __init__(self): # display constants self.size_display = constants.DISPLAY_SIZE # init game pygame.init() pygame.display.init() pygame.display.set_caption(constants.GAME_NAME) self.screen = pygame.display.set_mode(self.size_display) self.game = None self.quit_station = False self.current_object = 0 self.objects = [] self.SPACES_TEXT = 60 self.TOP_BUFFER = 200 self.CENTER_OF_SCREEN = constants.SCREEN_WIDTH // 2 self.background_image = resources.BACKGROUND_IMAGE_MENU_LOADED self.mixer = music.Music()
def object_create(connection, address): print(f'started object creation from {address}') name = connection.recv(settings.EXCHANGE_SIZE).decode('utf-8').strip() print(f'{name} received from {address}') file_name = connection.recv(settings.EXCHANGE_SIZE).decode('utf-8').strip() print(f'file name received {file_name} from {address}') file_name = file_name.split('.')[0] + '_' + str(int(time.time()) % 10000) + '.' + file_name.split('.')[1] music_file = open(os.path.join(settings.STORAGE, file_name), "wb") print(f'file ({file_name}) download started from {address}') data = connection.recv(settings.EXCHANGE_SIZE) while data: music_file.write(data) data = connection.recv(settings.EXCHANGE_SIZE) music_file.close() print(f'file ({file_name}) created success from {address}') music_obj = music.Music(file_name, name) music.playlist.add_music(music_obj) print(f'music object with id: {music_obj.id} created success from {address}')
def initGame(self): """ Initializes the game with necessary attributes. """ self.printText("Level %d-%d" % (self.stage, self.level), (40, 15)) self.field = board.Board(self.stage, self.level) self.timer = 3 * 60 + 1 self.drawBoard() self.drawInterface() self.updateTimer() # Dictionary of Key Bindings self.move_dict = { 0: pygame.K_BACKSPACE, 1: pygame.K_UP, 2: pygame.K_DOWN, 3: pygame.K_LEFT, 4: pygame.K_RIGHT, 5: pygame.K_SPACE } # Playerse only intialized in the first run if self.firstRun: self.firstRun = False self.initPlayers() else: self.resetPlayerPosition(self.user, False) # Initialize Enemies self.initEnemies(self.level * 2 + 1) # Music players mp = music.Music() mp.playMusic(self.mode) self.runGame()
async def on_ready(): utils.print_log('warning', f'{bot.user} has connected to Discord!') async for guild in bot.fetch_guilds(): utils.print_log('warning', f'{guild.name}[{guild.id}]') bot.add_cog(lol.LOL(bot)) bot.add_cog(music.Music(bot))
if (musicfile.endswith(".mp3")) ] # Choosing k training samples lib = len(library) print "Total Samples: ", lib k = int(round(0.4 * lib)) print "k: ", k k_chosen = random.sample(range(0, lib), k) print "Songs Chosen for Training: ", k_chosen # Define Training and Testing Set training = [] testing = [] for i in range(lib): temp = music.Music(library[i]) if (i in k_chosen) == True: training.append(temp) else: testing.append(temp) # Play Songs allowing user to like or dislike # Dummy Music Player print "\n0 if dislike" print "1 if like" for i in training: user_input = raw_input("\n" + str(i.name) + ": ") if user_input == "1": i.label = 1 else:
import music import index daniel_caesar = music.Music("Get You, Japanese Denim", "Daniel Caesar", "http://res.cloudinary.com/thefader/image/upload/IMG_6801_zisbnb.jpg", "https://www.youtube.com/watch?v=6rVYRiksbRE") jerreau = music.Music("Really Got It", "Jerreau Vandel", "http://stereochampions.com/wp-content/uploads/2016/06/jerreau-2.jpg", "https://www.youtube.com/watch?v=hWI6-y7XHWk") sir = music.Music("something", "SiR", "http://www.okayplayer.com/wp-content/uploads/2015/10/sir-soulection-beats-1.jpg", "https://www.youtube.com/watch?v=Y1Mmy5LcN-4") stro = music.Music("live set", "Stro Elliot", "http://www.djdmac.com/blog/wp-content/uploads/2014/06/StroElliot.jpg", "https://www.youtube.com/watch?v=iwMoPG5RrxI") jmsn = music.Music("cruel intentions, hypnotized", "JMSN", "http://www.whudat.de/images/2016/05/JMSN-Soulection-Cruel-Intentions-Hypnotize-WHUDAT.jpg", "https://www.youtube.com/watch?v=ab5svfSft4c") ravyn = music.Music("free room, blossum dearie", "Ravyn Lenae", "http://s3-us-west-1.amazonaws.com/ones2watch/blog_145626621225.jpg",
show_parameters[ART_CAR_RING_PARAM] = oldest_ring show_parameters[SEVEN_PAL_BEAT_PARAM_START] = artCarHandler.get_ring_animation(oldest_ring) do_show(None, None) else: # no art car detected past threshold tell any rings playing hello animations to stop # send hello animation stop message broadcast for target ring for ring_num_stop in artCarHandler.rings_to_stop_hello_animation: show_parameters[ART_CAR_RING_PARAM] = ring_num_stop show_parameters[SEVEN_PAL_BEAT_PARAM_START] = 0 do_show(None, None) if BRAIN_DEBUG: do_list(None, None) print sorted(control_messages.keys()) mega_music = music.Music() running = True while running: try: if len(message_queues) == 0: timeout = None # wait indefinitely when there are no remotes else: timeout = next_timesync_sec - time.time() if auto_show: show_timeout = last_show_change_sec + TIME_LIMIT - time.time() if show_timeout < timeout: timeout = show_timeout if timeout <= 0: timeout = 0.01 # could generate writing list here from nonempty message_queues
import pygame import birds import pipes import coins import points import music import medals pygame.init() screen = pygame.display.set_mode((400, 624)) pygame.display.set_caption('Flappy Bird') clock = pygame.time.Clock() audio = music.Music() with open("score", 'r') as file: saved_score = file.readline() class Background(pygame.sprite.Sprite): def __init__(self, image_landscape, image_base, location_landscape, location_base): pygame.sprite.Sprite.__init__(self) self.image_landscape = pygame.image.load(image_landscape) self.image_base = pygame.image.load(image_base) self.rect_landscape = self.image_landscape.get_rect() self.rect_base = self.image_base.get_rect() self.rect_landscape.left, self.rect_landscape.top = location_landscape self.rect_base.left, self.rect_base.top = location_base
import database import music import preferences import structures.currency import structures.user unsaved = False # User information class user = None # Main window window = None # Global objects music = music.Music() # Music player object preferences = preferences.Preferences() # Preferences configuration object database = database.Database() # Database connection object names = structures.user.Names() # Names object currency = structures.currency.Currency() # Currency object # In-game data handling objects players = None clubs = None stadiums = None leagues = None referees = None nations = None companies = None buildings = None merchandise = None
def main(): try: stt = streaming.StreamingSTT( # replace with speech to text credentials username '9d28bb42-fd0f-4126-ac66-2d0882fbe7f8', # replace with speech to text credentials password 'Gixj8klOaqK4') except: fatalFailure() try: tts = textToSpeech.TextToSpeech( # replace with text to speech credentials username '6fa627fb-384e-4586-9a72-185b70c1f09a', # replace with text to speech credentials password 'zQYWSqHEA7dm') except: fatalFailure() try: convo = conversation.Conversation( # replace with conversation credentials username 'bdce62cf-d7f7-4cbc-8b0b-dee6950d1c01', # replace with conversation credentials password 'K5Cmn1aJ3He8', # replace with workspace ID. '0c3cdb7b-3258-457e-a3b7-1b1236fea9c4') except: fatalFailure() # replace with robot name name = 'Bonnie' servo_obj = servo.Servo() servoP = servoProcess.ServoProcess(servo_obj) led_obj = led.Led() ledP = ledProcess.LedProcess(led_obj) music_obj = music.Music("/home/pi/tj-python/resources/music.wav") musicP = musicProcess.MusicProcess(music_obj) time.sleep(.5) ledP.red() time.sleep(.5) ledP.green() time.sleep(.5) ledP.blue() time.sleep(.5) ledP.rainbowCycle(.0001, 99999999999999) # tts.speak("Hello, just a moment while I boot up") servoP.wave(3) """l = led.Led() le = ledProcess.LedProcess(l) print('sleeping') time.sleep(3) print('done sleeping, Lets Strobe') le.strobe() #le.customColor(255,0,0) print('sleeping') time.sleep(3) print('kill in 2') time.sleep(2) le.customColor(255,0,0) #le.stop() print('dead') """ tts.speak('Hello my name is ' + name + ' I am the CBU admissions bot') while True: ledP.blue() try: phrase = stt.get_phrase() except: ledP.red() ledP.orange() if (name in phrase) or ('bunny' in phrase) or ('body' in phrase) or ( 'Bani' in phrase): response = convo.sendMessage(phrase) ledP.green() #response = response.upper() if '~' in response: print('Command Found') if '~RED' in response: ledP.red() response = response.replace('~RED', '', 1) if '~ORANGE' in response: ledP.orange() response = response.replace('~ORANGE', '', 1) if '~YELLOW' in response: ledP.yellow() response = response.replace('~YELLOW', '', 1) if '~GREEN' in response: ledP.green() response = response.replace('~GREEN', '', 1) if '~BLUE' in response: print('Its Blue') ledP.blue() response = response.replace('~BLUE', '', 1) if '~PURPLE' in response: ledP.purple() response = response.replace('~PURPLE', '', 1) if '~PINK' in response: ledP.pink() response = response.replace('~PINK', '', 1) if '~WHITE' in response: ledP.white() response = response.replace('~WHITE', '', 1) if '~RAINBOW' in response: ledP.rainbow() response = response.replace('~RAINBOW', '', 1) if '~RAINBOWCYCLE' in response: ledP.rainbowCycle() response = response.replace('~RAINBOWCYCLE', '', 1) if '~MUSICPLAY' in response: musicP.play() response = response.replace('~MUSICPLAY', '', 1) if '~MUSICSTOP' in response: musicP.stop() response = response.replace('~MUSICSTOP', '', 1) if '~LEDOFF' in response: ledP.off() response = response.replace('~LEDOFF', '', 1) if '~ARMSTOP' in response: servoP.stop() response = response.replace('~ARMSTOP', '', 1) if '~ARMUP' in response: servoP.armUp() response = response.replace('~ARMUP', '', 1) if '~ARMDOWN' in response: servoP.armDown() response = response.replace('~ARMDOWN', '', 1) if '~DANCE' in response: servoP.wave(10) ledP.rainbowCycle(1, 50) response = response.replace('~DANCE', '', 1) if '~ARMANGLE' in response: response = response.replace('~ARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.angle(param) if '~ARMWAVECOUNT' in response: response = response.replace('~ARMWAVECOUNTARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.wave(param) if '~ARMWAVE' in response: servoP.wave(2) response = response.replace('~ARMWAVE', '', 1) if response == '': response = 'awkward silence' ledP.pink() tts.speak(response)
sys.path.append(os.path.split(sys.path[0])[0]) #player intialization player = pygame.image.load('player.png') playerPosition = [0,0] #player position [x,y] playerNextR = [0,0] #spot right to player playerNextL = [0,0] #spot left to player playerNextU = [0,0] #spot up to player playerNextD = [0,0] #spot down to player playerNextRRU = [0,0] #spot right to player playerNextLLD = [0,0] #spot left to player playerNextUUR = [0,0] #spot up to player playerNextDDL = [0,0] #spot down to player #Music mp = music.Music() mp.playMusic(self.mode) #Empty Corners currentTile = tileMap[playerPosition[1]][playerPosition[0]] tileMap[playerPosition[1]][playerPosition[0]] = GROUND playerPosition = [1,0] tileMap[playerPosition[1]][playerPosition[0]] = GROUND playerPosition = [0,1] tileMap[playerPosition[1]][playerPosition[0]] = GROUND playerPosition = [29,0] tileMap[playerPosition[1]][playerPosition[0]] = GROUND playerPosition = [28,0] tileMap[playerPosition[1]][playerPosition[0]] = GROUND playerPosition = [29,1] tileMap[playerPosition[1]][playerPosition[0]] = GROUND
import song import music song = song.Song("september", "funk") music = music.Music(song) print(music.get())
async def on_ready(): activity = discord.Game(name='with Nep') await bot.change_presence(activity=activity) print(f'Logged in as {bot.user.name}') bot.add_cog(music.Music(bot))
def main(self): pygame.init() pygame.mixer.init() pygame.display.set_caption("坦克大战") # 背景 backgroundImage = pygame.image.load("image/background.png") self.startInterface(630, 630) # 游戏开始的时间 time1 = pygame.time.get_ticks() # 游戏主循环 while not self.isOver: self.stage += 1 if self.stage > self.totalStages: break if self.isDifficult: self.stage = 10 self.switchStage(630, 630) # 音效 gameMusic = music.Music() if self.closeMusic: gameMusic.closeMusic() gameMusic.start() #该关卡敌方坦克总数量 totalEnemyTanks = 19 + self.stage #场上存在的敌方坦克总数量 existEnemyTanks = 0 #场上可以存在的敌方坦克总数量 canExistEnemyTanks = min(max(self.stage * 2, 4), 8) #定义精灵组:坦克,我方坦克,敌方坦克,敌方子弹 self.allTankGroup = pygame.sprite.Group() self.mytankGroup = pygame.sprite.Group() self.allEnemyGroup = pygame.sprite.Group() self.mediumEnemyGroup = pygame.sprite.Group() #中型坦克 self.heavyEnemyGroup = pygame.sprite.Group() #重型坦克 self.lightEnemyGroup = pygame.sprite.Group() #轻型坦克 self.enemyBulletGroup = pygame.sprite.Group() #创建地图 gameMap = block.Map(self.stage) #创建我方坦克 myTank1 = myTank.MyTank(1) self.allTankGroup.add(myTank1) self.mytankGroup.add(myTank1) if self.playerNum != 1: myTank2 = myTank.MyTank(2) self.allTankGroup.add(myTank2) self.mytankGroup.add(myTank2) # 创建敌方坦克 for i in range(1, 4): if totalEnemyTanks > 0: totalEnemyTanks -= 1 existEnemyTanks += 1 enemy = enemyTank.EnemyTank(i) self.allTankGroup.add(enemy) self.allEnemyGroup.add(enemy) if enemy.kind == 2: self.mediumEnemyGroup.add(enemy) continue if enemy.kind == 3: self.heavyEnemyGroup.add(enemy) continue self.lightEnemyGroup.add(enemy) # 自定义事件 # 创建敌方坦克延迟200 DELAYEVENT = pygame.constants.USEREVENT pygame.time.set_timer(DELAYEVENT, 200) # 创建敌方子弹延迟1000 ENEMYBULLETNOTCOOLINGEVENT = pygame.constants.USEREVENT + 1 pygame.time.set_timer(ENEMYBULLETNOTCOOLINGEVENT, 1000) # 创建我方子弹延迟200 MYBULLETNOTCOOLINGEVENT = pygame.constants.USEREVENT + 2 pygame.time.set_timer(MYBULLETNOTCOOLINGEVENT, 200) clock = pygame.time.Clock() # 大本营 myhome = home.Home() # 关卡主循环 while True: if self.isOver: break if totalEnemyTanks < 1 and existEnemyTanks < 1: self.isOver = False break for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # 我方子弹冷却事件 if event.type == MYBULLETNOTCOOLINGEVENT: myTank1.bulletNotCooling = True if self.playerNum != 1: myTank2.bulletNotCooling = True # 敌方子弹冷却事件 if event.type == ENEMYBULLETNOTCOOLINGEVENT: for each in self.allEnemyGroup: each.bulletNotCooling = True # 创建敌方坦克 if event.type == DELAYEVENT: if totalEnemyTanks > 0: if existEnemyTanks < canExistEnemyTanks: enemy = enemyTank.EnemyTank() if pygame.sprite.spritecollide(enemy, self.allTankGroup, False, None): break self.allEnemyGroup.add(enemy) self.allTankGroup.add(enemy) existEnemyTanks += 1 if enemy.kind == 2: self.mediumEnemyGroup.add(enemy) elif enemy.kind == 3: self.heavyEnemyGroup.add(enemy) else: self.lightEnemyGroup.add(enemy) # 检查用户的键盘操作 key_pressed = pygame.key.get_pressed() # 玩家一的移动操作 myTank1.move1(self.allTankGroup, gameMap.brickGroup, gameMap.ironGroup) if key_pressed[pygame.K_SPACE]: if not myTank1.bullet.life and myTank1.bulletNotCooling: gameMusic.fire() myTank1.shoot() myTank1.bulletNotCooling = False # 玩家二的移动操作 if self.playerNum != 1: myTank2.move2(self.allTankGroup, gameMap.brickGroup, gameMap.ironGroup) if key_pressed[pygame.K_KP0]: if not myTank2.bullet.life and myTank2.bulletNotCooling: gameMusic.fire() myTank2.shoot() myTank2.bulletNotCooling = False # 实现各种场景 self.screen.blit(backgroundImage, (0, 0)) for each in gameMap.brickGroup: self.screen.blit(each.image, each.rect) for each in gameMap.ironGroup: self.screen.blit(each.image, each.rect) for each in gameMap.grassGroup: self.screen.blit(each.image, each.rect) self.screen.blit(myhome.home, myhome.rect) # 我方坦克1 print(myTank1.life) if myTank1.life > 0: self.screen.blit(myTank1.tank_R0, (myTank1.rect.left, myTank1.rect.top)) # 我方坦克2 if self.playerNum != 1: if myTank2.life > 0: self.screen.blit(myTank2.tank_R0, (myTank2.rect.left, myTank2.rect.top)) # 敌方坦克 enemy.cartoon() enemy.creatImage(self.allEnemyGroup, self.allTankGroup, self.screen, gameMap.brickGroup, gameMap.ironGroup) # 我方坦克1子弹 if myTank1.createBulletImage(self.screen, self.enemyBulletGroup, self.heavyEnemyGroup, self.mediumEnemyGroup, self.lightEnemyGroup, gameMap.brickGroup, gameMap.ironGroup, myhome, gameMusic) == -1: existEnemyTanks -= 1 totalEnemyTanks -= 1 # 我方坦克2子弹 if self.playerNum != 1: if myTank2.createBulletImage(self.screen, self.enemyBulletGroup, self.heavyEnemyGroup, self.mediumEnemyGroup, self.lightEnemyGroup, gameMap.brickGroup, gameMap.ironGroup, myhome, gameMusic) == -1: existEnemyTanks -= 1 totalEnemyTanks -= 1 # 绘制敌人子弹 if self.playerNum == 1: enemy.createBulletImage(self.screen, self.allEnemyGroup, self.enemyBulletGroup, myTank1, gameMusic, self.playerNum, gameMap, myhome) if myTank1.life == 0 or myhome.alive == False: self.isOver = True if self.playerNum != 1: enemy.createBulletImage(self.screen, self.allEnemyGroup, self.enemyBulletGroup, myTank1, gameMusic, self.playerNum, gameMap, myhome, myTank2) if myTank1.life == 0 and myTank2.life == 0: self.isOver = True if myhome.alive == False: self.isOver = True pygame.display.flip() clock.tick(60) time2 = pygame.time.get_ticks() self.time = time2 - time1 if not self.isOver: self.endInterface(630, 630, True, self.time) else: self.endInterface(630, 630, False, self.time)