Пример #1
0
    def __init__(self, difficulty):
        self.difficulty = difficulty
        self.default_rate = 5
        self.default_hp = 100
        self.level = int(self.__class__.__name__[5:])

        self.boss = Boss(
            attack_speed=self.count_attack_speed(),
            recover_speed=self.count_recover_speed(),
            attack_power=self.count_attack_power(),
            heal_rate=self.count_recover_power(),
            hp=self.count_hp(),
        )

        self.player = Player(
            attack_power=2,
            heal_rate=1,
            hp=50,
        )
        self.spark_sprites = adapter.create_group()
        self.exclude_boss_sprites = adapter.create_group()
        self.exclude_boss_sprites.add(self.player)

        self.attack_keys = list('yhnujmikolp')
        self.recover_keys = list('qazwsxedcrfvtgb')
        self.attack_text_queue = []
        self.recover_text_queue = []
        self.right_title, self.left_title, self.right_text, self.left_text = self.count_hint_position()
Пример #2
0
    def remove_from_current_room(self, player: Player):
        rooms = self.rooms

        for room in rooms:
            if room is player.current_room:
                player.previous_room = player.current_room
                room.players.remove(player)
                break
        player.current_room = None
Пример #3
0
    def startPage(self):
        self.actions['changeScreen'] = self.changeScreen
        self.actions['dream'] = self.dream
        self.actions['communicate'] = self.communicate
        self.player = Player(xRatio=0.5, yRatio=2 / 3)

        self.loadScreen()  # init the screen
        self.drawScreen(
        )  # draw screen background, characters, mapObjects on canvas
        self.drawStartPageUI()
Пример #4
0
class App:
    def __init__(self):
        pyxel.init(160, 120, caption="herobo")
        pyxel.image(0).load(0, 0, "../assets/cat_16x16.png")
        self.x = 0
        self.player = Player()
        pyxel.run(self.update, self.draw)

    def update(self):
        self.player.act()

    def draw(self):
        pyxel.cls(0)
        self.player.character.render()
Пример #5
0
    def __init__(self):
        ## Foreground
        # A list of all on-screen elements.

        self.player = Player()
        self.welcome = Text("Welcome to Teamgame2!", 320, 100, 48, center=True)
        self.welcome2 = Text("Press [SPACE] to move", 320, 160, 24, center=True)
Пример #6
0
def begin_game(update, context):
    global a_board
    global a_player

    a_player = Player(12, "Guerrero")
    a_board = Board(a_player)

    update.message.reply_text(
        "I've created a new game! Please use /show to show the board.")
Пример #7
0
def main():
    p = Player()
    p.name = input("What is your character's name? ")
    print("(type help to get a list of actions) \n")
    print("{} enter a dark cave, searching for an adventure.".format(p.name))

    while (p.health > 0):
        line = input(">> ")
        args = line.split()
        if len(args) > 0:
            commandFound = False
            for c in Commands.keys():
                if args[0] == c[:len(args[0])]:
                    Commands[c](p)
                    commandFound = True
                    break
            if not commandFound:
                print("{} doesn't understand the suggestion.".format(p.name))
Пример #8
0
    def create_player(self, name, address=None):
        players = self.players
        for plr in players:
            if plr.name == name:
                return None

        room1 = self.rooms[0]

        name = str(name)
        id_player = len(players) + 1
        new_player = Player(id_player, name, address=address)
        new_player.inventory.append(Item('Map', command='map'))

        self.add_to_room(new_player, room1)
        players.append(new_player)
        return id_player
Пример #9
0
    def setup(self):
        #Create characters
        lumberjack = Npc("Bob", [self.item_handler.get_item("apple")],
                         "A friendly lumberjack")
        princess = Npc("Rapunzel", [],
                       "A beautiful princess with long blonde hair")
        caveman = Npc("Rocky", [], "A caveman with a big bushy beard")
        witch = Npc("Morgana", [
            self.item_handler.get_item("wand"),
            self.item_handler.get_item("toad")
        ], "A wicked witch dressed in black")
        bard = Npc("Lofty", [self.item_handler.get_item("lyre")],
                   "A whimsical bard playing a lyre")
        king = Npc("James", [self.item_handler.get_item("crown")],
                   "The benevolent king of the land")
        player = Player(self.player_name, [], 20)

        self.characters.append(player)
        self.characters.append(lumberjack)
        self.characters.append(princess)
        self.characters.append(caveman)
        self.characters.append(witch)
        self.characters.append(bard)
        self.characters.append(king)
