def dead_screen(name): outro_text = ["Menu", 'Press SPACE to restart'] screen.fill((0, 0, 0)) fon = pygame.transform.scale(load_image('gameover.png'), (900, 700)) screen.blit(fon, (-50, -150)) font = pygame.font.Font('data/font/PressStart2P.ttf', 25) text = font.render(outro_text[1], 1, (100, 255, 100)) text_x = 170 text_y = 480 screen.blit(text, (text_x, text_y)) restart_button = dead_buttons(250, 50, outro_text[0], 270, 370) play_music('dead.mp3') high_score(screen) dead_group.draw(screen) pygame.display.flip() #возвращение ранее выбранной карты при рестарте if name == 'cactus': color = (255, 219, 88) elif name == 'tree': color = (0, 255, 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() if event.type == pygame.MOUSEBUTTONDOWN: if restart_button.check_click(event.pos): start_screen() if event.type == pygame.KEYDOWN: if pygame.key.get_pressed(): if event.key == pygame.K_SPACE: game(velocity, bvelocity, color, isJump, JumpCount, running, name) pygame.display.flip() clock.tick(fps)
def pause(screen, record): size = width, height = screen.get_rect().w, screen.get_rect().h image = load_image('pause_fon.jpg') intro_text = ["Пауза", "Нажмите Esc, чтобы продолжить"] # Создаём экземпляр шрифта font = pygame.font.Font(None, 30) text_coord = 260 # Начальная высота надписи # Рендерим текст стартового экрана построчно (из-за особенностей pygame) # тут я сам не до конца понимаю, поэтому лучше не трогать for line in intro_text: string_rendered = font.render(line, 1, (255, 255, 255)) intro_rect = string_rendered.get_rect() text_coord += 10 intro_rect.top = text_coord intro_rect.x = width // 2 - intro_rect.w // 2 text_coord += intro_rect.height image.blit(string_rendered, intro_rect) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate(record=record) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: return screen.blit(image, (0, 0)) pygame.display.flip()
def gameover_screen(screen): pygame.mixer.init() gayover = pygame.mixer.Sound('data/sounds/gameover1.wav') # Размеры переданного экрана size = width, height = screen.get_rect().w, screen.get_rect().h intro_text = [ "Game over", "", "Игра окончена", "Нажмите любую кнопку чтобы продолжить", "Esc чтобы выйти" ] image = load_image('gameover.jpg') # Создаём экземпляр шрифта font = pygame.font.Font(None, 30) text_coord = 260 # Начальная высота надписи # Рендерим текст стартового экрана построчно (из-за особенностей pygame) # тут я сам не до конца понимаю, поэтому лучше не трогать for line in intro_text: string_rendered = font.render(line, 1, (255, 255, 255)) intro_rect = string_rendered.get_rect() text_coord += 10 intro_rect.top = text_coord intro_rect.x = width // 2 - intro_rect.w // 2 text_coord += intro_rect.height image.blit(string_rendered, intro_rect) gayover.play() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() if event.type == pygame.KEYDOWN: return event.key != pygame.K_ESCAPE screen.blit(image, (0, 0)) pygame.display.flip()
def start_screen(screen): # Размеры переданного экрана size = width, height = screen.get_rect().w, screen.get_rect().h intro_text = ["2D Гонки", "", "Выберите машину"] # Добавляем картинку фона (я заменил на бесплатную картинку) fon = pygame.transform.scale(load_image('fon1.jpg'), (width, height)) # Добавляем её на экран screen.blit(fon, (0, 0)) # Создаём экземпляр шрифта font = pygame.font.Font(None, 30) text_coord = 50 # Начальная высота надписи # Рендерим текст стартового экрана построчно (из-за особенностей pygame) # тут я сам не до конца понимаю, поэтому лучше не трогать for line in intro_text: string_rendered = font.render(line, 1, (0, 0, 0)) intro_rect = string_rendered.get_rect() text_coord += 10 intro_rect.top = text_coord intro_rect.x = width // 2 - intro_rect.w // 2 text_coord += intro_rect.height fon.blit(string_rendered, intro_rect) # Создаём спрайты машин и кнопки car_sprites = pygame.sprite.Group() buttons = pygame.sprite.Group() btn = Button((200, 400), 'start_button.png', buttons) for i in range(4): Car((80 + i * 130, 200), load_image(f'car{i}.png'), car_sprites) selected_car = None selection_rect = pygame.Rect( -10, -10, 1, 1) # Прямоугольник подсвечивающий выбранную машинку while True: screen.blit(fon, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.MOUSEBUTTONDOWN: for car in car_sprites: # Проверяем на какую машину нажали мышкой и сохраняем выбор if car.rect.collidepoint(event.pos): selected_car = car selection_rect = selected_car.rect # Если нажали кнопку и машина выбрана, то возвращаем выбранную машину и начинаем игру if btn.button_pressed(event.pos) and selected_car is not None: return selected_car.image pygame.draw.rect(screen, (0, 0, 0), selection_rect) car_sprites.draw(screen) buttons.draw(screen) pygame.display.flip() clock.tick(FPS)
def start_screen(intro_text, screen, height): global displace background = pygame.transform.scale(load_image('empty.png'), screen.get_size()) screen.blit(background, (0, 0)) text_alpha = pygame.Surface(screen.get_size(), pygame.SRCALPHA) size = int(7 / 90 * height) font = pygame.font.Font("slkscr.ttf", size) buttons = [] y = height / 6 for line in intro_text: string_rendered = font.render(line, 1, [(0, 245, 255), (255, 0, 245)][random.randint(0, 1)]) intro_rect = string_rendered.get_rect() y += height // 10 x = (width - font.size(line)[0]) // 2 + displace text_width, text_height = font.size(line) intro_rect.top = y intro_rect.x = x y += intro_rect.height text_rect = (x - 3 / 8 * size, y - 3 / 2 * size, text_width + 3 / 4 * size, text_height + 3 / 4 * size) buttons.append(text_rect) text_alpha.blit(string_rendered, intro_rect) current_button = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: terminate() elif event.key == pygame.K_w or pygame.key == pygame.K_UP: current_button = (current_button + 1) % len(buttons) elif event.key == pygame.K_s or pygame.key == pygame.K_DOWN: current_button = (current_button - 1) % len(buttons) else: if current_button == 1: return screen.fill((0, 0, 0)) pygame.draw.rect(screen, (255, 255, 255), buttons[current_button], 3) screen.blit(text_alpha, (0, 0)) pygame.display.update() clock.tick(fps)
def finish_screen(outro_text, screen, height): global displace new_alpha = pygame.Surface(screen.get_size(), pygame.SRCALPHA) new_alpha.blit(screen.copy(), (0, 0)) background = pygame.transform.scale(load_image('empty.png'), screen.get_size()) screen.blit(background, (0, 0)) text_alpha = pygame.Surface(screen.get_size(), pygame.SRCALPHA) size = int(5 / 90 * height) font = pygame.font.Font("slkscr.ttf", size) y = height / 9 for line in outro_text: string_rendered = font.render(line, 1, [(0, 245, 255), (255, 0, 245)][random.randint(0, 1)]) intro_rect = string_rendered.get_rect() y += height // 10 x = (width - font.size(line)[0]) // 2 + displace text_width, text_height = font.size(line) intro_rect.top = y intro_rect.x = x y += intro_rect.height text_alpha.blit(string_rendered, intro_rect) y = 5 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: terminate() elif event.key == pygame.K_SPACE: return next_level() screen.fill((0, 0, 0)) screen.blit(new_alpha, (0, y)) screen.blit(text_alpha, (0, 0)) y += 3 new_alpha.fill((255, 255, 255, 255), special_flags=pygame.BLEND_RGBA_MULT) pygame.display.flip() clock.tick(fps)
ANIMATEEVENT = 31 pygame.time.set_timer(ANIMATEEVENT, 80) MOVINGEVENT = 29 pygame.time.set_timer(MOVINGEVENT, 20) SHOOTINGEVENT = 28 pygame.time.set_timer(SHOOTINGEVENT, 50) ENEMYANIMATEEVENT = 27 pygame.time.set_timer(ENEMYANIMATEEVENT, 200) while True: if scenename != oldscenname: downloadSprites.draw(screen) oldscenname = scenename pygame.display.flip() if scenename == "quit": terminate() elif scenename == "menu_": Scene = Menu() scenename= "menu" pygame.mixer.music.set_volume(0.1) elif scenename == "listlevs_": Scene = Listlevs() scenename= "listlevs" elif scenename == "newgame": new_game_save() Scene = Level1("Level_1.txt") scenename = "level1" elif scenename == "continue": pygame.mixer.music.set_volume(0.1) if check_location() == 1: Scene = Level1("Level_1.txt")
def _perform_action(self, action, playerObj, menuObject): if action == MOVE_LEFT: playerObj.moveLeft = True playerObj.direction = 'left' elif action == MOVE_RIGHT: playerObj.moveRight = True playerObj.direction = 'right' elif action == MOVE_DOWN: playerObj.moveDown = True playerObj.direction = 'down' elif action == MOVE_UP: playerObj.moveUp = True playerObj.direction = 'up' elif action == NO_MOVE_LEFT: playerObj.moveLeft = False elif action == NO_MOVE_RIGHT: playerObj.moveRight = False elif action == NO_MOVE_DOWN: playerObj.moveDown = False playerObj.currentWeapon.spriteObj.resetSpriteList() elif action == NO_MOVE_UP: playerObj.moveUp = False elif action == NORMAL_ATTACK: playerObj.isAttacking = 1 elif action == NO_NORMAL_ATTACK: playerObj.isAttacking = 0 elif action == RANGED_ATTACK: if playerObj.arrows > 0: playerObj.arrows -= 1 print "Firing!" playerObj.rangedWeapon.shoot() else: print "No arrows!" elif action == CONTINIOUS_RANGED_ATTACK: if pygame.time.get_ticks( ) > playerObj.lastFired + 500 and playerObj.arrows > 0: playerObj.rangedWeapon.shoot() playerObj.lastFired = pygame.time.get_ticks() playerObj.arrows -= 1 else: if playerObj.arrows < 1: print "No arrows!" else: print "Notching arrow!" elif action == SWITCH_WEAPON: playerObj.cycleWeapon() elif action == USE_POTION: playerObj.usePotion() elif action == PICKUP_OBJECT: playerObj.pickup = True if functions.playerInventory: playerObj.isTrading = True elif action == NO_PICKUP_OBJECT: playerObj.pickup = False playerObj.isTrading = False elif action == OPEN_MENU: self._log.debug('Opening menu') menuObject.activateText() elif action == PAUSE_GAME: if functions.paused: self._log.debug('Resuming game') functions.paused = False else: self._log.debug('Pausing game') functions.paused = True elif action == TAKE_SCREENSHOT: self._log.info('Taking screenshot') functions.screenshot() elif action == SET_FULLSCREEN: if Display.is_fullscreen: self._log.debug('Exiting fullscreen') Display.resetWindow() Display.is_fullscreen = 0 else: self._log.debug('Entering fullscreen') Display.fullscreen() Display.is_fullscreen = 1 elif action == RESTART_MATCH: self._log.info('Restarting match') playerObj.isDead = True elif action == QUIT_GAME: self._log.info('Quitting game') functions.terminate()
def game_cycle(screen, car_image): pygame.mixer.init() clock = pygame.time.Clock() # Инициализация "часов" для работы со временем # Загружаем файлы со звуком bns = pygame.mixer.Sound('data/sounds/bonus_pick.wav') crash = pygame.mixer.Sound('data/sounds/hit.wav') start = pygame.mixer.Sound('data/sounds/start1.wav') motor = pygame.mixer.Sound('data/sounds/motor.wav') motor.set_volume(0.2) health = 3 event1 = pygame.USEREVENT + 1 pygame.time.set_timer(event1, 5000) HP = load_image('heart.png') # Инициализируем группы спрайтов all_sprites = pygame.sprite.Group() car_group = pygame.sprite.Group() road_blocks = pygame.sprite.Group() weak_obst = pygame.sprite.Group() strong_obst = pygame.sprite.Group() bonuses = pygame.sprite.Group() car = Car((141, 310), car_image, car_group) # Создаём первых 2 блока дороги [RoadBlock(0, i, all_sprites, road_blocks) for i in range(-580, 1, 580)] record = read_record('data/record.txt') distance = 0 fps = 57 # 57 кадров в секунду для более стабильной отрисовки game_is_playing = True moving_left = False moving_right = False moving_up = False moving_down = False start.play(maxtime=1000) motor.play(loops=-1) while game_is_playing: # Этот цикл для последующей реализации game over экрана и начала новой игры screen.fill((0, 0, 0)) for i in range(health): screen.blit(HP, (310 + 30 * i, 20)) for event in pygame.event.get(): if event.type == pygame.QUIT: terminate(record=record) # Если мы нажали кнопку и не отпустили, # то продолжаем двигаться if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: moving_up = True if event.key == pygame.K_DOWN: moving_down = True if event.key == pygame.K_LEFT: moving_left = True if event.key == pygame.K_RIGHT: moving_right = True if event.key == pygame.K_ESCAPE: pause(screen, record) if event.type == pygame.KEYUP: if event.key == pygame.K_UP: moving_up = False if event.key == pygame.K_DOWN: moving_down = False if event.key == pygame.K_LEFT: moving_left = False if event.key == pygame.K_RIGHT: moving_right = False if event.type == event1: list(road_blocks)[0].change_speed(1) # Двигаем машинку (можно попробовать реализовать через функцию update в классе Car) if moving_up: car_group.update(0, -car.v / fps) if moving_down: car_group.update(0, car.v / fps) if moving_left: car_group.update(-car.v / fps, 0) if moving_right: car_group.update(car.v / fps, 0) if car.intersection(weak_obst) is not None: if RoadBlock.speed > 1: list(road_blocks)[0].change_speed(-2) crash.play() else: game_is_playing = False if car.intersection(strong_obst) is not None: if health > 1 and RoadBlock.speed > 1: health -= 1 list(road_blocks)[0].change_speed(-2) crash.play() else: game_is_playing = False picked_bonus = car.intersection(bonuses) if picked_bonus is not None: list(road_blocks)[0].change_speed(2) bns.play() # Проверяем выходит ли один из блоков за нижнюю границу экрана for block in road_blocks: if picked_bonus in block.objects: block.objects.remove(picked_bonus) if not block.is_viewing(): road_blocks.remove(block) RoadBlock(0, block.rect.y - 580 * 2, all_sprites, road_blocks).add_object(weak_obst, strong_obst, bonuses) distance += RoadBlock.speed / fps if distance > record: record = distance font = pygame.font.Font(None, 25) screen.blit( font.render(f"Скорость: {RoadBlock.speed * 5} км/ч", 1, (255, 255, 255)), (330, 70)) screen.blit( font.render(f"Пройденное расстояние: {int(distance)} м", 1, (255, 255, 255)), (330, 110)) screen.blit( font.render(f"Рекорд: {int(record)} м", 1, (255, 255, 255)), (330, 150)) # Обновляем все группы спрайтов # Рисуем поочерёдно, чтобы одни спрайты не накладывались на другие road_blocks.update() road_blocks.draw(screen) for block in road_blocks: block.objects.draw(screen) car_group.draw(screen) # Отсчитываем для стабильного fps clock.tick(fps) pygame.display.flip() motor.stop() RoadBlock.speed = 3 write_record('data/record.txt', record)
def main(): print("=== Welcome to National Bank ===") while True: try: acc = functions.Account() user_input = input("\nEnter your name: ") user_input = user_input.lower().strip() while True: if user_input in accounts.keys(): while True: select = functions.choice_1(user_input) if select == 1 or select == 2: if select == 1: while True: usr_choice = functions.choice_2() if usr_choice == 1 or usr_choice == 2 or usr_choice == 3: if usr_choice == 1: if user_input.lower().strip( ) not in accounts: accounts.update( {user_input: 0}) print( f'{user_input.upper()}\'s current balance is: Rp {accounts.get(user_input)}' ) user_input3 = int( input( "\nHow many do you want to deposit? Rp " )) accounts.update({ user_input: accounts.get(user_input) + user_input3 }) print( f'{user_input.upper()}\'s current balance is: Rp {accounts.get(user_input)}. Thank you for using our service.\n' ) if usr_choice == 2: if user_input.lower().strip( ) not in accounts: accounts.update( {user_input: 0}) while True: print( f'{user_input.upper()}\'s current balance is: Rp {accounts.get(user_input)}' ) user_input3 = int( input( "\nHow many do you want to withdraw? Rp " )) if user_input3 > accounts.get( user_input): print( "\nError! Your input exceeded the current balance: " + str( accounts.get( user_input))) else: accounts.update({ user_input: accounts.get( user_input) - user_input3 }) print( f'\n{user_input.upper()}\'s current balance is: Rp {accounts.get(user_input)}. Thank you for using our service.\n' ) break if usr_choice == 3: if user_input.lower().strip( ) not in accounts: accounts.update( {user_input: 0}) print( f'{user_input.upper()}\'s current balance is: Rp {accounts.get(user_input)}' ) while True: state = functions.terminate() if state == 1: break if state == 2: print( "\nThank you for using our service." ) append_accounts() elif state < 1 or state > 2: print( "\nInvalid input! Try again\n" ) else: print("\nInvalid input! Try again") if select == 2: while True: user_input = input("\nEnter your name: ") user_input = user_input.lower().strip() if user_input in accounts: break else: print( "\nSuccess! Account has been created." ) break else: print("\nInvalid input. Try again") else: print( f'\nSuccess! Account has been created.\n\n{user_input.upper()}\'s current balance is: Rp {acc.get_balance()}' ) user_input3 = int( input("How many do you want to deposit? Rp ")) acc.deposit(user_input3) print( f'\n{user_input.upper()}\'s current balance is: Rp {acc.get_balance()}\n' ) accounts.update({user_input: acc.get_balance()}) while True: state = functions.terminate() if state == 1: break elif state == 2: print( "\nThank you for using our service.\n === National Bank ===" ) a = '' for i in accounts.items(): a += i[0] + ',' + str(i[1]) + "\n" file2.write(a) exit() elif state < 1 or state > 2: print("\nInvalid input! Try again\n") except ValueError: print( "\nSomething unexpected happened. Program has been terminated to prevent data corruption.\n === National Bank ===" ) append_accounts()
def _perform_action(self, action, playerObj, menuObject): if action == MOVE_LEFT: playerObj.moveLeft = True playerObj.direction = 'left' elif action == MOVE_RIGHT: playerObj.moveRight = True playerObj.direction = 'right' elif action == MOVE_DOWN: playerObj.moveDown = True playerObj.direction = 'down' elif action == MOVE_UP: playerObj.moveUp = True playerObj.direction = 'up' elif action == NO_MOVE_LEFT: playerObj.moveLeft = False elif action == NO_MOVE_RIGHT: playerObj.moveRight = False elif action == NO_MOVE_DOWN: playerObj.moveDown = False playerObj.currentWeapon.spriteObj.resetSpriteList() elif action == NO_MOVE_UP: playerObj.moveUp = False elif action == NORMAL_ATTACK: playerObj.isAttacking = 1 elif action == NO_NORMAL_ATTACK: playerObj.isAttacking = 0 elif action == RANGED_ATTACK: if playerObj.arrows > 0: playerObj.arrows -= 1 print "Firing!" playerObj.rangedWeapon.shoot() else: print "No arrows!" elif action == CONTINIOUS_RANGED_ATTACK: if pygame.time.get_ticks() > playerObj.lastFired + 500 and playerObj.arrows > 0: playerObj.rangedWeapon.shoot() playerObj.lastFired = pygame.time.get_ticks() playerObj.arrows -= 1 else: if playerObj.arrows < 1: print "No arrows!" else: print "Notching arrow!" elif action == SWITCH_WEAPON: playerObj.cycleWeapon() elif action == USE_POTION: playerObj.usePotion() elif action == PICKUP_OBJECT: playerObj.pickup = True if functions.playerInventory: playerObj.isTrading = True elif action == NO_PICKUP_OBJECT: playerObj.pickup = False playerObj.isTrading = False elif action == OPEN_MENU: self._log.debug('Opening menu') menuObject.activateText() elif action == PAUSE_GAME: if functions.paused: self._log.debug('Resuming game') functions.paused = False else: self._log.debug('Pausing game') functions.paused = True elif action == TAKE_SCREENSHOT: self._log.info('Taking screenshot') functions.screenshot() elif action == SET_FULLSCREEN: if Display.is_fullscreen: self._log.debug('Exiting fullscreen') Display.resetWindow() Display.is_fullscreen = 0 else: self._log.debug('Entering fullscreen') Display.fullscreen() Display.is_fullscreen = 1 elif action == RESTART_MATCH: self._log.info('Restarting match') playerObj.isDead = True elif action == QUIT_GAME: self._log.info('Quitting game') functions.terminate()
def start_screen(): intro_text = ["DINO", "CHROM", 'US', "Пустыня", 'Лес', "Играть", "Выход"] screen.fill((255, 255, 255)) tick = load_image('tick.png') fon = pygame.transform.scale(load_image('fon.png'), (800, 600)) screen.blit(fon, (0, 0)) font = pygame.font.Font('data/font/PressStart2P.ttf', 50) text = font.render(intro_text[0], 1, (0, 255, 0)) text_x = 120 text_y = 50 screen.blit(text, (text_x, text_y)) text1 = font.render(intro_text[1], 1, (255, 0, 0)) text_x = 320 text_y = 50 screen.blit(text1, (text_x, text_y)) text2 = font.render(intro_text[2], 1, (255, 255, 0)) text_x = 570 text_y = 50 screen.blit(text2, (text_x, text_y)) high_score(screen) map1_button = start_buttons(250, 50, intro_text[3], 250, 360) map2_button = start_buttons(250, 50, intro_text[4], 250, 420) play_button = start_buttons(250, 50, intro_text[5], 250, 300) exit_button = start_buttons(250, 50, intro_text[6], 250, 480) start_group.draw(screen) pygame.display.flip() color = (255, 219, 88) name = "cactus" #реализация галочки на выбранной карте через tickno tickno = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() if event.type == pygame.MOUSEBUTTONDOWN: if exit_button.check_click(event.pos): terminate() if map1_button.check_click(event.pos): color = (255, 219, 88) name = 'cactus' if not tickno: screen.blit(tick, (180, 360)) tickno = False else: pygame.draw.rect(screen, (255, 255, 255), (180, 420, 64, 50)) screen.blit(tick, (180, 360)) if map2_button.check_click(event.pos): color = (0, 255, 0) name = 'tree' if not tickno: screen.blit(tick, (180, 420)) tickno = False else: pygame.draw.rect(screen, (255, 255, 255), (180, 360, 64, 50)) screen.blit(tick, (180, 420)) if play_button.check_click(event.pos): game(velocity, bvelocity, color, isJump, JumpCount, running, name) pygame.display.flip() clock.tick(fps)
def game(velocity, bvelocity, color, isJump, JumpCount, running, name): play_music('soundtrack.mp3') pygame.mixer.music.set_volume(0.5) board = Board(80, 60) dino = Dino(load_image("dinos2.png"), 2, 1, x_pos, y_pos) time = 0 score = int(time) screen.fill((255, 255, 255)) board.render(color) lst_cactus = [ ] #создаем списки наших спрайтов (на деле стоило использовать группы) lst_bird = [] scorelist = [] f = open("data/score.dat", "r") for line in f: highscore = round(float(line), 1) dead = False while running: birdchoose = random.randint(1, 2) plantchoose = random.randint( 1, 3) #рандомный выбор будущей птицы/растения screen.fill((255, 255, 255)) high_score(screen) scoreupdate(score, screen) for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() if event.type == pygame.KEYDOWN: if (event.key == pygame.K_SPACE and not isJump) or (event.key == pygame.K_UP and not isJump): isJump = True JumpCount = -10 if isJump: if JumpCount <= 10: dino.rect.y += int( JumpCount * 10 / 2**3 ) #физка прыжка, за основу взято земное ускорение и формула (вскоре переработанная) elif JumpCount >= -10: isJump = False JumpCount += 1 / 2 if time >= 10: if plantchoose == 1: lst_cactus.append(Plant(width, velocity, plantchoose, name)) elif plantchoose == 2: lst_cactus.append(Plant(width, velocity, plantchoose, name)) elif plantchoose == 3: lst_cactus.append(Plant(width, velocity, plantchoose, name)) if score >= 30: if birdchoose == 1: lst_bird.append(Bird(width, bvelocity, birdchoose)) if birdchoose == 2: lst_bird.append(Bird(width, bvelocity, birdchoose)) bvelocity += 45 velocity += 75 time = 0 if not isJump and not dead: dino.update() #начинается проверка спрайтов на столкновение, и очищение списка если столкновение произошло for cactus in lst_cactus: if pygame.sprite.collide_mask(dino, cactus): pygame.mixer.music.stop() i = 0 cactus.dead(lst_cactus) dino.dead() while lst_cactus != lst_bird and i < len(lst_bird): lst_bird[i].dead(lst_bird) i += 1 #определение рекордов и запись if curscore >= highscore: highscore = round(curscore, 1) f = open("data/score.dat", "w") f.write(str(highscore)) f.close() dead_screen(name) dead = True if not dead: cactus.update() for bird in lst_bird: if pygame.sprite.collide_mask(dino, bird): pygame.mixer.music.stop() dino.dead() bird.dead(lst_bird) n = 0 while lst_bird != lst_cactus and n < len(lst_cactus): lst_cactus[n].dead(lst_cactus) n += 1 if curscore >= highscore: highscore = round(curscore, 1) f = open("data/score.dat", "w") f.write(str(highscore)) f.close() dead_screen(name) dead = True if not dead: bird.update() if not dead: main_group.draw(screen) screen.blit(dino.image, (dino.rect.x, dino.rect.y)) board.render(color) pygame.display.update() scorelist.append(score) curscore = max(scorelist) time += 0.1 score += 0.1 clock.tick(45)
def play(screen, height): global current_level smooth_end = 0 finished = [] alpha_surf = pygame.Surface(screen.get_size(), pygame.SRCALPHA) alpha_surf.fill((255, 255, 255, 220), special_flags=pygame.BLEND_RGBA_MULT) camera = Camera(screen.get_size()[1]) running = True player1.isMoving = True player1.isMovingDown = True player2.isMoving = True player2.isMovingDown = True draw_sprites = pygame.sprite.Group() while running: playable = player1.isPlayable and player2.isPlayable draw_sprites.empty() time_delta = clock.tick(fps) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: terminate() else: eval(str(buttons.get(event.key))) alpha_surf.fill((255, 255, 255, 250), special_flags=pygame.BLEND_RGBA_MULT) new_alpha = pygame.Surface(screen.get_size(), pygame.SRCALPHA) screen.fill((0, 0, 0)) if not player1.move(time_delta, player_group, tile_group, all_sprites, alpha_surf, finish): finished.append(1) if not player2.move(time_delta, player_group, tile_group, all_sprites, alpha_surf, finish): finished.append(2) if playable and not finished: if player1.rect.y > screen.get_size()[1]: finish.rect.y = player2.rect.y - finish.rect.h finished.append(2) if player2.rect.y > screen.get_size()[1]: finish.rect.y = player1.rect.y - finish.rect.h finished.append(1) elif ((not player1.isPlayable and not player2.isPlayable) and (not finished and (player1.rect.y <= screen.get_size()[1] * 0.6 or player2.rect.y <= screen.get_size()[1] * 0.6))): player1.isPlayable = True player2.isPlayable = True alpha_surf.blit( pygame.transform.scale(load_image("start.png"), screen.get_size()), (0, 0)) player1.inverted += player2.other_inverted * 3 player2.inverted += player1.other_inverted * 3 player1.other_inverted, player2.other_inverted = 0, 0 y = camera.scroll_for( player1 if player1.rect.y < player2.rect.y else player2) new_alpha.blit(alpha_surf, (0, -y)) alpha_surf = new_alpha for sprite in all_sprites: camera.apply(sprite) camera.apply(finish) screen.blit(alpha_surf, (0, 0)) for sprite in tile_group: if 0 - 2 / 3 * tile_size < sprite.rect.y < height: # + tile_size: sprite.add(draw_sprites) draw_sprites.draw(screen) pygame.display.flip() if finished: if playable: result = "Player " + str(finished[0]) + " has won!" if len( finished) == 1 else "draw!" if result == "draw!": player1.isPlayable = False player2.isPlayable = False else: k = ("player" + str(int(result.split("Player ")[1][0]) % 2 + 1) + ".switch_off()") eval(k) smooth_end += time_delta if smooth_end > 1.22: time.sleep(0.3) running = False SCORE[1] += 1 in finished SCORE[2] += 2 in finished current_level += 1 return result