def menu_esc(): ''' function called after the user press ESC key and answer question ''' if globals.answer.upper()=='Y': if globals.stage==0: exit_program() elif globals.stage<=2: globals.stage=0 if globals.cli: if not globals.opponent_disconnect: sockets.query({"action":"bye","player_id":globals.player_id}) else: sockets.query({"action":"bbye"}) clean_question()
def exit_program(): ''' handle a clean exit of threads ''' globals.running = False if globals.cli: if not globals.opponent_disconnect: sockets.query({"action":"bye","player_id":globals.player_id}) else: sockets.query({"action":"bbye"}) if globals.server_thread: time.sleep(2) #wait for connect threads close itself #unblock server thread sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", int(globals.port))) sock.close() globals.server_thread.join(5) sys.exit(0)
def exit_program(): ''' handle a clean exit of threads ''' globals.running = False if globals.cli: if not globals.opponent_disconnect: sockets.query({"action": "bye", "player_id": globals.player_id}) else: sockets.query({"action": "bbye"}) if globals.server_thread: time.sleep(2) #wait for connect threads close itself #unblock server thread sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", int(globals.port))) sock.close() globals.server_thread.join(5) sys.exit(0)
def menu_esc(): ''' function called after the user press ESC key and answer question ''' if globals.answer.upper() == 'Y': if globals.stage == 0: exit_program() elif globals.stage <= 2: globals.stage = 0 if globals.cli: if not globals.opponent_disconnect: sockets.query({ "action": "bye", "player_id": globals.player_id }) else: sockets.query({"action": "bbye"}) clean_question()
elementbutton.DeathElementButton((155, 0), globals.actionpanel2) #Кнопки завершения хода первого и второго игрока. completethecoursebutton.CompleteTheCourseButton((760, 0), globals.actionpanel1) completethecoursebutton.CompleteTheCourseButton((760, 0), globals.actionpanel2) #Окна выбора карты стихии globals.cardsofelementshower1 = cardsofelementshower.CardsOfElementShower((0, 301), globals.player1) globals.cardsofelementshower2 = cardsofelementshower.CardsOfElementShower((0, 55), globals.player2) globals.gameinformationpanel = gameinformation.GameInformationPanel() globals.importantmessage = important_message.MessageWindow('We are waiting for another player') #globals.gameinformationpanel.display('Battle started.') #******************************************************************************** globals.screen.blit(globals.background, (0, 0)) globals.panels.update() globals.interface.update() pygame.display.flip() sockets.query({"action":"join","nickname":nickname[0:-1]}) #входим в игру def server_handler(): while True: gi = sockets.get_package() #si = sock.recv(256) #print 'si' #print si #print "RETURN:" #print get_package() if gi['action'] == 'join': print("Join to Game with Player_id "+str(gi['id'])) globals.player_id = gi['id'] elif gi['action'] == 'update': #Устанавливаем ники globals.player1.nickname = gi['nicknames'][0] globals.player2.nickname = gi['nicknames'][1]
def finish_turn(): me_finish_turn() sockets.query({"action":"switch_turn"})
def event(self, event): if event.type == QUIT: menu.exit_program() if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: if not globals.question: if not 'importantmessage' in globals.__dict__: menu.menu_esc_question() else: #handle ESC key when display importantmessage if globals.cli: if not globals.opponent_disconnect: sockets.query({ "action": "bye", "player_id": globals.player_id }) else: sockets.query({"action": "bbye"}) globals.information_group.remove( globals.importantmessage) del globals.importantmessage globals.stage = 0 globals.cli = False return else: menu.clean_question() return if globals.question and (event.key >= K_0 and event.key <= K_9 or event.key >= K_a and event.key <= K_z or event.key == K_PERIOD): globals.answer = globals.answer + pygame.key.name(event.key) if globals.question and (event.key == K_RETURN or len( globals.answer) >= globals.answer_maxchar): exec(globals.answer_cmd) menu.clean_question() return if globals.itemfocus: globals.itemfocus.change(event) if event.type == MOUSEBUTTONDOWN: if event.button == 1: globals.point.draw(event.pos) if globals.stage == 0: collided = pygame.sprite.spritecollide( globals.point, globals.menu_group, 0) elif globals.stage <= 2: collided = pygame.sprite.spritecollide( globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide( globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide( globals.point, globals.panels, 0) if not collided: return item = collided[len(collided) - 1] if item.type == "nicknamewindow": return if item.type == "healthwindow": return if item.type == 'outer': return if item.type == 'button' or item.type == 'txtinput' or item.type == 'checkbox': item.onmousedown() return if item.type == "warrior_card": #Карта в колоде! Карта на поле в cardbox #exec('selected_card_0 = cards.' + item.name + '()') #Переменной selected_card_0 присваиваем новый объект globals.selected_card = cards.links_to_cards[ item.name]() # из локальной в глобальную if globals.player.id == 1: for cardbox in globals.cardboxes[0:5]: if globals.player.action_points: if cardbox.card.name == "player": #если карты нет cardbox.light = True else: for cardbox in globals.cardboxes[5:10]: if cardbox.card.name == "player": cardbox.light = True return if item.type == "magic_card": #карта магии в колоде if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display( "You've already made a move.") return selected_card = cards.links_to_cards[item.name]() #exec('selected_card = cards.' + item.name + '()') #в переменную selected_card засовываем одну такую карту #exec('available_mana = globals.player.' + selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana available_mana = globals.player.mana[selected_card.element] if available_mana >= selected_card.level: #exec('globals.player.' + selected_card.element + '_mana -= ' + str(selected_card.level)) #Отнимаем ману globals.player.mana[ selected_card.element] -= selected_card.level globals.player.action_points = False #ставим запись, что ход сделан selected_card.player = globals.player sockets.query({ "action": "card", "card": selected_card.name, "type": "magic" }) selected_card.cast( ) #вызываем магию, периодизация делается уже внутри класса, путем добавления в группу globals.magic_cards selected_card.spell_speaker() #Закрываем колоду for cardbox in globals.cardboxes: cardbox.light = False else: globals.gameinformationpanel.display( 'Not enough mana.') return if globals.cast_focus: #выбор цели для каста if item.type == 'cardbox': globals.cast_focus_wizard.focus_cast_action(item.card) sockets.query({ "action": "cast", "position": globals.cast_focus_wizard.parent.position, "target": item.position, "focus": True }) if item.player.id != globals.player.id: return if globals.cli: if item.player.id != globals.player_id: return if item.type == "cardbox": #Если клик на карточный бокс if item.card.name != "player": #Если в этом блоке есть карта if item.card.cast: #если есть каст if not item.card.used_cast: # если еще не кастовали if not item.card.focus_cast: sockets.query({ "action": "cast", "position": item.position, "focus": False }) item.card.cast_action() else: globals.gameinformationpanel.display( "You've already cast.") return if globals.selected_card: #если выбрана карта if item.card.name != 'player': globals.gameinformationpanel.display( 'This sector is busy.') return if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display( "You've already made a move.") return #отключаем подсветку for cardbox in globals.cardboxes: cardbox.light = False #Выводим карту #exec('available_mana = globals.player.' + globals.selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana available_mana = globals.player.mana[ globals.selected_card.element] if available_mana < globals.selected_card.level: globals.gameinformationpanel.display( "Not enough mana.") return item.card = globals.selected_card item.card.parent = item sockets.query({ "action": "card", "card": item.card.name, "position": item.position, "type": "warrior" }) #item.card.cardboxes = cardboxes #item.card.playerscards = playerscards item.card.field = True item.card.summon( ) #функция которая хранит описание действий при выводе карты globals.player.action_points = False #exec('globals.player.' + globals.selected_card.element + '_mana -= ' + str(globals.selected_card.level)) #Отнимаем ману globals.player.mana[ globals.selected_card. element] -= globals.selected_card.level #globals.cards_in_deck.empty() #очищаем группу карты в колоде if item.player.id == 1: globals.ccards_1.add(item.card) else: globals.ccards_2.add(item.card) globals.selected_card = 0 elif event.button == 3: #ПРАВАЯ КНОПКА МЫШИ if globals.cast_focus: globals.cast_focus = False for card in globals.ccards_1.sprites( ) + globals.ccards_2.sprites(): card.light_switch(False) return globals.point.draw(event.pos) collided = pygame.sprite.spritecollide(globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide( globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide( globals.point, globals.panels, 0) if not collided: return item = collided[len(collided) - 1] if item.type == "warrior_card" or item.type == "magic_card": #по боевой карте globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.info globals.cardinfo.card = item globals.cardinfo.show = True if item.type == "cardbox": if item.card.name != "player": globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.card.info globals.cardinfo.card = item.card globals.cardinfo.show = True if item.type == 'cardsofelementshower': globals.interface.remove(globals.cardsofelementshower1) globals.interface.remove(globals.cardsofelementshower2) globals.cards_in_deck.empty() for cardbox in globals.cardboxes: cardbox.light = False elif event.type == MOUSEBUTTONUP: #отпускаем кнопку мыши if event.button == 3: #Правую if globals.cardinfo.show: globals.cardinfo.show = False globals.card_info_group.empty() else: #1 for elem in globals.interface: if elem.type == 'button': elem.onmouseup() elif event.type == MOUSEMOTION: globals.point.draw(event.pos) if globals.stage == 0: collided = pygame.sprite.spritecollide(globals.point, globals.menu_group, 0) elif globals.stage <= 2: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: if self.onmouse_element: self.onmouse_element.onmouseout() self.onmouse_element = False return item = collided[len(collided) - 1] if item.type == 'button': if self.onmouse_element != item: item.onmouseout() self.onmouse_element = item item.onmouse() #>>>>>>> other
def start_game(cli=False,ai=False): globals.attack_started = [True] globals.background = pygame.image.load(current_folder+'/misc/bg_sample.gif') #globals.background = globals.background.convert() #globals.background = pygame.Surface(globals.screen.get_size()) globals.background = globals.background.convert_alpha() globals.cards_of_element_shower_element = "water" #globals.background.fill((0, 0, 0)) background_backup = globals.background.copy() #font.set_bold(0) globals.games_cards[0]['water'] = cards.water_cards_deck[:] globals.games_cards[0]['fire'] = cards.fire_cards_deck[:] globals.games_cards[0]['air'] = cards.air_cards_deck[:] globals.games_cards[0]['earth'] = cards.earth_cards_deck[:] globals.games_cards[0]['life'] = cards.life_cards_deck[:] globals.games_cards[0]['death'] = cards.death_cards_deck[:] if globals.player1: globals.player1.enemy = None globals.player2.enemy = None globals.player1 = player.Player1() globals.player2 = player.Player2() globals.player1.enemy = globals.player2 globals.player2.enemy = globals.player1 globals.player = globals.player1 # 0 1 2 3 4 //Расположение # 5 6 7 8 9 globals.cardbox0 = cardbox.Cardbox((22, 46), globals.player1, 0) #0 место на поле globals.cardbox1 = cardbox.Cardbox((172, 46), globals.player1, 1) #1 место на поле globals.cardbox2 = cardbox.Cardbox((322, 46), globals.player1, 2) #2 место на поле globals.cardbox3 = cardbox.Cardbox((472, 46), globals.player1, 3) #3 место на поле globals.cardbox4 = cardbox.Cardbox((622, 46), globals.player1, 4) #4 место на поле globals.cardbox5 = cardbox.Cardbox((22, 238), globals.player2, 5) #5 место на поле globals.cardbox6 = cardbox.Cardbox((172, 238), globals.player2, 6) #6 место на поле globals.cardbox7 = cardbox.Cardbox((322, 238), globals.player2, 7) #7 место на поле globals.cardbox8 = cardbox.Cardbox((472, 238), globals.player2, 8) #8 место на поле globals.cardbox9 = cardbox.Cardbox((622, 238), globals.player2, 9) #9 место на поле globals.cardboxes = [globals.cardbox0, globals.cardbox1, globals.cardbox2, globals.cardbox3, globals.cardbox4, globals.cardbox5, globals.cardbox6, globals.cardbox7, globals.cardbox8, globals.cardbox9] #Ссылки на объекты for tcardbox in globals.cardboxes: if pygame.version.vernum < (1, 9, 1): tcardbox.normal_rect = copy.deepcopy(tcardbox.rect) tcardbox.opposite_rect = copy.deepcopy(tcardbox.get_opposite_cardbox().rect) else: tcardbox.normal_rect = tcardbox.rect.copy() tcardbox.opposite_rect = tcardbox.get_opposite_cardbox().rect.copy() globals.castlabel = cards.CastLabel() healthwindow.HealthWindowEnemy((175, 10)) #Окошко здоровья верхнего игрока healthwindow.HealthWindow((167, 557)) #Окошко здоровья нижнего игрока # Кнопки колод стихий первого игрока elementbutton.WaterElementShower((246, 2)) elementbutton.FireElementShower((337, 2)) elementbutton.AirElementShower((419, 2)) elementbutton.EarthElementShower((509, 2)) elementbutton.LifeElementShower((590, 2)) elementbutton.DeathElementShower((668, 2)) # Кнопки колод стихий второго игрока globals.water_element_button = elementbutton.WaterElementButton((11, 427)) globals.fire_element_button = elementbutton.FireElementButton((56, 427)) globals.air_element_button = elementbutton.AirElementButton((101, 427)) globals.earth_element_button = elementbutton.EarthElementButton((146, 427)) globals.life_element_button = elementbutton.LifeElementButton((191, 427)) globals.death_element_button = elementbutton.DeathElementButton((236, 427)) #Кнопки завершения хода первого и второго игрока. completethecoursebutton.CompleteTheCourseButton((758, 378)) #Окна выбора карты стихии globals.cardofelementsshower = cardsofelementshower.CardsOfElementShower() globals.nickname2 = nickname_window.NicknameWindow((142, 530), 'Guest') globals.nickname1 = nickname_window.NicknameWindow((22, 0), globals.nick) if ai: globals.player2.ai = True globals.nickname2.set_nickname('Computer') #стрелочки для сдвига карт в колоде #globals.leftarrow = cardsofelementshower.LeftArrow((356, 489)) #globals.rightarrow = cardsofelementshower.RightArrow((739, 491)) if not cli: globals.gameinformationpanel.display('Battle Started') globals.cli = False sockets.query = lambda x: x else: val = sockets.connect() if not val: globals.gameinformationpanel.display('Cant connect to server.') menu.menu_main() globals.stage = False return 0 else: globals.importantmessage = important_message.MessageWindow('We are waiting for another player') sockets.query = sockets.query_ globals.cli = True thread.start_new_thread(server_handler, ()) if not globals.cli: player.switch_position() #******************************************************************************** globals.screen.blit(globals.background, (0, 0)) globals.panels.update() globals.interface.update() pygame.display.flip() sockets.query({"action":"join", "nickname":globals.nick}) #входим в игру while globals.stage == 1: #if globals.turn_ended and len(cards_attacking) = 0: # for cardbox in globals.cardboxes: # cardbox.opposite = not cardbox.opposite for event in pygame.event.get(): globals.event_handler.event(event) globals.panels.update() globals.interface.update() globals.ccards_1.update() globals.ccards_2.update() globals.cardofelementsshower.update() globals.cards_in_deck.update() globals.card_info_group.update() globals.information_group.update() #interface_up_layer.update() globals.screen.blit(globals.background, (0, 0)) #globals.background.fill((0,0,0)) globals.background = background_backup.copy() if globals.animation == "N": for item in animations.animations_running + animations.cards_attacking + animations.cards_dying: del item animations.animations_running = [] animations.cards_attacking = [] animations.cards_dying = [] if len(animations.animations_running) == False and len(globals.attack_started): if not globals.cli: player.switch_position() for animation_running in animations.animations_running: animation_running.run() if len(globals.attack_started) and len(globals.cards_attacking) == False: if not globals.cli: player.switch_position() pygame.display.flip() clock.tick(50)
def start_game(cli=False, ai=False): wzglobals.attack_started = [True] wzglobals.background = \ pygame.image.load(current_folder+'/misc/bg_sample.gif') # wzglobals.background = wzglobals.background.convert() # wzglobals.background = pygame.Surface(wzglobals.screen.get_size()) wzglobals.background = wzglobals.background.convert_alpha() wzglobals.cards_of_element_shower_element = "water" # wzglobals.background.fill((0, 0, 0)) background_backup = wzglobals.background.copy() # font.set_bold(0) wzglobals.games_cards[0]['water'] = cards.water_cards_deck.cards[:] wzglobals.games_cards[0]['fire'] = cards.fire_cards_deck.cards[:] wzglobals.games_cards[0]['air'] = cards.air_cards_deck.cards[:] wzglobals.games_cards[0]['earth'] = cards.earth_cards_deck.cards[:] wzglobals.games_cards[0]['life'] = cards.life_cards_deck.cards[:] wzglobals.games_cards[0]['death'] = cards.death_cards_deck.cards[:] if wzglobals.player1: wzglobals.player1.enemy = None wzglobals.player2.enemy = None wzglobals.player1 = player.Player1() wzglobals.player1.nickname = wzglobals.nick wzglobals.player2 = player.Player2() wzglobals.player1.enemy = wzglobals.player2 wzglobals.player2.enemy = wzglobals.player1 wzglobals.player = wzglobals.player1 # 0 1 2 3 4 //Расположение # 5 6 7 8 9 wzglobals.cardbox0 = \ cardbox.Cardbox((22, 46), wzglobals.player1, 0) # 0 место на поле wzglobals.cardbox1 = \ cardbox.Cardbox((172, 46), wzglobals.player1, 1) # 1 место на поле wzglobals.cardbox2 = \ cardbox.Cardbox((322, 46), wzglobals.player1, 2) # 2 место на поле wzglobals.cardbox3 = \ cardbox.Cardbox((472, 46), wzglobals.player1, 3) # 3 место на поле wzglobals.cardbox4 = \ cardbox.Cardbox((622, 46), wzglobals.player1, 4) # 4 место на поле wzglobals.cardbox5 = \ cardbox.Cardbox((22, 238), wzglobals.player2, 5) # 5 место на поле wzglobals.cardbox6 = \ cardbox.Cardbox((172, 238), wzglobals.player2, 6) # 6 место на поле wzglobals.cardbox7 = \ cardbox.Cardbox((322, 238), wzglobals.player2, 7) # 7 место на поле wzglobals.cardbox8 = \ cardbox.Cardbox((472, 238), wzglobals.player2, 8) # 8 место на поле wzglobals.cardbox9 = \ cardbox.Cardbox((622, 238), wzglobals.player2, 9) # 9 место на поле wzglobals.cardboxes = [ wzglobals.cardbox0, wzglobals.cardbox1, wzglobals.cardbox2, wzglobals.cardbox3, wzglobals.cardbox4, wzglobals.cardbox5, wzglobals.cardbox6, wzglobals.cardbox7, wzglobals.cardbox8, wzglobals.cardbox9 ] # Ссылки на объекты for tcardbox in wzglobals.cardboxes: if pygame.version.vernum < (1, 9, 1): tcardbox.normal_rect = copy.deepcopy(tcardbox.rect) tcardbox.opposite_rect = \ copy.deepcopy(tcardbox.get_opposite_cardbox().rect) else: tcardbox.normal_rect = tcardbox.rect.copy() tcardbox.opposite_rect = \ tcardbox.get_opposite_cardbox().rect.copy() wzglobals.castlabel = cards.CastLabel() # Окошко здоровья верхнего игрока healthwindow.HealthWindowEnemy((175, 10)) healthwindow.HealthWindow((167, 557)) # Окошко здоровья нижнего игрока # Кнопки колод стихий первого игрока elementbutton.WaterElementShower((246, 2)) elementbutton.FireElementShower((337, 2)) elementbutton.AirElementShower((419, 2)) elementbutton.EarthElementShower((509, 2)) elementbutton.LifeElementShower((590, 2)) elementbutton.DeathElementShower((668, 2)) # Кнопки колод стихий второго игрока wzglobals.water_element_button = \ elementbutton.WaterElementButton((11, 427)) wzglobals.fire_element_button = \ elementbutton.FireElementButton((56, 427)) wzglobals.air_element_button = \ elementbutton.AirElementButton((101, 427)) wzglobals.earth_element_button = \ elementbutton.EarthElementButton((146, 427)) wzglobals.life_element_button = \ elementbutton.LifeElementButton((191, 427)) wzglobals.death_element_button = \ elementbutton.DeathElementButton((236, 427)) # Кнопки завершения хода первого и второго игрока. completethecoursebutton.CompleteTheCourseButton((758, 378)) # Окна выбора карты стихии wzglobals.cardofelementsshower = \ cardsofelementshower.CardsOfElementShower() wzglobals.nickname2 = \ nickname_window.NicknameWindow((142, 530), 'Guest') wzglobals.player2.nickname = 'Guest' wzglobals.nickname1 = \ nickname_window.NicknameWindow((22, 0), wzglobals.nick) if ai: wzglobals.player2.ai = True wzglobals.nickname2.set_nickname('Computer') wzglobals.player2.nickname = 'Computer' # стрелочки для сдвига карт в колоде # wzglobals.leftarrow = cardsofelementshower.LeftArrow((356, 489)) # wzglobals.rightarrow = cardsofelementshower.RightArrow((739, 491)) if not cli: wzglobals.gameinformationpanel.display('Battle Started') wzglobals.cli = False sockets.query = lambda x: x else: val = sockets.connect() if not val: wzglobals.gameinformationpanel.display('Cant connect to server.') menu.menu_main() wzglobals.stage = False return 0 else: wzglobals.importantmessage = important_message.MessageWindow( 'We are waiting for another player') sockets.query = sockets.query_ wzglobals.cli = True server_thread = threading.Thread(target=server_handler) server_thread.start() if not wzglobals.cli: player.switch_position() # ************************************************************************** wzglobals.screen.blit(wzglobals.background, (0, 0)) wzglobals.panels.update() wzglobals.interface.update() pygame.display.flip() sockets.query({ "action": "join", "nickname": wzglobals.nick }) # входим в игру while wzglobals.stage == 1: # if wzglobals.turn_ended and len(cards_attacking) = 0: # for cardbox in wzglobals.cardboxes: # cardbox.opposite = not cardbox.opposite for event in pygame.event.get(): wzglobals.event_handler.event(event) wzglobals.panels.update() wzglobals.interface.update() wzglobals.ccards_1.update() wzglobals.ccards_2.update() wzglobals.cardofelementsshower.update() wzglobals.cards_in_deck.update() wzglobals.card_info_group.update() wzglobals.information_group.update() # interface_up_layer.update() wzglobals.screen.blit(wzglobals.background, (0, 0)) # wzglobals.background.fill((0, 0, 0)) wzglobals.background = background_backup.copy() if wzglobals.animation == "N": for item in (animations.animations_running + animations.cards_attacking + animations.cards_dying): del item animations.animations_running = [] animations.cards_attacking = [] animations.cards_dying = [] if (not len(animations.animations_running) and len(wzglobals.attack_started)): if not wzglobals.cli: player.switch_position() for animation_running in animations.animations_running: animation_running.run() if not (len(wzglobals.attack_started) and len(wzglobals.cards_attacking)): if not wzglobals.cli: player.switch_position() pygame.display.flip() clock.tick(50)
def event(self, event): if event.type == QUIT: menu.exit_program() if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: if not globals.question: if not 'importantmessage' in globals.__dict__: menu.menu_esc_question() else: #handle ESC key when display importantmessage if globals.cli: if not globals.opponent_disconnect: sockets.query({"action":"bye","player_id":globals.player_id}) else: sockets.query({"action":"bbye"}) globals.information_group.remove(globals.importantmessage) del globals.importantmessage globals.stage = 0 globals.cli = False return else: menu.clean_question() return if globals.question and (event.key>=K_0 and event.key<=K_9 or event.key>=K_a and event.key<=K_z or event.key==K_PERIOD): globals.answer=globals.answer+pygame.key.name(event.key) if globals.question and (event.key==K_RETURN or len(globals.answer)>=globals.answer_maxchar): exec(globals.answer_cmd) menu.clean_question() return if globals.itemfocus: globals.itemfocus.change(event) if event.type == MOUSEBUTTONDOWN: if event.button == 1: globals.point.draw(event.pos) if globals.stage==0: collided = pygame.sprite.spritecollide(globals.point, globals.menu_group, 0) elif globals.stage<=2: collided = pygame.sprite.spritecollide(globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.panels, 0) if not collided: return item = collided[len(collided)-1] if item.type == "nicknamewindow": return if item.type == "healthwindow": return if item.type == 'outer': return if item.type == 'button' or item.type == 'txtinput' or item.type == 'checkbox': item.onmousedown() return if item.type == "warrior_card": #Карта в колоде! Карта на поле в cardbox #exec('selected_card_0 = cards.' + item.name + '()') #Переменной selected_card_0 присваиваем новый объект globals.selected_card = cards.links_to_cards[item.name]() # из локальной в глобальную if globals.player.id == 1: for cardbox in globals.cardboxes[0:5]: if globals.player.action_points: if cardbox.card.name == "player": #если карты нет cardbox.light = True else: for cardbox in globals.cardboxes[5:10]: if cardbox.card.name == "player": cardbox.light = True return if item.type == "magic_card": #карта магии в колоде if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display("You've already made a move.") return selected_card = cards.links_to_cards[item.name]() #exec('selected_card = cards.' + item.name + '()') #в переменную selected_card засовываем одну такую карту #exec('available_mana = globals.player.' + selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana available_mana = globals.player.mana[selected_card.element] if available_mana >= selected_card.level: #exec('globals.player.' + selected_card.element + '_mana -= ' + str(selected_card.level)) #Отнимаем ману globals.player.mana[selected_card.element] -= selected_card.level globals.player.action_points = False #ставим запись, что ход сделан selected_card.player = globals.player sockets.query({"action":"card","card":selected_card.name,"type":"magic"}) selected_card.cast() #вызываем магию, периодизация делается уже внутри класса, путем добавления в группу globals.magic_cards selected_card.spell_speaker() #Закрываем колоду for cardbox in globals.cardboxes: cardbox.light = False else: globals.gameinformationpanel.display('Not enough mana.') return if globals.cast_focus: #выбор цели для каста if item.type == 'cardbox': globals.cast_focus_wizard.focus_cast_action(item.card) sockets.query({"action":"cast","position":globals.cast_focus_wizard.parent.position,"target":item.position,"focus":True}) if item.player.id != globals.player.id: return if globals.cli: if item.player.id != globals.player_id: return if item.type == "cardbox": #Если клик на карточный бокс if item.card.name != "player": #Если в этом блоке есть карта if item.card.cast: #если есть каст if not item.card.used_cast: # если еще не кастовали if not item.card.focus_cast: sockets.query({"action":"cast","position":item.position,"focus":False}) item.card.cast_action() else: globals.gameinformationpanel.display("You've already cast.") return if globals.selected_card: #если выбрана карта if item.card.name != 'player': globals.gameinformationpanel.display('This sector is busy.') return if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display("You've already made a move.") return #отключаем подсветку for cardbox in globals.cardboxes: cardbox.light = False #Выводим карту #exec('available_mana = globals.player.' + globals.selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana available_mana = globals.player.mana[globals.selected_card.element] if available_mana < globals.selected_card.level: globals.gameinformationpanel.display("Not enough mana.") return item.card = globals.selected_card item.card.parent = item sockets.query({"action":"card","card":item.card.name,"position":item.position,"type":"warrior"}) #item.card.cardboxes = cardboxes #item.card.playerscards = playerscards item.card.field = True item.card.summon() #функция которая хранит описание действий при выводе карты globals.player.action_points = False #exec('globals.player.' + globals.selected_card.element + '_mana -= ' + str(globals.selected_card.level)) #Отнимаем ману globals.player.mana[globals.selected_card.element] -= globals.selected_card.level #globals.cards_in_deck.empty() #очищаем группу карты в колоде if item.player.id == 1: globals.ccards_1.add(item.card) else: globals.ccards_2.add(item.card) globals.selected_card = 0 elif event.button == 3: #ПРАВАЯ КНОПКА МЫШИ if globals.cast_focus: globals.cast_focus = False for card in globals.ccards_1.sprites()+globals.ccards_2.sprites(): card.light_switch(False) return globals.point.draw(event.pos) collided = pygame.sprite.spritecollide(globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.panels, 0) if not collided: return item = collided[len(collided)-1] if item.type == "warrior_card" or item.type == "magic_card" : #по боевой карте globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.info globals.cardinfo.card = item globals.cardinfo.show = True if item.type == "cardbox": if item.card.name != "player": globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.card.info globals.cardinfo.card = item.card globals.cardinfo.show = True if item.type == 'cardsofelementshower': globals.interface.remove(globals.cardsofelementshower1) globals.interface.remove(globals.cardsofelementshower2) globals.cards_in_deck.empty() for cardbox in globals.cardboxes: cardbox.light = False elif event.type == MOUSEBUTTONUP: #отпускаем кнопку мыши if event.button == 3: #Правую if globals.cardinfo.show: globals.cardinfo.show = False globals.card_info_group.empty() else: #1 for elem in globals.interface: if elem.type == 'button': elem.onmouseup() elif event.type == MOUSEMOTION: globals.point.draw(event.pos) if globals.stage==0: collided = pygame.sprite.spritecollide(globals.point, globals.menu_group, 0) elif globals.stage<=2: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: if self.onmouse_element: self.onmouse_element.onmouseout() self.onmouse_element = False return item = collided[len(collided)-1] if item.type == 'button': if self.onmouse_element != item: item.onmouseout() self.onmouse_element = item item.onmouse() #>>>>>>> other
def event(self, event): if event.type == QUIT: if not globals.opponent_disconnect: sockets.query({"action":"bye","player_id":globals.player_id}) else: sockets.query({"action":"bbye"}) sys.exit(0) if event.type == MOUSEBUTTONDOWN: if event.button == 1: globals.point.draw(event.pos) collided = pygame.sprite.spritecollide(globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.panels, 0) if not collided: return item = collided[len(collided)-1] if item.type == "warrior_card": #Карта в колоде! Карта на поле в cardbox exec('selected_card_0 = cards.' + item.name + '()') #Переменной selected_card_0 присваиваем новый объект globals.selected_card = selected_card_0 # из локальной в глобальную if globals.player.id == 1: for cardbox in globals.cardboxes[0:5]: if globals.player.action_points: if cardbox.card.name == "player": #если карты нет cardbox.light = True else: for cardbox in globals.cardboxes[5:10]: if cardbox.card.name == "player": cardbox.light = True return if item.type == "magic_card": #карта магии в колоде if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display("You've already made a move.") return exec('selected_card = cards.' + item.name + '()') #в переменную selected_card засовываем одну такую карту exec('available_mana = globals.player.' + selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana if available_mana >= selected_card.level: exec('globals.player.' + selected_card.element + '_mana -= ' + str(selected_card.level)) #Отнимаем ману globals.player.action_points = False #ставим запись, что ход сделан selected_card.player = globals.player sockets.query({"action":"card","card":selected_card.name,"type":"magic"}) selected_card.cast() #вызываем магию, периодизация делается уже внутри класса, путем добавления в группу globals.magic_cards #Закрываем колоду globals.interface.remove(globals.cardsofelementshower1) globals.interface.remove(globals.cardsofelementshower2) globals.cards_in_deck.empty() for cardbox in globals.cardboxes: cardbox.light = False else: globals.gameinformationpanel.display('Not enough mana.') return if globals.cast_focus: #выбор цели для каста if item.type == 'cardbox': globals.cast_focus_wizard.focus_cast_action(item.card) sockets.query({"action":"cast","position":globals.cast_focus_wizard.parent.position,"target":item.position,"focus":True}) if item.player.id != globals.player_id: return if item.player.id != globals.player.id: return if item.type == "cardbox": #Если клик на карточный бокс if item.card.name != "player": #Если в этом блоке есть карта if item.card.cast: #если есть каст if not item.card.used_cast: # если еще не кастовали if not item.card.focus_cast: sockets.query({"action":"cast","position":item.position,"focus":False}) item.card.cast_action() else: globals.gameinformationpanel.display("You've already cast.") return if globals.selected_card: #если выбрана карта if item.card.name != "player": globals.gameinformationpanel.display("This sector is busy.") return if not globals.player.action_points: #если уже ходил globals.gameinformationpanel.display("You've already made a move.") return #отключаем подсветку for cardbox in globals.cardboxes: cardbox.light = False #Выводим карту exec('available_mana = globals.player.' + globals.selected_card.element + '_mana') # Вычисляем сколько маны у нас есть. Значение помещаем в локальную переменную available_mana if available_mana < globals.selected_card.level: globals.gameinformationpanel.display("Not enough mana.") return item.card = globals.selected_card item.card.parent = item sockets.query({"action":"card","card":item.card.name,"position":item.position,"type":"warrior"}) #item.card.cardboxes = cardboxes #item.card.playerscards = playerscards item.card.field = True item.card.summon() #функция которая хранит описание действий при выводе карты globals.player.action_points = False exec('globals.player.' + globals.selected_card.element + '_mana -= ' + str(globals.selected_card.level)) #Отнимаем ману globals.interface.remove(globals.cardsofelementshower1) #Закрываем окна выбора карты globals.interface.remove(globals.cardsofelementshower2) #Закр. окна выбора карты globals.cards_in_deck.empty() #очищаем группу карты в колоде if item.player.id == 1: globals.ccards_1.add(item.card) else: globals.ccards_2.add(item.card) globals.selected_card = 0 if item.type == 'elementbutton': # global cards_of_element_shower_element globals.cards_in_deck.empty() if item.element == 'water': globals.cards_of_element_shower_element = "water" elif item.element == 'fire': globals.cards_of_element_shower_element = "fire" elif item.element == 'air': globals.cards_of_element_shower_element = "air" elif item.element == 'earth': globals.cards_of_element_shower_element = "earth" elif item.element == 'life': globals.cards_of_element_shower_element = "life" elif item.element == 'death': globals.cards_of_element_shower_element = "death" if globals.player.id == 1: globals.interface.add(globals.cardsofelementshower1) else: globals.interface.add(globals.cardsofelementshower2) play_bookopen_sound() elif item.type == 'completethecoursebutton': player.finish_turn() elif event.button == 3: #ПРАВАЯ КНОПКА МЫШИ if globals.cast_focus: globals.cast_focus = False for card in globals.ccards_1.sprites()+globals.ccards_2.sprites(): card.light_switch(False) return globals.point.draw(event.pos) collided = pygame.sprite.spritecollide(globals.point, globals.cards_in_deck, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.interface, 0) if not collided: collided = pygame.sprite.spritecollide(globals.point, globals.panels, 0) if not collided: return item = collided[len(collided)-1] if item.type == "warrior_card" or item.type == "magic_card" : #по боевой карте globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.info globals.cardinfo.card = item globals.cardinfo.show = True if item.type == "cardbox": if item.card.name != "player": globals.card_info_group.add(globals.cardinfo) #globals.cardinfo.text = item.card.info globals.cardinfo.card = item.card globals.cardinfo.show = True if item.type == 'cardsofelementshower': play_bookclose_sound() for cardbox in globals.cardboxes: cardbox.light = False elif event.type == MOUSEBUTTONUP: #отпускаем кнопку мыши if event.button == 3: #Правую if globals.cardinfo.show: globals.cardinfo.show = False globals.card_info_group.empty()
def start_game(cli=False): globals.background = pygame.image.load(current_folder+'/misc/bg_sample.gif') #globals.background = globals.background.convert() #globals.background = pygame.Surface(globals.screen.get_size()) globals.background = globals.background.convert_alpha() #globals.background.fill((0, 0, 0)) background_backup = globals.background.copy() #font.set_bold(0) cards.water_cards = list([c for c in cards.water_cards_deck]) cards.fire_cards = list([c for c in cards.fire_cards_deck]) cards.air_cards = list([c for c in cards.air_cards_deck]) cards.earth_cards = list([c for c in cards.earth_cards_deck]) cards.life_cards = list([c for c in cards.life_cards_deck]) cards.death_cards = list([c for c in cards.death_cards_deck]) globals.player1 = player.Player1() globals.player2 = player.Player2() globals.player1.enemy = globals.player2 globals.player2.enemy = globals.player1 globals.player = globals.player1 ############################################################################################################### #ACTIONS ############################################################################################################### #globals.infopanel1 = infopanel.Infopanel((0, 0), globals.player1) #Инициализация панели верхнего игрока #globals.infopanel2 = infopanel.Infopanel((0, 545), globals.player2) #Инициализация панели нижнего игрока #globals.actionpanel1 = actionpanel.Actionpanel((0, 25), globals.player1) #Панель с кнопками верхнего игрока #globals.actionpanel2 = actionpanel.Actionpanel((0, 570), globals.player2) #Панель с кнопками нижнего игрока # 0 1 2 3 4 //Расположение # 5 6 7 8 9 globals.cardbox0 = cardbox.Cardbox((32, 44), globals.player1, 0) #0 место на поле globals.cardbox1 = cardbox.Cardbox((187, 44), globals.player1, 1) #1 место на поле globals.cardbox2 = cardbox.Cardbox((341, 44), globals.player1, 2) #2 место на поле globals.cardbox3 = cardbox.Cardbox((497, 44), globals.player1, 3) #3 место на поле globals.cardbox4 = cardbox.Cardbox((651, 44), globals.player1, 4) #4 место на поле globals.cardbox5 = cardbox.Cardbox((32, 248), globals.player2, 5) #5 место на поле globals.cardbox6 = cardbox.Cardbox((187, 248), globals.player2, 6) #6 место на поле globals.cardbox7 = cardbox.Cardbox((341, 248), globals.player2, 7) #7 место на поле globals.cardbox8 = cardbox.Cardbox((497, 248), globals.player2, 8) #8 место на поле globals.cardbox9 = cardbox.Cardbox((651, 248), globals.player2, 9) #9 место на поле globals.cardboxes = [globals.cardbox0, globals.cardbox1, globals.cardbox2, globals.cardbox3, globals.cardbox4, globals.cardbox5, globals.cardbox6, globals.cardbox7, globals.cardbox8, globals.cardbox9] #Ссылки на объекты for tcardbox in globals.cardboxes: tcardbox.normal_rect = tcardbox.rect.copy() tcardbox.opposite_rect = tcardbox.get_opposite_cardbox().rect.copy() #playerscards = [globals.ccards_1, globals.ccards_2] #Ссылки #exec('Cardbox((640,301),2)') #ElementsWindow((0,0),actionpanel1) #ElementsWindow((0,0),actionpanel2) globals.castlabel = cards.CastLabel() healthwindow.HealthWindowEnemy((90, 10)) #Окошко здоровья верхнего игрока healthwindow.HealthWindow((90, 464)) #Окошко здоровья нижнего игрока # Кнопки колод стихий первого игрока elementbutton.WaterElementShower((385, 10)) elementbutton.FireElementShower((419, 10)) elementbutton.AirElementShower((450, 10)) elementbutton.EarthElementShower((480, 10)) elementbutton.LifeElementShower((514, 10)) elementbutton.DeathElementShower((546, 10)) # Кнопки колод стихий второго игрока globals.water_element_button = elementbutton.WaterElementButton((176, 429)) globals.fire_element_button = elementbutton.FireElementButton((207, 429)) globals.air_element_button = elementbutton.AirElementButton((238, 429)) globals.earth_element_button = elementbutton.EarthElementButton((269, 429)) globals.life_element_button = elementbutton.LifeElementButton((300, 429)) globals.death_element_button = elementbutton.DeathElementButton((331, 429)) #Кнопки завершения хода первого и второго игрока. completethecoursebutton.CompleteTheCourseButton((760, 430)) #Окна выбора карты стихии globals.cardofelementsshower = cardsofelementshower.CardsOfElementShower() #стрелочки для сдвига карт в колоде globals.leftarrow = cardsofelementshower.LeftArrow((356, 489)) globals.rightarrow = cardsofelementshower.RightArrow((739, 491)) if not cli: globals.gameinformationpanel.display('Battle Started') globals.cli = False sockets.query = lambda x: x else: globals.importantmessage = important_message.MessageWindow('We are waiting for another player') sockets.connect() sockets.query = sockets.query_ globals.cli = True thread.start_new_thread(server_handler, ()) if not globals.cli: player.switch_position() #******************************************************************************** globals.screen.blit(globals.background, (0, 0)) globals.panels.update() globals.interface.update() pygame.display.flip() sockets.query({"action":"join", "nickname":globals.nick}) #входим в игру while globals.stage == 1: #if globals.turn_ended and len(cards_attacking) = 0: # for cardbox in globals.cardboxes: # cardbox.opposite = not cardbox.opposite for event in pygame.event.get(): globals.event_handler.event(event) globals.panels.update() globals.interface.update() if globals.player.id == 1: globals.ccards_1.update() else: globals.ccards_2.update() globals.cardofelementsshower.update() globals.cards_in_deck.update() globals.card_info_group.update() globals.information_group.update() #interface_up_layer.update() globals.screen.blit(globals.background, (0, 0)) #globals.background.fill((0,0,0)) globals.background = background_backup.copy() if len(globals.animations_running) == False and globals.attack_started: if not globals.cli: player.switch_position() for animation_running in globals.animations_running: animation_running.run() if globals.attack_started and len(globals.cards_attacking) == False: if not globals.cli: player.switch_position() pygame.display.flip() clock.tick(50)
def finish_turn(): me_finish_turn() sockets.query({"action": "switch_turn"})