Пример #10
0
 def add_to_room(self, player: Player, room: Room = None):
     if room is None:
         room = self.rooms[0]
     room.players.append(player)
     player.current_room = room
Пример #11
0
class LevelBase(LevelAbstract):
    def __init__(self, difficulty):
        self.difficulty = difficulty
        self.default_rate = 5
        self.default_hp = 100
        self.level = int(self.__class__.__name__[5:])

        self.boss = Boss(
            attack_speed=self.count_attack_speed(),
            recover_speed=self.count_recover_speed(),
            attack_power=self.count_attack_power(),
            heal_rate=self.count_recover_power(),
            hp=self.count_hp(),
        )

        self.player = Player(
            attack_power=2,
            heal_rate=1,
            hp=50,
        )
        self.spark_sprites = adapter.create_group()
        self.exclude_boss_sprites = adapter.create_group()
        self.exclude_boss_sprites.add(self.player)

        self.attack_keys = list('yhnujmikolp')
        self.recover_keys = list('qazwsxedcrfvtgb')
        self.attack_text_queue = []
        self.recover_text_queue = []
        self.right_title, self.left_title, self.right_text, self.left_text = self.count_hint_position()

    def count_hp(self):
        return self.default_hp + self.level * 0.5

    def count_attack_speed(self):
        return pow(self.difficulty, 1.5)

    def count_recover_speed(self):
        return pow(self.difficulty, 1.5)

    def count_attack_power(self):
        difficulty_power = self.default_rate * self.difficulty * 0.5
        level_addition = self.level * 0.5
        return self.default_rate + difficulty_power + level_addition

    def count_recover_power(self):
        difficulty_power = self.default_rate * self.difficulty * 0.5
        level_addition = self.level * 0.5
        return self.default_rate + difficulty_power + level_addition

    def boss_move(self, *args, **kwargs):
        pass

    def player_move(self, event, target, attack_key=k.K_RETURN):
        spark = self.player.attack(event, target, attack_key)
        if spark is not None:
            self.spark_sprites.add(spark)
            self.exclude_boss_sprites.add(spark)

    def count_hint_position(self):
        screen_w, screen_h = adapter.get_screen_x_y()

        title_width = 160
        title_height = title_width / 2
        padding = 15
        title_y = screen_h / 15 * 11 + padding

        right_x = screen_w - padding - title_width

        right_title = (right_x, title_y, title_width, title_height)
        left_title = (padding, title_y, title_width, title_height)

        y = screen_h / 15 * 13 + 5
        x = right_x + 35
        right_text = (x, y)

        x = padding + 35
        left_text = (x, y)
        return right_title, left_title, right_text, left_text

    def hint_title(self):
        attack = HintText(img.ATTACK_HINT, *self.right_title)
        self.exclude_boss_sprites.add(attack)

        recover = HintText(img.RECOVER_HINT, *self.left_title)
        self.exclude_boss_sprites.add(recover)

    def hint(self):
        self.hint_title()

    def get_random_key(self, key_list):
        return key_list[random.randint(0, len(key_list) - 1)]

    def init_queue(self, key_list: list):
        queue = []
        for _ in range(4):
            key = self.get_random_key(key_list)
            text = adapter.create_text(key.upper())
            queue.append((key, text))
        return queue

    def update_queue(self, queue: list, key_list: list):
        target_key = self.get_random_key(key_list)
        text = adapter.create_text(target_key.upper())
        queue.pop(0)
        queue.append((target_key, text))
        return target_key

    def reset(self):
        self.player.reset()
        self.boss.reset()

    def is_end(self):
        return self.player.is_dead() or self.boss.is_dead()

    def end_event(self):
        screen_size = adapter.get_screen_x_y()
        img_url = img.YOU_DIE

        if self.boss.is_dead():
            img_url = img.YOU_WIN
        end_background, _ = adapter.load_image(img_url)
        end_background = adapter.resize(end_background, screen_size)
        return end_background

    def update(self):
        self.player.update()
        self.boss.update()

    @staticmethod
    def match_time(t, speed):
        time_interval = 10 - speed
        if 10 >= time_interval or time_interval <= 0:
            return False
        return t % time_interval == 0
