예제 #1
0
 def __init__(self):
     PygameEngine.__init__(self)
     self.index = 0
     self.gamefield = GameField(84, 48)
     self.snake = Snake()
     self.direction = Direction.RIGHT
     self.running = True
예제 #2
0
 def parse(self):
     self.set_game_input()
     columns = self.input_map.index("\n")
     self.parse_status(self.input_map[:columns])
     screen_rows = self.input_map[columns+1:].split('\n')
     rows = len(screen_rows)
     self.field = GameField(columns, rows)
     self.parse_field(screen_rows)
예제 #3
0
class SnakeGame(PygameEngine):

    def __init__(self):
        PygameEngine.__init__(self)
        self.index = 0
        self.gamefield = GameField(84, 48)
        self.snake = Snake()
        self.direction = Direction.RIGHT
        self.running = True

    def logic(self, key):
        if self.running is not True:
            self.gameOver(key)
        else:
            self.game(key)

    def game(self, key):
        self.calculateDirection(key)
        self.index += 1
        if ((self.index % 10) == 0):
            self.snake.grow()
        self.snake.move(self.direction)

        if self.collision():
            self.running = False
        else:
            self.gamefield.clear()
            self.snake.render(self.gamefield)
            self.render(self.gamefield.matrix)

    def collision(self):
        snakeHead = self.snake.getHead()
        if snakeHead[0] < 0:
            return True
        if snakeHead[0] >= self.gamefield.height:
            return True
        if snakeHead[1] < 0:
            return True
        if snakeHead[1] >= self.gamefield.width:
            return True
        return False



    def calculateDirection(self, key):
        if key == Key.LEFT:
            self.direction = Direction.LEFT
        if key == Key.RIGHT:
            self.direction = Direction.RIGHT
        if key == Key.UP:
            self.direction = Direction.UP
        if key == Key.DOWN:
            self.direction = Direction.DOWN

    def gameOver(self, key):
        self.render(self.gamefield.matrix)
예제 #4
0
파일: testaa_gui.py 프로젝트: syurskyi/QT
    def set_level(self, reset):
        #This method sets the level to self.gamefield that user has chosen if possible
        #It is called via keypress event when enter is pressed and user is selecting level (self.selecting_level == True)
        #reset is a bool. if true this method is called from reset_gui otherwise this is called after keypress enter

        try:
            path = os.getcwd()  #get the current working dir
            os.chdir(path)  #change dir to the current working dir
            os.chdir('game_levels')

            #open the file if possible
            if not reset:
                file = open(self.level_text, 'r')

            else:
                #method is called from reset_gui
                file = open(self.gamefield_level, 'r')

            #parse a gamefield and a copy from the file
            gamefield = GameField()

            return_value = gamefield.parse_gamefield(file)

            file.close()

            if return_value:
                #if return value is False, the level is broken
                self.set_gamefield(gamefield)

                if not reset:
                    #if method is called from reset_gui these shouldn't be executed
                    self.gamefield_level = self.level_text  #this is used by reset_gui method

                    #show user a message screen that level change was successfull
                    self.message_box.setIcon(QMessageBox.Information)
                    self.message_box.setText('Level successfully changed')

            else:
                #create a message box that informs the user
                self.message_box.setIcon(QMessageBox.Warning)
                self.message_box.setText(
                    'Level is not ok, using the previous level')

        except FileNotFoundError:
            self.message_box.setIcon(QMessageBox.Warning)
            self.message_box.setText('Level with name {} not found'.format(
                self.level_text))

        finally:
            os.chdir(
                path
            )  #This changes back to working directory where classes etc are defined
            if not reset:
                #show the message box to the user
                self.message_box.setWindowTitle('Level select')
                self.message_box.show()
예제 #5
0
 def new_game(self):
     self.running = True
     self.waiting = True
     self.gameover = False
     self.milestone = 100
     self.game_speed = 1
     self.lives = 4
     self.game_field = GameField(self.size)
     self.player = Player(
         [self.size[0] / 2 - Player.size[0] / 2, self.size[1] - 80],
         [255, 255, 255])
예제 #6
0
 def updateField(self):
     newField = GameField(self.field.width(), self.field.height())
     for wall in self.walls:
         newField.add(wall.coordinates, wall)
     for pill in self.pills:
         newField.add(pill.coordinates, pill)
     for ghost in self.ghosts:
         newField.add(ghost.coordinates, ghost)
     if self.pacman:
         newField.add(self.pacman.coordinates, self.pacman)
     if self.gameOver:
         Game.printGameOver(newField)
     self.field = newField
예제 #7
0
 def parse(self):
     if self.levelMaps:
         self.inputMap = self.levelMaps.getLevel(self.level)
     else:
         if "SEPARATOR" in self.inputMap:
             self.levelMaps = LevelMaps(self.inputMap)
             self.lastLevel = self.levelMaps.maxLevel()
             self.inputMap = self.levelMaps.getLevel(self.level)
     columns = self.inputMap.index("\n")
     self.parseStatus(self.inputMap[:columns])
     screenRows = self.inputMap[columns + 1:].split('\n')
     rows = len(screenRows)
     self.field = GameField(columns, rows)
     self.parseField(screenRows)
예제 #8
0
def start(message):
    """
    Handles the /start command.
    :param message: String received from the user.
    :return: None.
    """
    bot.send_sticker(message.chat.id, data='CAADAgADCBMAAkKvaQABJS_tlanrZB8C')
    bot.send_message(message.chat.id, constants.HELP_MESSAGE)
    users[message.chat.id] = GameField()