Пример #12
0
from characters.player import Player
from characters.monster import Monster
from data.rooms import rooms, outside, treasure
from data.items import pitchfork

pc = Player(rooms[outside])

rabble_rouser = '******'
monsters = {
    rabble_rouser: Monster(rabble_rouser, rooms[treasure], [pitchfork])
}
Пример #13
0
import pygame
pygame.init()

from characters.ghost import Ghost
from characters.player import Player

win = pygame.display.set_mode((800, 800))

pygame.display.set_caption("Game")

on = True

monster3 = Ghost(win, 500, 20, 15)
monster2 = Ghost(win, 300, 20, 15)
monster = Ghost(win, 400, 780, 15, 5, 1)
player = Player(win, 0, 0, 50, 50)

while on:
    pygame.time.delay(5)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            on = False

    #board background
    win.fill((0, 0, 0))

    pygame.draw.rect(win, (255, 255, 255), (0, 0, 200, 800))
    pygame.draw.rect(win, (255, 255, 255), (600, 0, 200, 800))

    player.update()
Пример #14
0
 def __init__(self):
     pyxel.init(160, 120, caption="herobo")
     pyxel.image(0).load(0, 0, "../assets/cat_16x16.png")
     self.x = 0
     self.player = Player()
     pyxel.run(self.update, self.draw)
Пример #15
0
    def run(self):
        # login and success get player information from DB
        if self.startPageUI.player:
            # initial player
            self.player = Player(self.startPageUI.player.name,
                                 self.startPageUI.player.xRatio,
                                 self.startPageUI.player.yRatio,
                                 self.startPageUI.player.level,
                                 self.startPageUI.player.id)
            # set current screen ID that player in
            self.currentScreenID = ScreenID.getScreenID(
                self.startPageUI.player.screenID)
            self.startPageUI.player = None

            self.loadScreen()
            self.drawScreen()
            self.canControl = True
            self.focus_set()

        if self.chatUI.codeResult != "" or self.chatUI.getLevel != 0:
            level = int(math.ceil(
                len(self.chatUI.codeResult) / 20)) + self.chatUI.getLevel
            levelUP(self.player, level, self.currentScreenID)
            for canvas in self.player.canvases:
                self.canvas.deleteWeight(canvas)
            self.player.canvases = []
            self.canvas.drawCharacter(self.player)
            self.chatUI.codeResult = ""
            self.chatUI.getLevel = 0

        displacement = self.player.getDisplacement()
        for canvas in self.player.canvases:
            self.canvas.move(canvas, displacement.dx, displacement.dy)

        for character in self.screen.characters:
            if character.role != 'boss':
                continue
            if self.getDistance(character.x, character.y) < 100:
                self.canvas.itemconfig(character.effect, state=tkinter.NORMAL)
            else:
                self.canvas.itemconfig(character.effect, state=tkinter.HIDDEN)

        if self.chatUI.help:
            playerLevel = int(self.player.level)
            message = ''
            if playerLevel >= 2:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Ace 詢問 "learn", "CI/CD" 相關問題')
            if playerLevel >= 3:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Angular 詢問 "Route53" 相關問題')
            if playerLevel >= 10:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Chrome 詢問 "TDD" 相關問題')
            if playerLevel >= 30:
                message += '%s :\t%s\n' % (
                    'System :',
                    '快去找 JaKC 詢問 "TokenExchange", "PoP的nonce為何payload要先hash", "好多RFC要讀喔", "我以為我懂,其實我不懂,而且我不懂我哪裡不懂" 相關問題'
                )
                message += '%s :\t%s\n' % (
                    'System :',
                    '快去找 YoSi 詢問 "LL大大說明為了code簡潔甚至有團隊限制function只能在幾行內解決" 相關問題')
                message += '%s :\t%s\n' % (
                    'System :', '快去找 Climu 詢問 "Python的Address這麼不認真" 相關問題')
            if playerLevel >= 2:
                self.chatUI.writeMessage(message)
            self.chatUI.help = False

        self.after(int(1000 / self.fps), self.run)