예제 #9
0
def new_game_check(message):
    """
    Handles the /new <height> <width> [<bombs>] command.
    Initializes a new game for the user.
    :param message: String received from the user.
    :return: None.
    """
    if message.chat.id not in users.keys():
        users[message.chat.id] = GameField()
    try:
        user_arguments = FieldParams(message.text)
    except exceptions.InputErrorException:
        bot.send_message(message.chat.id, 'Ошибка ввода')
        return
    except exceptions.TooManyBombsException:
        bot.send_message(message.chat.id, "Слишком много бомб")
        return
    except exceptions.TooLargeFieldException:
        bot.send_message(
            message.chat.id,
            "Слишком большое поле : размеры должны быть меньше 16")
        return
    except exceptions.IncorrectParamsException:
        bot.send_message(message.chat.id, "Некорректный размер поля")
        return
    except exceptions.NotEnoughBombsException:
        bot.send_message(message.chat.id, "Маловато бомб")
        return
    if user_arguments.bombs % 10 == 1 and user_arguments.bombs != 11:
        bot.send_message(message.chat.id,
                         'На поле {} бомба'.format(user_arguments.bombs))
    elif 2 <= user_arguments.bombs % 10 <= 4 and (user_arguments.bombs <= 10 or
                                                  user_arguments.bombs >= 20):
        bot.send_message(message.chat.id,
                         'Ha поле {} бомбы'.format(user_arguments.bombs))
    else:
        bot.send_message(message.chat.id,
                         'Ha поле {} бомб'.format(user_arguments.bombs))
    users[message.chat.id].init_game_field(user_arguments, message.chat.id)
    with open('/'.join([os.getcwd(), 'users/{}.jpg'.format(message.chat.id)]),
              'rb') as photo:
        bot.send_photo(message.chat.id, photo)
예제 #10
0
    def set_level(self):
        #This method sets the level to self.gamefield that user has chosen if possible
        #It is called via keypress event when enter is pressed and user is selecting level (self.selecting_level == True)

        try:
            path = os.getcwd()  #get the current working dir
            os.chdir(path)  #change dir to the current working dir
            os.chdir('game_levels')

            #open the file if possible

            file = open(self.level_text, 'r')

            #parse a gamefield and a copy from the file
            gamefield = GameField()
            game_copy = GameField()
            return_value = gamefield.parse_gamefield(file)
            file.seek(0)  #This is very important otherwise program will die
            game_copy.parse_gamefield(file)

            file.close()

            if return_value:
                #if return value is False, the level is broken
                self.set_gamefield(gamefield, game_copy)
                self.gamefield_level = self.level_text  #this is used by reset_gui method
                print('Level successfully changed')

            else:
                print('Level is not ok, using the previous level')

        except FileNotFoundError:
            print('Level with name {} not found'.format(self.level_text))

        finally:
            os.chdir(
                path
            )  #This changes back to working directory where classes etc are defined
예제 #11
0
class Game(object):
    def __init__(self, inputMap=None):
        if inputMap is not None:
            self.inputMap = inputMap.rstrip()
        self.field = None
        self.lives = 3
        self.score = 0
        self.pacman = None
        self.ghosts = []
        self.pills = []
        self.walls = []
        self.gameOver = False
        self.controller = None
        self.gate = None
        self.level = 1
        self.lastLevel = 1
        self.levelMaps = None
        self.animation = False

    def play(self, debug):
        self.parse()
        while (self.gameOver is False):
            self.tick()
            self.render()
            self.refresh()
            sleep(0.1)
            if (self.pacman.alive is False):
                self.pacman.restart()
            if (debug is True):
                self.gameOver = True

    def parse(self):
        if self.levelMaps:
            self.inputMap = self.levelMaps.getLevel(self.level)
        else:
            if "SEPARATOR" in self.inputMap:
                self.levelMaps = LevelMaps(self.inputMap)
                self.lastLevel = self.levelMaps.maxLevel()
                self.inputMap = self.levelMaps.getLevel(self.level)
        columns = self.inputMap.index("\n")
        self.parseStatus(self.inputMap[:columns])
        screenRows = self.inputMap[columns + 1:].split('\n')
        rows = len(screenRows)
        self.field = GameField(columns, rows)
        self.parseField(screenRows)

    def parseStatus(self, statusLine):
        elements = statusLine.split()
        try:
            self.lives = int(elements[0])
            self.score = int(elements[1])
        except ValueError:
            pass

    def parseField(self, screenRows):
        for y in range(self.field.height()):
            for x in range(self.field.width()):
                if Pacman.isPacman(screenRows[y][x]):
                    self.pacman = Pacman(self, (x, y), screenRows[y][x])
                    self.pacman.useAnimation(self.animation)
                    self.field.add((x, y), self.pacman)
                if Wall.isWall(screenRows[y][x]):
                    wall = Wall((x, y), screenRows[y][x])
                    self.walls.append(wall)
                    self.field.add((x, y), wall)
                    if Wall.isGate(screenRows[y][x]):
                        self.gate = wall
                if Pill.isPill(screenRows[y][x]):
                    pill = Pill((x, y), screenRows[y][x])
                    self.pills.append(pill)
                    self.field.add((x, y), pill)
                if Ghost.isGhost(screenRows[y][x]):
                    ghost = Ghost(self, (x, y), screenRows[y][x])
                    self.ghosts.append(ghost)
                    self.field.add((x, y), ghost)

    def setGameField(self, width, height):
        self.field = GameField(width, height)

    def setPacman(self, coordinates, direction):
        self.pacman = Pacman(self, coordinates)
        self.pacman.setDirection(direction)
        self.field.add(coordinates, self.pacman)

    def addWall(self, coordinates, icon):
        wall = Wall(coordinates, icon)
        self.walls.append(wall)
        self.field.add(coordinates, wall)

    def tick(self):
        if not self.gameOver:
            for ghost in self.ghosts:
                ghost.tick()
            if self.pacman:
                self.pacman.tick()
        self.updateField()

    def render(self):
        self.output = "{lives:1d}".format(lives=self.lives)
        self.output += "{score:>{width}d}\n".format(score=self.score,
                                                    width=self.field.width() -
                                                    len(self.output))
        self.output += self.field.render()

    def refresh(self):
        print("\u001B[H" + "\u001B[2J" + "\u001B[1m")
        print(self.output)

    def updateField(self):
        newField = GameField(self.field.width(), self.field.height())
        for wall in self.walls:
            newField.add(wall.coordinates, wall)
        for pill in self.pills:
            newField.add(pill.coordinates, pill)
        for ghost in self.ghosts:
            newField.add(ghost.coordinates, ghost)
        if self.pacman:
            newField.add(self.pacman.coordinates, self.pacman)
        if self.gameOver:
            Game.printGameOver(newField)
        self.field = newField

    def getElement(self, coords):
        return self.field.get(coords)

    def isGhost(self, coordinates):
        return Ghost.isGhost(self.field.get(coordinates))

    def isWall(self, coordinates):
        return Wall.isWall(self.field.get(coordinates))

    def isGate(self, coordinates):
        return Wall.isGate(self.field.get(coordinates))

    def isField(self, coordinates):
        return Wall.isField(self.field.get(coordinates))

    def isPill(self, coordinates):
        return Pill.isPill(self.field.get(coordinates))

    def isPacman(self, coordinates):
        return isinstance(self.field.get(coordinates), Pacman)

    def eatPill(self, coordinates):
        pill = self.field.get(coordinates)
        self.pills.remove(pill)
        self.score += pill.score()
        for ghost in self.ghosts:
            ghost.triggerEffect(pill)
        if len(self.pills) == 0:
            self.nextLevel()

    def killGhost(self, ghost):
        self.score += ghost.score()
        ghost.kill()

    def killPacman(self):
        self.pacman.kill()
        self.lives -= 1
        if (self.lives == 0):
            self.gameOver = True

    def getPacman(self):
        return self.pacman

    def setController(self, controller):
        self.controller = controller

    def move(self, direction):
        self.pacman.move(direction)

    def setLevel(self, level):
        self.level = level

    def setMaxLevel(self, level):
        self.lastLevel = level

    def nextLevel(self):
        if self.level < self.lastLevel:
            self.level += 1
            self.pills = []
            self.walls = []
            self.ghosts = []
            self.parse()
        else:
            self.gameOver = True
            self.pacman.restart()

    def useAnimation(self):
        self.animation = True

    def getLives(self):
        return self.lives

    def getScore(self):
        return self.score

    def printGameOver(field):
        cols = field.width()
        rows = field.height()
        GAME = "GAME"
        OVER = "OVER"
        y = floor(rows / 2) - 2
        padding = floor(((cols - 2) - len(GAME)) / 2)
        for i in range(len(GAME)):
            x = padding + i + 1
            field.add((x, y), GAME[i])
            field.add((x, y + 1), OVER[i])
예제 #12
0
파일: testaa_gui.py 프로젝트: syurskyi/QT
            print('NOTICE: There is something wrong in the config file')
            print('The game is partially using standard set values')

        path = os.getcwd()  #get the current working dir

        os.chdir('game_levels')
        #file = open('erikoisempi_kentta.txt','r')
        #file = open('vihollis_testi_kentta.txt','r')
        file = open('game_testi.txt', 'r')
        #file = open('leijuva_testi_kentta.txt','r')
        #file = open ('erilainen_kentta.txt','r')
        #file = open('melko_tyhja_kentta.txt','r')

        os.chdir(path)  #change dir to the current working dir

        gamefield = GameField()
        gamefield.parse_gamefield(file)
        file.close()

        main = Gui(gamefield)

        #print(Gui.Level_number)
        #print(Config.level_number)

        #main.set_gamefield(gamefield)
        main.gamefield_level = 'game_testi.txt'

        main.show()

        sys.exit(app.exec_())