Пример #16
0
class Application(tkinter.Frame):
    def __init__(self, master):
        self.width = int(config['window']['width'])
        self.height = int(config['window']['height'])
        self.fps = int(config['frame']['fps'])
        self.currentScreenID = ScreenID.START
        self.beforeScreenID = None
        self.canControl = False
        self.chatUI = None
        self.actions = {}
        self.shot1Image = tkinter.PhotoImage(
            file='resources/shots/explosive.gif')
        self.shot2Image = tkinter.PhotoImage(file='resources/shots/fish.gif')
        self.shot1ID = None
        self.shot2ID = None
        self.help = False

        super().__init__(master=master, width=self.width, height=self.height)
        self.bind("<Key>", self.key)  # listen keyborad
        self.pack()
        # create a canvas to draw all item
        self.canvas = Canvas(self, self.width, self.height)
        self.startPage()
        self.focus_set()  # focus on this frame
        self.run()  # this function handler all game event logic
        self.mainloop()

    def startPage(self):
        self.actions['changeScreen'] = self.changeScreen
        self.actions['dream'] = self.dream
        self.actions['communicate'] = self.communicate
        self.player = Player(xRatio=0.5, yRatio=2 / 3)

        self.loadScreen()  # init the screen
        self.drawScreen(
        )  # draw screen background, characters, mapObjects on canvas
        self.drawStartPageUI()

    # load screen information by self.currentScreenID.
    # screen Start, MeetingRoom, WorkRoom1, WorkRoom2 have characters information
    # screen WorkRoom1, WorkRoom2 information include characters information
    # screen Start, MeetingRoom need inject characters information
    def loadScreen(self):
        # get current screen (only work_room_1 and work_room_2 can get characters)
        self.screen = getScreen(self.currentScreenID)

        # get characters information in screen start and screen meeting room
        if self.currentScreenID == ScreenID.START or self.currentScreenID == ScreenID.MEETING_ROOM:
            self.screen.characters = getCharacters(self.currentScreenID)

    def drawScreen(self):
        self.canvas.reset()
        self.canvas.setBackground(self.screen.background)
        self.canvas.drawText(TextInfo(10, 10, self.screen.name),
                             startFrom=tkinter.NW)

        for character in self.screen.characters:
            self.canvas.drawCharacter(character)
        for mapObject in self.screen.mapObjects:
            self.canvas.drawImage(
                ImageInfo(int(self.width * mapObject.xRatio),
                          int(self.height * mapObject.yRatio),
                          mapObject.image))
        self.canvas.drawCharacter(self.player)
        self.drawChatBlock()

    # game logic
    def run(self):
        # login and success get player information from DB
        if self.startPageUI.player:
            # initial player
            self.player = Player(self.startPageUI.player.name,
                                 self.startPageUI.player.xRatio,
                                 self.startPageUI.player.yRatio,
                                 self.startPageUI.player.level,
                                 self.startPageUI.player.id)
            # set current screen ID that player in
            self.currentScreenID = ScreenID.getScreenID(
                self.startPageUI.player.screenID)
            self.startPageUI.player = None

            self.loadScreen()
            self.drawScreen()
            self.canControl = True
            self.focus_set()

        if self.chatUI.codeResult != "" or self.chatUI.getLevel != 0:
            level = int(math.ceil(
                len(self.chatUI.codeResult) / 20)) + self.chatUI.getLevel
            levelUP(self.player, level, self.currentScreenID)
            for canvas in self.player.canvases:
                self.canvas.deleteWeight(canvas)
            self.player.canvases = []
            self.canvas.drawCharacter(self.player)
            self.chatUI.codeResult = ""
            self.chatUI.getLevel = 0

        displacement = self.player.getDisplacement()
        for canvas in self.player.canvases:
            self.canvas.move(canvas, displacement.dx, displacement.dy)

        for character in self.screen.characters:
            if character.role != 'boss':
                continue
            if self.getDistance(character.x, character.y) < 100:
                self.canvas.itemconfig(character.effect, state=tkinter.NORMAL)
            else:
                self.canvas.itemconfig(character.effect, state=tkinter.HIDDEN)

        if self.chatUI.help:
            playerLevel = int(self.player.level)
            message = ''
            if playerLevel >= 2:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Ace 詢問 "learn", "CI/CD" 相關問題')
            if playerLevel >= 3:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Angular 詢問 "Route53" 相關問題')
            if playerLevel >= 10:
                message += '%s :\t%s\n' % ('System :',
                                           '快去找 Chrome 詢問 "TDD" 相關問題')
            if playerLevel >= 30:
                message += '%s :\t%s\n' % (
                    'System :',
                    '快去找 JaKC 詢問 "TokenExchange", "PoP的nonce為何payload要先hash", "好多RFC要讀喔", "我以為我懂,其實我不懂,而且我不懂我哪裡不懂" 相關問題'
                )
                message += '%s :\t%s\n' % (
                    'System :',
                    '快去找 YoSi 詢問 "LL大大說明為了code簡潔甚至有團隊限制function只能在幾行內解決" 相關問題')
                message += '%s :\t%s\n' % (
                    'System :', '快去找 Climu 詢問 "Python的Address這麼不認真" 相關問題')
            if playerLevel >= 2:
                self.chatUI.writeMessage(message)
            self.chatUI.help = False

        self.after(int(1000 / self.fps), self.run)

    # keyboard handler (want to use some pattern to optimize)
    def key(self, event):
        # print("pressed", repr(event.char))
        if not self.canControl:
            return

        displacement = Displacement()
        key = event.char
        if key == 'w':
            displacement.dy = -moveSpeed
        elif key == 's':
            displacement.dy = moveSpeed
        elif key == 'a':
            displacement.dx = -moveSpeed
        elif key == 'd':
            displacement.dx = moveSpeed
        elif key == 'e':
            obj = self.getClosestObject()
            if obj:
                self.actions[obj.action](obj)
        elif key == 'm':
            self.meeting()
        elif key == '1':
            if not self.shot1ID:
                self.shot1ID = self.canvas.drawImage(
                    ImageInfo(int(0.5 * self.width), int(0.5 * self.height),
                              self.shot1Image))
        elif key == '2':
            if not self.shot2ID:
                self.shot2ID = self.canvas.drawImage(
                    ImageInfo(int(0.5 * self.width), int(0.5 * self.height),
                              self.shot2Image))
        elif key == '\r':
            self.chatUI.show()
        elif key == '\x1b':
            if self.shot1ID:
                self.canvas.deleteWeight(self.shot1ID)
                self.shot1ID = None
            if self.shot2ID:
                self.canvas.deleteWeight(self.shot2ID)
                self.shot2ID = None
        # elif key == 'b':
        #     self.player.transfer(self.canvas)

        # update player position
        self.player.move(displacement, self.width, self.height)

        # '\r'      entry
        # ' '       space
        # '\x1b'    esc
        # '\uf700'  up
        # '\uf701'  down
        # '\uf702'  left
        # '\uf703'  right

    def drawStartPageUI(self):
        self.startPageUI = StartPageUI()
        self.canvas.drawButton(self.startPageUI.button)
        self.canvas.drawInput(self.startPageUI.text)

    def drawChatBlock(self):
        if not self.chatUI:
            self.chatUI = ChatUI(self)
        self.canvas.drawInput(self.chatUI.output,
                              startFrom=tkinter.NW,
                              canModify=False)
        self.canvas.drawInput(self.chatUI.input, startFrom=tkinter.NW)
        self.canvas.drawButton(self.chatUI.sendButton)
        self.canvas.drawButton(self.chatUI.clearButton)
        self.canvas.drawButton(self.chatUI.exitButton)
        for radio in self.chatUI.radios:
            self.canvas.drawRadio(radio)
        self.chatUI.hide()
        self.help = True

    def getClosestObject(self):
        closestObject = None
        minDistance = 100
        for character in self.screen.characters:
            distance = self.getDistance(character.x, character.y)
            if distance < minDistance:
                minDistance = distance
                closestObject = character

        for mapObject in self.screen.mapObjects:
            distance = self.getDistance(mapObject.xRatio * self.width,
                                        mapObject.yRatio * self.height)
            if distance < minDistance:
                minDistance = distance
                closestObject = mapObject

        return closestObject

    def getDistance(self, x, y):
        width = self.player.x - x
        height = self.player.y - y

        return math.sqrt(width * width + height * height)

    def changeScreen(self, mapObject):
        targetScreenID = ScreenID.getScreenID(mapObject.targetScreenID)
        if targetScreenID:
            self.beforeScreenID = self.currentScreenID
            self.currentScreenID = targetScreenID
        else:
            if self.beforeScreenID:
                self.currentScreenID = self.beforeScreenID
            else:
                self.currentScreenID = ScreenID.MAP
        self.loadScreen()
        self.setPlayerPosition()
        self.drawScreen()

    def meeting(self):
        if self.currentScreenID == ScreenID.MEETING_ROOM:
            return

        self.beforeScreenID = self.currentScreenID
        self.currentScreenID = ScreenID.MEETING_ROOM
        self.loadScreen()
        self.setPlayerPosition()
        self.drawScreen()

    def setPlayerPosition(self):
        target = 'Door'
        if self.currentScreenID == ScreenID.MAP:
            if self.beforeScreenID == ScreenID.HOME:
                target = 'Home'
            elif self.beforeScreenID == ScreenID.WORK_ROOM_1:
                target = 'Work1'
            elif self.beforeScreenID == ScreenID.WORK_ROOM_2:
                target = 'Work2'
            elif int(self.player.level) >= 100:
                target = 'Work2'
            else:
                target = 'Work1'

        for mapObject in self.screen.mapObjects:
            if mapObject.name == target:
                xRatio, yRatio = mapObject.xRatio, mapObject.yRatio
                break

        self.player.x = xRatio * self.width
        self.player.y = yRatio * self.height

        if self.currentScreenID == ScreenID.MEETING_ROOM:
            return
        characterTransferScreen(self.player, self.currentScreenID)

    def dream(self, mapObject):
        self.chatUI.canExit = False
        self.chatUI.show()

    def communicate(self, character):
        if self.currentScreenID == ScreenID.MEETING_ROOM:
            if character.id == '5':
                message = '%s :\t%s\n' % (character.name, '#@%&*')
                self.chatUI.writeMessage(message)
            elif character.id == '1':
                message = '%s :\t%s\n' % (character.name, 'ABCD RFC')
                self.chatUI.writeMessage(message)
            elif character.id == '2':
                message = '%s :\t%s\n' % (character.name, '123 6749')
                self.chatUI.writeMessage(message)
            elif character.id == '4':
                message = '%s :\t%s\n' % (character.name, '...')
                self.chatUI.writeMessage(message)
            elif character.id == '7':
                message = '%s :\t%s\n' % (
                    character.name,
                    'PoP 才能保證 Auth Server 接收到的 request 是從合法的 Client 送來的,避免機敏性資料出現意外'
                )
                self.chatUI.writeMessage(message)
            return
        self.chatUI.show(character, int(self.player.level))
Пример #17
0
def main():
    global app, temps, time_start

    # chdir("C:/Users/cleme/Desktop/Documents/1. DOCUMENTS CLEMENT/TRAVAIL/Post BAC/projets personnels info/MINI JEUX/Pacman/pacman_game")
    fps = 30

    clock = pygame.time.Clock()  # pour fps
    init()
    app = display.set_mode((800, 550))
    display.set_caption('SPACE INVADERS')
    couleurs = [(0, 255, 0), (255, 255, 255),
                (255, 255, 0)]  # vert, blanc, jaune

    temps = 0
    delta_ms = clock.tick(fps)
    delta_s = delta_ms / 1000

    fonts = create_fonts()
    text = create_texts(fonts, couleurs)

    time_start = time.time()

    player = Player(445, 490)
    L_invaders = create_invaders()
    L_ennemy_projectiles = []
    L_friendly_projectiles = []

    player_vie1 = Player(60, 100)
    player_vie2 = Player(100, 100)
    player_vie3 = Player(140, 100)
    nbr_vies = 0

    temps_de_boucle = 0.0015
    turn = False
    cheat_mode = False
    game_over = False
    running = True
    n_boucle = 0
    L_game_over = []
    while running == True:
        n_boucle += 1
        temps = time.time() - time_start
        app.fill((0, 0, 0))
        map(app)

        ### Events : ###
        running, test_over, cheat_mode, nbr_vies, player, L_friendly_projectiles, L_invaders, L_game_over = get_events(
            app, running, game_over, cheat_mode, nbr_vies, player, L_invaders,
            L_friendly_projectiles, L_game_over)
        L_game_over.append(test_over)

        test_over = test_collision(app, player, L_invaders,
                                   L_ennemy_projectiles,
                                   L_friendly_projectiles, game_over)
        L_game_over.append(test_over)

        if 'perdu' not in L_game_over and 'gagne' not in L_game_over:
            ### game not finished ###
            if n_boucle % 1 == 0:
                player.player_move(app)
            """deplacer les invaders à une vitesse 6 fois moins élevée que player"""
            try:
                if n_boucle % L_invaders[0].speed == 0:
                    L_end_of_line = []
                    L_game_over = [
                    ]  #on réinitialise la liste des tests de fin de jeu
                    for i in L_invaders:
                        test_over, end_of_line = i.invader_move(app)
                        L_end_of_line.append(end_of_line)
                        L_game_over.append(test_over)

                    if True in L_end_of_line:  #Si un invader arrive au bout de la ligne, tous descendent d'un cran
                        for i in L_invaders:
                            i.y += 25
                            i.invader_change_direction()
            except:
                pass

            if n_boucle % 300 == 0:
                if cheat_mode == False:
                    attack_player(L_invaders, player, L_ennemy_projectiles,
                                  n_boucle)
            """deplacer les projectiles"""
            try:
                if n_boucle % L_friendly_projectiles[0].speed == 0:
                    for p in range(len(L_friendly_projectiles)):
                        try:
                            L_friendly_projectiles[p].projectile_move(
                                app, n_boucle)
                            if L_friendly_projectiles[p].y <= 90:
                                L_friendly_projectiles.pop(p)
                        except:
                            pass
            except:
                pass

            try:
                if n_boucle % L_ennemy_projectiles[0].speed == 0:
                    for q in range(len(L_ennemy_projectiles)):
                        try:
                            L_ennemy_projectiles[q].projectile_move(
                                app, n_boucle)
                            if L_ennemy_projectiles[q].y >= 500:
                                L_ennemy_projectiles.pop(q)
                        except:
                            pass
            except:
                pass
            """afficher les objets (player, invaders, projectiles)"""
            player.old_direction = player.direction
            app.blit(player.img, player.rect)

            for i in L_invaders:
                app.blit(i.img, i.rect)
                i.old_direction = i.direction
            for p in L_friendly_projectiles:
                app.blit(p.img, p.rect)
            for q in L_ennemy_projectiles:
                app.blit(q.img, q.rect)

        finish(app, game_over, nbr_vies, player, text['label_finish'],
               text['label_game_over'], text['label_enter_revive'],
               text['label_enter_restart'])

        if 'perdu' in L_game_over:
            game_over = 'perdu'
        elif 'gagne' in L_game_over:
            game_over = 'gagne'
        """afficher le nb de vies"""
        try:
            app.blit(text['label_lives'], (50, 50))
            app.blit(player_vie1.img,
                     player_vie1.rect)  # l'objet et son rectangle
            if nbr_vies >= 1:
                app.blit(player_vie2.img,
                         player_vie2.rect)  # l'objet et son rectangle
                if nbr_vies >= 2:
                    app.blit(player_vie3.img,
                             player_vie3.rect)  # l'objet et son rectangle
            display.update()
        except:
            pass

        if cheat_mode == True:
            for i in L_invaders:
                i.speed = 100

        time.sleep(temps_de_boucle)

    quit()