예제 #13
0
class Race:
    def __init__(self, traceFile=None, visualize=False):
        self.visualize = visualize

        self.traceFileName = traceFile + '.dat'

        if self.loadTrace():
            self.setRandomInitialState()

        self._reward = 0

    def loadTrace(self):
        if path.exists(self.traceFileName):
            self.schema = np.loadtxt(self.traceFileName, dtype=np.int)
            self._height, self._width = self.schema.shape
            return True
        else:
            self._height, self._width = 50, 20
            self.schema = np.zeros((self._height, self._width), dtype=np.int)
            return False

    def setRandomInitialState(self):
        self._initial_position_y = self._position_y = self.height - 1
        available_positions = np.where(self.schema[self._position_y] == 1)[0]
        self._initial_position_x = self._position_x = np.random.choice(
            available_positions, 1)[0]
        self._speed_x = self._speed_y = 0

    @property
    def height(self):
        return self._height

    @property
    def width(self):
        return self._width

    @property
    def gamefield(self):
        if not hasattr(self, '_gamefield'):
            self._gamefield = GameField(self.height, self.width,
                                        self.editorMode)
            self._gamefield.init()
        return self._gamefield

    @property
    def is_final_step(self):
        return self.schema[self._position_y, self._position_x] == 2

    @property
    def reward(self):
        return self._reward

    @property
    def state(self):
        return (self._position_x, self._position_y, self._speed_x,
                self._speed_y)

    def makeAction(self):
        if self.is_final_step:
            if self.visualize: self.gamefield.quit()
            return 0

        delta_y, delta_x = self.solutioner.getNextAction(
            self.height - self._position_y - 1, self._position_x,
            self._speed_y, self._speed_x)

        self._speed_x = min(5, max(-5, self._speed_x + delta_x))
        self._speed_y = min(5, max(-5, self._speed_y + delta_y))

        new_pos_x = self._position_x + self._speed_x
        new_pos_y = self._position_y - self._speed_y  # start point is at the bottom left corner

        if (new_pos_x < 0) or (new_pos_x >= self.width) or (new_pos_y < 0) or (
                new_pos_y >= self.height) or (self.schema[new_pos_y, new_pos_x]
                                              == 0):
            self.setRandomInitialState()
            self._reward += -100
        else:
            self._position_x = new_pos_x
            self._position_y = new_pos_y
            self._reward += -1

        if self.visualize: self.displayCurrentGameState()

        return -1

    def displayCurrentGameState(self):
        self.gamefield.setScheme(self.schema, redraw=False)
        if not self.editorMode:
            self.gamefield.setPlayerPosition(self._position_x,
                                             self._position_y,
                                             redraw=False)
            self.gamefield.setPlayerSpeed(self._speed_x,
                                          self._speed_y,
                                          redraw=False)
            self.gamefield.setInformation(self._reward, redraw=False)
        self.gamefield.redraw()

    def runEditorMode(self):
        self.editorMode = True
        self.gamefield.subscribeEvent('exit', self.saveAndExit)
        self.gamefield.subscribeEvent('selection', self.updateSelectedArea)
        self.displayCurrentGameState()
        self.gamefield.run()

    def run(self, solutioner):
        self.editorMode = False
        self.solutioner = solutioner
        if self.solutioner: self.solutioner.bootstrap()

        if self.visualize:
            self.displayCurrentGameState()
            self.gamefield.subscribeEvent('exit', self.printFinalScoreAndExit)
            self.gamefield.subscribeEvent('space', self.makeAction)
            self.gamefield.run()
        else:
            while not self.is_final_step:
                self.makeAction()

        print('Final reward is %d' % self._reward)

    def updateSelectedArea(self, r_rows, r_cols, delta):
        self.schema[r_rows[0]:(r_rows[1] + 1),
                    r_cols[0]:(r_cols[1] + 1)] += delta
        self.schema = np.mod(self.schema, 3)
        self.gamefield.setScheme(self.schema)

    def saveAndExit(self):
        np.savetxt(self.traceFileName, self.schema, '%d')
        self.gamefield.quit()
        sys.exit()

    def printFinalScoreAndExit(self):
        print('Final reward is %d' % self._reward)
        self.gamefield.quit()
예제 #14
0
 def gamefield(self):
     if not hasattr(self, '_gamefield'):
         self._gamefield = GameField(self.height, self.width,
                                     self.editorMode)
         self._gamefield.init()
     return self._gamefield
예제 #15
0
 def setGameField(self, width, height):
     self.field = GameField(width, height)
예제 #16
0
class Game(object):
    def __init__(self, input_map=None):
        if input_map is not None:
            self.input_map = input_map.rstrip()
        self.field = None
        self.lives = 3
        self.score = 0
        self.pacman = None
        self.ghosts = []
        self.pills = []
        self.walls = []
        self.game_over = False
        self.controller = None
        self.display = None
        self.gate = None
        self.level = 1
        self.last_level = 1
        self.level_maps = None
        self.animation = False
        self.using_pills = False
        self.player = None
        self.scoreboard = None

    def init(self):
        self.parse()
        self.display.init(self)

    def play(self, debug):
        while True:
            self.tick()
            self.render()
            self.refresh()
            sleep(FRAME_RATE_IN_SECS)
            if (not self.pacman.alive):
                self.display.flash()
                self.pacman.restart()
            if self.game_over or debug:
                break
        self.post_score()

    def parse(self):
        self.set_game_input()
        columns = self.input_map.index("\n")
        self.parse_status(self.input_map[:columns])
        screen_rows = self.input_map[columns+1:].split('\n')
        rows = len(screen_rows)
        self.field = GameField(columns, rows)
        self.parse_field(screen_rows)

    def set_game_input(self):
        if self.level_maps:
            self.input_map = self.level_maps.get_level(self.level)
        else:
            if "SEPARATOR" in self.input_map:
                self.level_maps = LevelMaps(self.input_map)
                self.last_level = self.level_maps.max_level()
                self.input_map = self.level_maps.get_level(self.level)

    def parse_status(self, status_line):
        elements = status_line.split()
        try:
            self.lives = int(elements[0])
            self.score = int(elements[1])
        except ValueError:
            pass

    def parse_field(self, screen_rows):
        for y in range(self.field.height()):
            for x in range(self.field.width()):
                element = tokenizer.get_element((x, y), screen_rows[y][x])
                if (element):
                    element.add_to_game(self)

    def add_pill(self, pill):
        self.using_pills = True
        self.pills.append(pill)
        self.field.add(pill.coordinates, pill)

    def add_ghost(self, ghost):
        self.ghosts.append(ghost)
        self.field.add(ghost.coordinates, ghost)

    def set_field(self, width, height):
        self.field = GameField(width, height)

    def set_pacman(self, coordinates, direction):
        pacman = Pacman(coordinates)
        pacman.set_direction(direction)
        pacman.add_to_game(self)

    def add_pacman(self, pacman):
        self.pacman = pacman
        self.field.add(pacman.coordinates, pacman)

    def add_wall(self, coordinates, icon):
        wall = Wall(coordinates, icon)
        self.walls.append(wall)
        self.field.add(coordinates, wall)
        if Wall.is_gate(wall):
            self.gate = wall

    def tick(self):
        for ghost in self.ghosts:
            ghost.tick()
        if self.pacman:
            self.pacman.tick()
        if self.is_level_clear():
            self.next_level()
        self.update_field()

    def render(self):
        composite = Game.render_status(self.lives,
                                       self.score,
                                       self.field.width())
        self.output = composite["video"]
        self.colour = composite["colour"]
        self.output += "\n"
        self.colour.append(0)
        composite = self.field.render()
        self.output += composite["video"]
        self.colour.extend(composite["colour"])

    def render_status(lives, score, columns):
        colour = []
        video = "{lives:1d}".format(lives=lives)
        video += "{score:>{width}d}".format(score=score,
                                            width=columns - len(video))
        for i in range(len(video)):
            colour.append(0)
        return {"video": video, "colour": colour}

    def refresh(self):
        self.display.refresh(self.output, self.colour)

    def update_field(self):
        new_field = GameField(self.field.width(), self.field.height())
        for wall in self.walls:
            new_field.add(wall.coordinates, wall)
        for pill in self.pills:
            new_field.add(pill.coordinates, pill)
        for ghost in self.ghosts:
            new_field.add(ghost.coordinates, ghost)
        if self.pacman:
            new_field.add(self.pacman.coordinates, self.pacman)
        if self.game_over:
            Game.print_game_over(new_field)
        self.field = new_field

    def get_element(self, coords):
        return self.field.get(coords)

    def is_ghost(self, coordinates):
        return Ghost.is_ghost(self.field.get(coordinates))

    def is_wall(self, coordinates):
        return Wall.is_wall(self.field.get(coordinates))

    def is_gate(self, coordinates):
        return Wall.is_gate(self.field.get(coordinates))

    def is_field(self, coordinates):
        return Wall.is_field(self.field.get(coordinates))

    def is_pill(self, coordinates):
        return Pill.is_pill(self.field.get(coordinates))

    def is_pacman(self, coordinates):
        return isinstance(self.field.get(coordinates), Pacman)

    def eat_pill(self, coordinates):
        pill = self.field.get(coordinates)
        self.pills.remove(pill)
        self.score += pill.score()
        for ghost in self.ghosts:
            ghost.trigger_effect(pill)

    def kill_ghost(self, coordinates):
        ghost = self.field.get(coordinates)
        self.score += ghost.score()
        ghost.kill()

    def kill_pacman(self):
        self.pacman.kill()
        self.lives -= 1
        if (self.lives == 0):
            self.game_over = True

    def get_pacman(self):
        return self.pacman

    def set_controller(self, controller):
        self.controller = controller

    def set_display(self, display):
        self.display = display

    def move(self, direction):
        self.pacman.move(direction)

    def set_level(self, level):
        self.level = level

    def set_max_level(self, level):
        self.last_level = level

    def is_level_clear(self):
        return (len(self.pills) == 0) and self.using_pills

    def next_level(self):
        if self.level < self.last_level:
            self.level += 1
            self.pills[:] = []
            self.walls = []
            self.ghosts = []
            self.parse()
        else:
            self.game_over = True
            self.pacman.restart()

    def use_animation(self):
        self.animation = True

    def get_lives(self):
        return self.lives

    def get_score(self):
        return self.score

    def print_game_over(field):
        cols = field.width()
        rows = field.height()
        GAME = "GAME"
        OVER = "OVER"
        y = floor(rows / 2) - 2
        padding = floor(((cols - 2) - len(GAME)) / 2)
        for i in range(len(GAME)):
            x = padding + i + 1
            field.add((x, y), GAME[i])
            field.add((x, y+1), OVER[i])

    def set_player(self, player):
        self.player = player

    def post_score(self):
        if self.scoreboard is None:
            scoreboard_url = os.getenv("SCOREBOARD_URL")
            self.scoreboard = Scoreboard(scoreboard_url, self.player)
        self.scoreboard.post_score(self.score)

    def get_scores(self):
        response = self.scoreboard.scores()
        scores = []
        for score in response:
            name = score.player
            points = str(score.score)
            scores.append(name + ":" + points)
        return scores
    def process(self, screen):
        '''
        Triggers all game processes.

        Parameters
        ----------
        screen : TYPE Pygame screen.
            DESCRIPTION. Where everything is drawn.

        Returns
        -------
        None.

        '''
        menu = Menu(screen)
        menu.load(screen)
        player = [
            Player(color_of_player[0], color_name_of_player[0],
                   starting_set_of_ships_for_player0),
            Player(color_of_player[1], color_name_of_player[1],
                   starting_set_of_ships_for_player1)
        ]
        game_field = GameField(game_field_width, game_field_hight)
        game_field.update([player[0].ships, player[1].ships])
        self.renderer.draw_game_field(screen, game_field.cells,
                                      [player[0].ships, player[1].ships])
        exited = False
        finished = False
        number_of_active_player = 1
        while not exited:
            number_of_active_player += 1
            number_of_active_player %= 2
            player[number_of_active_player].update_ships_movement_points()
            player[number_of_active_player].activate_cells_of_ships()
            turn_passed = False
            while not turn_passed:
                clock.tick(FPS)
                turn_passed, finished, exited = self.handle_events(
                    game_field, player, number_of_active_player,
                    pygame.event.get())
                game_field.update([player[0].ships, player[1].ships])
                self.renderer.draw_game_field(
                    screen, game_field.cells,
                    [player[0].ships, player[1].ships])
                #
                out = open('observe.txt', 'a')
                out = open('observe.txt', 'w')
                for i in range(30):
                    for j in range(30):
                        print(
                            game_field.cells[j][i].type,
                            #game_field.cells[j][i].writing,
                            game_field.cells[j][i].orientation,
                            game_field.cells[j][i].is_chosen,
                            end='|',
                            file=out)
                    print(end='\n', file=out)
                #
            if finished:
                for i in range(len(player)):
                    if len(player[i].ships) > 0:
                        self.renderer.finish_the_game(screen, player[i].color,
                                                      player[i].color_name)
                while not exited:
                    clock.tick(FPS)
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            exited = True
예제 #18
0
    def set_game(self):
        self.pacman_alive = True
        self.kostul = True
        self.counterOfEatenFruits = 0
        self.gameover_exists = False
        self.counter = Counter()
        self.state = STATES["game"]
        self.ghosts.clear()
        self.objects.clear()
        self.objects.append(
            GameField([
                pygame.transform.scale(pygame.image.load("./Entity/Map.png"),
                                       (424, 468))
            ], [0, 0, 424, 468]))
        self.objects.append(
            Pacman(self.genPacmanImg(), [229, 255, 20, 20], 0, 1))
        self.start_v = 33
        self.finish_v = 34
        cnt = -1
        for v in self.graph.coordinates:
            cnt += 1
            name_on = "./Entity/Fruit/ SeedOn.png"
            name_off = "./Entity/Fruit/seedOff.png"
            self.objects.append(
                Seed([[
                    pygame.transform.scale(pygame.image.load(name_on), (2, 2))
                ], [
                    pygame.transform.scale(pygame.image.load(name_off), (2, 2))
                ]], [v[0] - 1, v[1] - 1, 2, 2]))  ## 3-68 элементы - зерна
            if 28 <= cnt <= 30:
                self.objects[-1].change_type(1)
        self.objects.append(
            Ghost(self.genPinkGhostImg(), [
                self.graph.coordinates[29][0], self.graph.coordinates[29][1],
                20, 20
            ], 0))  ## 69 элемент - розовый призрак
        self.objects.append(
            Ghost(self.genRedGhostImg(), [
                self.graph.coordinates[28][0], self.graph.coordinates[28][1],
                20, 20
            ], 0))  ## 70 элемент - красный призрак

        cnt = -1
        cnt = random.randint(0, 66)  # генерация фруктов
        while (28 <= cnt <= 30):
            cnt = random.randint(0, 66)
        v = self.graph.coordinates[cnt]
        self.objects[cnt + 2].change_type(1)
        i = random.randint(1, 5)
        self.fruit_index = len(self.objects)
        name_on = "./Entity/Fruit/fruit" + str(i) + ".png"
        name_off = "./Entity/Fruit/seedOff.png"
        self.objects.append(
            Fruit([[
                pygame.transform.scale(pygame.image.load(name_on), (15, 15))
            ], [pygame.transform.scale(pygame.image.load(name_off),
                                       (15, 15))]],
                  [v[0] - 5, v[1] - 8, 15, 15]))
        #self.objects[69].move_to_point([self.graph.coordinates[29][0], self.graph.coordinates[29][1]])
        self.objects[69].start_moving_to_point([
            self.graph.coordinates[23][0] - 10,
            self.graph.coordinates[23][1] - 10
        ])
        self.ghosts.append([69, 29, 23])
        self.objects[70].start_moving_to_point([
            self.graph.coordinates[29][0] - 10,
            self.graph.coordinates[29][1] - 10
        ])
        self.ghosts.append([70, 28, 29])