Пример #18
0
def main():
    print("GOOD LUCK HAVE FUN!")

    pygame.init()
    screen = pygame.display.set_mode(DISPLAY)
    pygame.display.set_caption("Rein")
    timer = pygame.time.Clock()

    brains = [Brain(identifier=1,n=2) for i in range(15)] + [Brain(identifier=2,n=2) for i in range(15)]

    while True:
        field = Environment(ENV_WIDTH_CELLS, ENV_HEIGHT_CELLS)

        pac_button = Button(ENV_WIDTH_CELLS, 0, info='PC')
        mode_button = Button(ENV_WIDTH_CELLS, 1, info='mode')
        mode_button_1 = Button(ENV_WIDTH_CELLS, 2, info='mod1')
        mode_button_2 = Button(ENV_WIDTH_CELLS, 3, info='mod2')
        go_button = Button(5, 4, img='img/game_over2.png')
        pacman = Player(field=field,
                        x=npr.randint(ENV_WIDTH_CELLS),
                        y=npr.randint(ENV_HEIGHT_CELLS),
                        health_points=1000,
                        brain=Brain(identifier=3, n=1),
                        img='img/pacman_1.png',
                        animation=['img/pacman_1.png', 'img/pacman_2.png'])

        group_one = [Player(field=field,
                            x=npr.randint(ENV_WIDTH_CELLS / 2),
                            y=npr.randint(ENV_HEIGHT_CELLS / 2),
                            health_points=HP,
                            brain=brains[i],
                            img='img/warrior_2.png') for i in range(15)]

        group_two = [Player(field=field,
                            x=npr.randint(ENV_WIDTH_CELLS / 2, ENV_WIDTH_CELLS),
                            y=npr.randint(ENV_HEIGHT_CELLS / 2, ENV_HEIGHT_CELLS),
                            health_points=HP,
                            brain=brains[i + 15],
                            img='img/warriorNew_1.png') for i in range(15)]

        while len(group_one) > 0 and len(group_two) > 0:
            pacman_list = ([pacman] if pac_button.pushed and pacman.flag != 'delete' else [])
            enteties = group_one + group_two + pacman_list
            timer.tick(7.5)
            for evt in pygame.event.get():
                event_handler(evt, pac_button)
                event_handler(evt, mode_button)
                event_handler(evt, mode_button_1)
                event_handler(evt, mode_button_2)

            pygame.display.update()

            if pac_button.pushed:
                pacman.update(pacman, enteties, mode=True)

            field.draw(screen)
            for g in enteties:
                if g.flag == 'delete':
                    continue
                if len(group_one) != 0 and len(group_two) != 0:
                    if g in group_one:
                        g.update(g, enteties, mode=not (mode_button.pushed or mode_button_1.pushed))
                    elif g in group_two:
                        g.update(g, enteties, mode=not (mode_button.pushed or mode_button_2.pushed))
                g.draw(screen)


            group_one = [i for i in group_one if i.flag != 'delete']
            group_two = [i for i in group_two if i.flag != 'delete']

            pac_button.draw(screen)
            mode_button.draw(screen)
            mode_button_1.draw(screen)
            mode_button_2.draw(screen)
            pygame.display.update()

        field.draw(screen)
        for g in enteties:
            g.draw(screen)

        wait = True
        while wait:
            timer.tick(7)
            go_button.draw(screen)
            for evt in pygame.event.get():
                event_handler(evt, go_button)

            if go_button.pushed:
                wait = False
            pygame.display.update()
    exit()