예제 #19
0
    def reset_gui(self):

        #this method is called when game has ended and is
        #switched back to starting screen
        #this is test version of this method

        #Init win and lose screen values for a new game
        self.first_win_screen = True
        self.first_lose_screen = True
        self.restart = True  # This adjusts scene rect when user restarts the game

        #initialize gamefield's key press capturing class variables
        GameField.Right_arrow = 0
        GameField.Left_arrow = 0
        GameField.Space = 0

        #create same widget as in init, make scene and view not drawn
        self.scene.setSceneRect(0, 0, 0, 0)
        self.scene_view.setFixedSize(0, 0)

        #delete all the items in the scene
        self.scene.clear()
        #These need to be redefined because the old items were destroyed above
        self.end_text = QGraphicsTextItem('GAME OVER,')
        self.continue_text = QGraphicsTextItem(
            'Continue by pressing the button')
        self.win_text = QGraphicsTextItem('YOU WON!')
        self.lose_text = QGraphicsTextItem('YOU LOST')

        #initialize gamefield
        path = os.getcwd()  #get the current working dir
        os.chdir(path)  #change dir to the current working dir
        os.chdir('game_levels')

        #open the file, it should always success because this file has been already opened and checked

        file = open(self.gamefield_level, 'r')

        #parse a gamefield and a copy from the file

        gamefield = GameField()

        return_value = gamefield.parse_gamefield(file)
        file.close()
        self.gamefield = gamefield

        os.chdir(path)  #change dir to the current working dir

        #initialize all lists of scene items
        self.enemy_items = []
        self.static_items = []

        #set the correct screen style
        GameField.Fail = False

        pixmap = QPixmap(
            'start_screen_test.png')  #this pic will be changed later

        widget = QLabel()
        widget.setPixmap(pixmap)
        widget.setScaledContents(True)
        self.setCentralWidget(widget)
        self.centralWidget().setLayout(self.layout)

        #enable start and cancel buttons and disable continue button
        self.start_button.setEnabled(True)
        self.start_button.setFixedSize(70, 50)
        self.cancel_button.setEnabled(True)
        self.cancel_button.setFixedSize(70, 50)

        self.continue_button.setFixedSize(0, 0)
        self.continue_button.setEnabled(False)

        #this is for changing the background color, prior was used for testing (that's why name is not good)
        self.count = 0
예제 #20
0
    )  #create config object, this must be done before creating gui or gamefield objects
    if config.config_return_value:
        #If is true when return value is 1 or 2

        if config.config_return_value == 2:
            print('NOTICE: There is something wrong in the config file')
            print('The game is partially using standard set values')

        #file = open('erikoisempi_kentta.txt','r')
        #file = open('vihollis_testi_kentta.txt','r')
        file = open('game_testi.txt', 'r')
        #file = open('leijuva_testi_kentta.txt','r')
        #file = open ('erilainen_kentta.txt','r')
        #file = open('melko_tyhja_kentta.txt','r')

        gamefield = GameField()
        gamefield.parse_gamefield(file)
        file.close()

        #file = open('erikoisempi_kentta.txt','r')
        #file = open('vihollis_testi_kentta.txt','r')
        #file = open('game_testi.txt','r')
        #file = open('leijuva_testi_kentta.txt','r')
        #file = open ('erilainen_kentta.txt','r')
        file = open('melko_tyhja_kentta.txt', 'r')

        gamefield_copy = GameField()
        gamefield_copy.parse_gamefield(file)
        file.close()

        main = Gui()
예제 #21
0
class Game:
    size = None
    screen = None
    star_background = None
    game_field = None
    game_speed = 1
    game_thread = None
    player = None
    fps = 60
    running = True
    gameover = False
    waiting = True
    font = None
    padding = 20
    score = 0
    random_color = [255, 0, 0]
    milestone = 2000
    hit = 0
    highscore = 0
    fpsClock = pygame.time.Clock()

    def __init__(self, size):
        self.size = size
        pygame.font.init()
        self.score = 0
        self.star_background = Stars(self.size)
        self.font = pygame.font.Font("res/font.ttf", 28)
        self.screen = pygame.display.set_mode(size)
        if not self.gameover:
            self.new_game()
        self.loop()

    def new_game(self):
        self.running = True
        self.waiting = True
        self.gameover = False
        self.milestone = 100
        self.game_speed = 1
        self.lives = 4
        self.game_field = GameField(self.size)
        self.player = Player(
            [self.size[0] / 2 - Player.size[0] / 2, self.size[1] - 80],
            [255, 255, 255])

    def draw_score(self):
        fps = self.font.render("x" + str(round(self.game_speed, 2)), False,
                               (255, 255, 255))
        self.screen.blit(fps, (self.padding, self.padding))
        lives = self.font.render(
            str(self.lives) + " Lives", False, (255, 255, 255))
        self.screen.blit(
            lives,
            (self.size[0] - lives.get_width() - self.padding, self.padding))
        score = self.font.render(str(int(self.score)), False, (255, 255, 100))
        self.screen.blit(
            score, ((self.size[0] / 2) - score.get_width() / 2, self.padding))
        if self.waiting:
            start = self.font.render("Press any key to start", False,
                                     self.random_color)
            self.screen.blit(
                start,
                ((self.size[0] / 2) - start.get_width() / 2,
                 (self.size[1] - start.get_height()) - self.padding - 140))
        if self.gameover or self.waiting:
            highscore = self.font.render(
                "Highscore: " + str(int(self.highscore)), False,
                (255, 255, 255))
            self.screen.blit(highscore,
                             ((self.size[0] / 2) - highscore.get_width() / 2,
                              self.padding + self.size[1] / 2))

    def render_game(self):
        self.star_background.render(self.screen)
        self.game_field.render(self.screen)
        self.player.render(self.screen)
        self.draw_score()

    def update_score(self):
        if not self.gameover:
            self.score += self.game_speed * 0.1
        if self.score > self.highscore:
            self.highscore = self.score

    def game_over_animation(self):
        if self.game_speed > 0.5:
            self.game_speed -= 0.01
        if self.player.pos[1] < self.size[1]:
            self.player.pos[1] += 0.5
        else:
            new = True
            for obj in self.game_field.objects:
                if obj.pos[1] < self.size[1]:
                    new = False
            if new:
                self.new_game()

    def update_game(self):
        self.star_background.update(2 * self.game_speed)

        if self.score > self.milestone and not self.waiting:
            self.milestone += 250 * self.game_speed * self.game_speed
            print(self.milestone)
            self.game_speed += 0.5

        if not self.waiting:
            self.game_field.update(4 * self.game_speed, self.gameover)
            self.update_score()
            if self.lives <= 0:
                self.gameover = True

            if self.game_field.is_colliding(self.player):
                if not self.lives <= 0:
                    self.lives -= 1
                    self.hit = 10
            self.player.update(4 * self.game_speed, self.size[0])

    def event_handling(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if not self.waiting and not self.gameover:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        self.player.move_left = True
                    if event.key == pygame.K_RIGHT:
                        self.player.move_right = True
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT:
                        self.player.move_left = False
                    if event.key == pygame.K_RIGHT:
                        self.player.move_right = False
            if self.waiting:
                if event.type == pygame.KEYDOWN:
                    self.score = 0
                    self.game_speed = 1
                    self.waiting = False

    def animation_handling(self):
        if self.gameover:
            self.game_over_animation()

        if self.hit > 0:
            self.hit -= 1

    def calc_colors(self):
        j = 0
        while j < len(self.random_color):
            self.random_color[j] += (j + 1) * 10
            if self.random_color[j] > 255:
                self.random_color[j] = 0
            j += 1

    def loop(self):
        while self.running:
            if self.hit == 0:
                self.screen.fill((0, 0, 0))
            else:
                self.screen.fill(self.random_color)

            self.animation_handling()
            self.calc_colors()
            self.event_handling()
            self.update_game()

            self.render_game()
            pygame.display.flip()
            self.fpsClock.tick(self.fps)
예제 #22
0
def main():

    file1 = open('game_testi.txt','r')
    gamefield1 = GameField()
    print(gamefield1.player)
    print(GameField.Space)
    
    

    gamefield1.parse_gamefield(file1)
    print('leveli on :{}'.format(gamefield1.max_level))
    print(gamefield1.player)

    print(gamefield1.player.position.x_min) #this should be 100
    print(gamefield1.player.position.x_max) #this should be 130
    print(gamefield1.player.position.y_max) #this should be 250+3*50=400
    print(gamefield1.player.position.y_min) # 460

    #those coordinates (in comments) were wrong and the should be ignored

    for i in range(0,len(gamefield1.ground_objects)):
        ob = gamefield1.ground_objects[i].position
        print('ground objekti y_min: {} y_max: {} x_min: {} x_max: {}'.format(ob.y_min,ob.y_max, ob.x_min, ob.x_max))

    print()
    for i in range (len(gamefield1.static_objects)):
        #print all positions (compare to game_testi.txt)
        ob = gamefield1.static_objects[i].position
        if gamefield1.static_objects[i].type == 'finish_object':
            print('maali loytyy')
        print('y_min: {} y_max: {} x_min: {} x_max: {}'.format(ob.y_min,ob.y_max, ob.x_min, ob.x_max))

    for i in range (len(gamefield1.enemies)):
        enemy = gamefield1.enemies[i].position 
        print('enemies in file: y_min {}, y_max {}, x_min {}, x_max {}'.format(enemy.y_min, enemy.y_max, enemy.x_min, enemy.x_max))

    enemy = gamefield1.enemies[1].position #2 enemy which is read so it's enemy at the bottom left corner
    print('enemy 2 in file: y_min {}, y_max {}, x_min {}, x_max {}'.format(enemy.y_min, enemy.y_max, enemy.x_min, enemy.x_max))

    print(gamefield1.static_objects[27].type) #shoud be invisible

    file1.close()
    print()

    file2 = open('game_testi2.txt','r')
    gamefield2 = GameField()
    gamefield2.parse_gamefield(file2) #should be same as test 1 but 1 more line so y location should be shiftet 50 down
    for i in range (len(gamefield2.static_objects)):
        #print all positions (compare to game_testi.txt)
        ob = gamefield2.static_objects[i].position
        print('y_min: {} y_max: {} x_min: {} x_max: {}'.format(ob.y_min,ob.y_max, ob.x_min, ob.x_max))

    file2.close()
    print()

    #let's test malformed files

    file3 = open ('game_testi_broken1.txt')
    #this file is missing one - so it's not well-formed

    gamefield3 = GameField()
    ret = gamefield3.parse_gamefield(file3) #should return false and print error message
    print(ret)
    file3.close()

    gamefield4 = GameField()
    file4 = open('game_testi_broken2.txt')
    #file is missing finish

    print()
    gamefield4.parse_gamefield(file4)
    file4.close()

    gamefield5 = GameField()
    file5 = open('game_testi_broken3.txt')
    #file contains too many player locations

    print()
    gamefield5.parse_gamefield(file5)
    file5.close()


    gamefield6 = GameField()
    file6 = open('game_testi_broken4.txt')
    #file contains incorrect object symbol

    print()
    gamefield6.parse_gamefield(file6)
    file5.close()