Example #1
0
 def __init__(self):
     super(OptionsScreen, self).__init__()
 
     self.font = utils.getFont('VolterGoldfish', 44)
     self.infofont = utils.getFont('VolterGoldfish', 18)
     self.keyfont = utils.getFont('VolterGoldfish', 24)
     self.background = pygame.image.load("../img/backgrounds/options.png").convert()
     self.soundBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
     self.musicBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
     self.keyImg = pygame.image.load("../img/backgrounds/key.png").convert_alpha()
     self.volumeTest = pygame.mixer.Sound("../sounds/volumeTest.wav")
     self.menuEntries = ["Music","Sound","Controls","Back"]
     self.menuPositions = [(200,100),(200,200),(200,300),(200,500)]
     self.menuChoice = 0
     self.activeColor = THECOLORS["black"]
     self.inactiveColor = THECOLORS["grey64"]
     self.soundLevel = 0
     if exist('soundLevel'):
         self.soundLevel = load('soundLevel')
     self.musicLevel = 0
     if exist('musicLevel'):
        self.musicLevel = load('musicLevel')
     self.actionKeys = ['slow time','shield','trap','left','jump','right']
     self.keys = ['w','x','c','<','^','>']
     self.actionKeysPos = [(200,450),(330,450),(430,450),(530,450),(630,450),(730,450)]
Example #2
0
 def __init__(self):
     super(StartScreen, self).__init__()
     self.enterFont = utils.getFont("VolterGoldfish", 40)
     self.infoFont = utils.getFont("VolterGoldfish", 18)
     self.background = pygame.image.load("../img/backgrounds/title_pix.png").convert()
     self.running = True
     self.enterColors = (235, 246, 242)
     self.frameNumber = 0
     self.fade = 1
     self.msg = "A game using pygame and pyganim"
Example #3
0
    def redraw(self):
        self.image.fill(utils.green)

        self.ghostText = utils.getFont(size=24, style="bold").render(self.winMessage, True, utils.gray)
        self.image.blit(self.ghostText, (25, 25))

        self.text = utils.getFont(size=24, style="bold").render(self.displayMessage, True, utils.black)
        self.image.blit(self.text, (25, 25))
        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 500
Example #4
0
 def __init__(self):
     super(MainMenuScreen, self).__init__()
     self.font = utils.getFont('VolterGoldfish', 44)
     self.infofont = utils.getFont('VolterGoldfish', 18)
     self.background = pygame.image.load("../img/backgrounds/mainMenu.png").convert()
     self.menuEntries = ["Start Game","Options","Quit"] ## add continue -> levelMenuScreen
     self.menuPositions = [(200,100),(200,300),(200,500)]
     self.menuInfo = ["Start or continue your adventure","Change game and user settings","Exit the game. Goodbye!"]
     self.menuChoice = 0
     self.activeColor = THECOLORS["black"]
     self.inactiveColor = THECOLORS["grey64"]
Example #5
0
    def __init__(self, pos, size, color, text, action):
        Button.__init__(self, pos, size, color, action)

        self.fontSize = self.rect.h
        self.text = utils.getFont(size=self.fontSize,
                                  style='bold').render(text, True, utils.black)
        self.textRect = self.text.get_rect()

        while self.textRect.w > self.rect.w:
            self.fontSize -= 2
            self.text = utils.getFont(size=self.fontSize, style='bold').render(
                text, True, utils.black)
            self.textRect = self.text.get_rect()
Example #6
0
    def redraw(self):
        self.image.fill(utils.GREEN)

        self.ghostText = utils.getFont(size=24,
                                       style='bold').render(self.winMessage,
                                                            True, utils.GREY)
        self.image.blit(self.ghostText, (25, 25))

        self.text = utils.getFont(size=24,
                                  style='bold').render(self.displayMessage,
                                                       True, utils.BLACK)
        self.image.blit(self.text, (25, 25))
        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 500
Example #7
0
    def gotoMenu(self):
        rect = self.gw.get_rect()

        def startPlay():
            self.menu = False


        playB = TextButton((rect.centerx, rect.centery-50), (200, 80), utils.green, "Play", startPlay)
        quitB = TextButton((rect.centerx, rect.centery+50), (200, 80), utils.red, "Quit", self.quitGame)

        self.menu = True
        while self.menu:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.quitGame()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        menu = False

                self.gw.fill(utils.white)

                text = utils.getFont(size=82, style="bold").render("Tutorial Game", True, utils.black)
                textRect = text.get_rect()
                textRect.center = self.gw.get_rect().center
                textRect.y -= 200
                self.gw.blit(text, textRect)

                playB.update(self.gw)
                quitB.update(self.gw)

                pygame.display.update()
                self.clock.tick(self.FPS)
Example #8
0
    def gotoMenu(self):
        rect = self.gameWindow.get_rect()

        def startPlay():
            self.menu = False

        playB = TextButton((rect.centerx, rect.centery - 100), (200, 80),
                           utils.GREEN, "Play", startPlay)
        quitB = TextButton((rect.centerx, rect.centery + 50), (200, 80),
                           utils.RED, "Quit", self.quitGame)

        self.menu = True
        while self.menu:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.quitGame()
                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_q:
                        self.menu = False

            self.gameWindow.fill(utils.WHITE)
            text = utils.getFont(size=82,
                                 style='bold').render("Tutorial Game", True,
                                                      utils.BLACK)
            textRect = text.get_rect()
            textRect.center = self.gameWindow.get_rect().center
            textRect.y -= 250
            self.gameWindow.blit(text, textRect)
            playB.update(self.gameWindow)
            quitB.update(self.gameWindow)

            pg.display.update()
            self.clock.tick(self.FPS)
Example #9
0
    def gotoMenu(self):
        rect = self.gw.get_rect()

        def startPlay():
            self.menu = False

        playB = TextButton((rect.centerx, rect.centery - 50), (200, 80),
                           utils.green, "Play", startPlay)
        quitB = TextButton((rect.centerx, rect.centery + 50), (200, 80),
                           utils.red, "Quit", self.quitGame)

        self.menu = True
        while self.menu:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.quitGame()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        menu = False

                self.gw.fill(utils.white)

                text = utils.getFont(size=82, style="bold").render(
                    "Tutorial Game", True, utils.black)
                textRect = text.get_rect()
                textRect.center = self.gw.get_rect().center
                textRect.y -= 200
                self.gw.blit(text, textRect)

                playB.update(self.gw)
                quitB.update(self.gw)

                pygame.display.update()
                self.clock.tick(self.FPS)
Example #10
0
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.name = random.choice(charList)
        self.image = utils.getFont(size=26, style='bold').render(self.name, True, utils.black)
        self.rect = self.image.get_rect()

        self.rect.x = random.randint(0, 100 - self.rect.width)
        self.rect.y = random.randint(0, 100 - self.rect.height)

        self.xmove = random.choice([-1, 1])
        self.ymove = random.choice([-1, 1])
        self.speed = 20.0
    def redraw(self):
        self.image.fill(utils.green)

        elements = [str(len(self.displayMessage)), "of", str(len(self.winMessage))]

        for i, string in enumerate(elements):
            self.text = utils.getFont().render(string, True, utils.black)
            self.image.blit(self.text, (20, 5 + i*22))


        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 500
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.name = random.choice(charList)
        self.image = utils.getFont(size=26, style='bold').render(self.name, True, utils.black)
        self.rect = self.image.get_rect()

        self.rect.x = random.randint(0, 100 - self.rect.width)
        self.rect.y = random.randint(0, 100 - self.rect.height)

        self.xmove = random.choice([-1, 1])
        self.ymove = random.choice([-1, 1])
        self.speed = 20.0
Example #13
0
    def __init__(self):
        pg.sprite.Sprite.__init__(self)

        self.name = rnd.choice(charList)
        self.image = utils.getFont(size=30,
                                   style='bold').render(self.name,
                                                        True, utils.BLACK)
        self.rect = self.image.get_rect()

        self.rect.x = rnd.randint(5, 75)
        self.rect.y = rnd.randint(5, 75)

        self.xmove = rnd.choice([-2, -1, 1, 2])
        self.ymove = rnd.choice([-2, -1, 1, 2, 1])
        self.speed = 20.0
Example #14
0
    def redraw(self):
        self.image.fill(utils.green)

        elements = [
            str(len(self.displayMessage)), "of",
            str(len(self.winMessage))
        ]

        for i, string in enumerate(elements):
            self.text = utils.getFont().render(string, True, utils.black)
            self.image.blit(self.text, (20, 5 + i * 22))

        self.rect = self.image.get_rect()
        self.rect.x = 100
        self.rect.y = 500
Example #15
0
 def __init__(self):
     super(LevelSelectScreen, self).__init__()
     self.font = utils.getFont('VolterGoldfish', 44)
     self.background = pygame.image.load("../img/backgrounds/levelSelect.png").convert()
     self.levelTitles = ["Tutorial","Green Machine", "Strange Orange", "Purple Trouble"]
     self.levelBackgrounds = []
     self.lvlbgsNames = []
     self.currentLevel = 0
     self.menuEntries = ["Stage 1","Stage 2","Stage 3","Back"]
     self.menuPositions = [(200,100),(200,200),(200,300),(200,500)]
     self.activeColor = THECOLORS["black"]
     self.inactiveColor = THECOLORS["grey64"]
     self.menuChoice = 0
     self.running = True
     self.frame_number = 0
Example #16
0
 def __init__(self, levelInd):
     super(GameScreen, self).__init__()
     self.fadeScreen    = pygame.image.load("../img/backgrounds/blackscreen.png").convert()
     self.font          = getFont("VolterGoldfish", 20)
     self.nextColorIcon = pygame.image.load("../img/hud/nextColor23.png").convert_alpha()
     self.progressIcon  = pygame.image.load("../img/hud/progress.png").convert_alpha()
     self.timebar       = pygame.image.load("../img/hud/timebar.png").convert_alpha()
     self.shieldbar     = pygame.image.load("../img/hud/shieldbar.png").convert_alpha()
     self.lifebar_      = pygame.image.load("../img/hud/lifebar_.png").convert()
     
     self.level         = Level(levelInd)
     self.camera        = Camera(640, 800, 3200)
     # running          = True
     self.retry         = False
     self.frame_number  = 0
     self.anims         = []
     
     self.stopDelay     = 0
     self.stopped       = False
     
     self.killFragments = []
     self.dust          = []
     
     self.starting      = True
     self.ending        = False
     self.alpha         = 255
     
     
     # Music load
     # pygame.mixer.music.load("../sounds/piano.wav")
     # pygame.mixer.music.play(-1)
     pygame.mixer.music.set_volume(0.5)
     
     # Player
     self.player        = Player()
     self.fire          = Rect((0,3200),(800,5))
     self.playerDown    = False
     
     
     self.answerPos     = [(100,300),(100,400),(100,500)]
     self.answerChoice  = 0
     self.activecolor   = THECOLORS['white']
     self.inactivecolor = THECOLORS['grey21']
     
     if exist('powers'):
         self.player.timePower, self.player.mines, self.player.shields = load('powers')
Example #17
0
    def pause(self):
        pause = True
        while pause:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.quitGame()
                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_p:
                        print("Game unpaused.")
                        pause = False

                text = utils.getFont(size=96, style='bold').render(
                    "PAUSED", True, utils.BLACK)
                textRect = text.get_rect()
                textRect.center = self.gameWindow.get_rect().center

                self.gameWindow.blit(text, textRect)
                pg.display.update()
                self.clock.tick(self.FPS)
Example #18
0
    def pause(self):
        pause = True
        while pause:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        print "game unpaused"
                        pause = False

                text = utils.getFont(size=96, style="bold").render("Paused", True, utils.black)
                textRect = text.get_rect()
                textRect.center = self.gw.get_rect().center

                self.gw.blit(text, textRect)

                pygame.display.update()
                self.clock.tick(self.FPS)
Example #19
0
    def pause(self):
        pause = True
        while pause:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        print "game unpaused"
                        pause = False

                text = utils.getFont(size=96, style="bold").render(
                    "Paused", True, utils.black)
                textRect = text.get_rect()
                textRect.center = self.gw.get_rect().center

                self.gw.blit(text, textRect)

                pygame.display.update()
                self.clock.tick(self.FPS)
Example #20
0
        game.see_coeff_box = False


def cancel_update():
    game.see_coeff_box = False


def defaults():
    game.controller.p_const = .1
    game.controller.i_const = 1/60
    game.controller.d_const = 1/30
    reset_func()
    game.see_coeff_box = False


settings_startbtn = {"text": "Start! (s)", "font": utils.getFont()}
settings_exitbtn = {"text": "Exit (esc)", "font": utils.getFont()}
settings_input_updatebtn = {"text": "Update coefficients (c)", "font": utils.getFont()}
settings_controller_input_box = {"active": False}
settings_show_sensors = {"text": "Show Sensors", "font": utils.getFont()}
settings_hide_sensors = {"text": "Hide Sensors", "font": utils.getFont()}
settings_reset = {"text": "Reset", "font": utils.getFont()}
settings_update_coeffs = {"text": "Update coefficients", "font": utils.getFont(size=12)}
settings_confirm_update = {"text": "Update!", "font": utils.getFont(size=12)}
settings_cancel_update = {"text": "Cancel", "font": utils.getFont()}
settings_defaults = {"text": "Default Values", "font": utils.getFont(size=12)}

if __name__ == "__main__":
    pg.init()
    gameWindow = pg.display.set_mode((800, 600))
    game = PIDCar(gameWindow)
Example #21
0
def newWork(srcName, k, fontSize, subtitle_type):
    videoSrc = './videoSrc/%s' % srcName
    src = srcName[:-4]
    srtSrc = './subtitle/srt/%s.srt' % src
    if subtitle_type == "adaptive":
        file_name = json.dumps(config) + src
    elif subtitle_type == "simple_opposite":
        file_name = "simple_opposite+" + src
    elif subtitle_type == "whole_background_level":
        file_name = "whole_background_level" + src
    elif subtitle_type == "low_penalty":
        file_name = "low_penalty" + src
    outputDir = './videoOutput/%s' % src
    if not os.path.exists(outputDir):
        os.mkdir(outputDir)
    # file_name = "CIE1976-KeyFrameArbitraryColor-FixOutputBug-ExpFrameMeanDelta-distancestandard-60_translossbeta-0.2_DPcolor_tolerance-3-" + src
    # file_name = "white-" + src
    # file_name = "black-" + src

    # Record statistics
    log_statistics = {}
    log_statistics["frame"] = []
    log_statistics["max_min_distance"] = []
    log_statistics["max_min_distance_color"] = []
    log_statistics["chosen_color"] = []
    log_statistics["frame_loss"] = []

    # process srt and load video
    cap = cv.VideoCapture(videoSrc)
    fps = cap.get(cv.CAP_PROP_FPS)
    subs = processSRT(srtSrc, fps)

    # process colors and font
    font = getFont('Consolas', fontSize)

    # findChange(cap, src, font, k)
    # analysisColorTune(cap)

    frame_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))

    my_palette = load_palette()
    color_tune_analyzer = ColorTuneAnalyzer(frame_width=frame_width,
                                            frame_height=frame_height,
                                            n_cluser=config["tune_num"])

    status = {}
    if subtitle_type == "adaptive" or subtitle_type == "whole_background_level" or subtitle_type == "low_penalty":
        previous_sub = None
        for sub in subs:
            start = time.time()
            status[sub] = workOnSingleSub(cap=cap,
                                          now_sub=sub,
                                          palette=my_palette,
                                          font=font,
                                          k=k,
                                          color_analyzer=color_tune_analyzer,
                                          previous_sub=previous_sub,
                                          log_statistics=log_statistics,
                                          subtitle_type=subtitle_type)
            previous_sub = sub
            print(sub, " : ", time.time() - start)
        if subtitle_type == "low_penalty":
            for sub in subs:
                status[sub]["chosen_color"] = status[sub][
                    "max_min_distance_color"]
        else:
            # DP
            DP_all_frames(status=status,
                          subs=subs,
                          palette=my_palette,
                          log_statistics=log_statistics)
            outputLog(log_statistics,
                      file_path=os.path.join(outputDir, file_name + ".csv"))
    elif subtitle_type == "simple_opposite":
        for sub in subs:
            start = time.time()
            status[sub] = simpleOppositeOnSingleSub(cap, sub, font, k)
            print(sub, " : ", time.time() - start)

    # output
    resultPath = os.path.join(outputDir, file_name + ".mp4")
    fourcc = cv.VideoWriter_fourcc(*"mp4v")
    # fourcc = cv.VideoWriter_fourcc(*"H264")
    videoWriter = cv.VideoWriter(resultPath, fourcc, fps,
                                 (frame_width, frame_height))

    # add subtitle and output
    cap.set(cv.CAP_PROP_POS_FRAMES, 0)
    _, frame = cap.read()
    itr = iter(subs)
    nowSub = next(itr, None)
    resColor = iter(status[nowSub]["chosen_color"])
    # resColor = iter(status[nowSub]["max_min_distance_color"])
    text = nowSub.text

    im = Image.fromarray(cv.cvtColor(frame, cv.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(im)
    textWidth, textHeight = getTextInfoPIL(draw, text, font)

    cap.set(cv.CAP_PROP_POS_FRAMES, 0)

    frame_id = 0
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            if frame_id % 100 == 0:
                print("Frame {} Complete!".format(frame_id))

            if nowSub is not None:
                if frame_id >= nowSub.start and frame_id < nowSub.end:
                    # RGB
                    im = Image.fromarray(cv.cvtColor(frame, cv.COLOR_BGR2RGB))
                    draw = ImageDraw.Draw(im)
                    drawSubtitle(draw, text,
                                 (frame_width // 2 - textWidth // 2,
                                  frame_height - k * textHeight), font,
                                 next(resColor))
                    # drawSubtitle(draw, text, (frame_width // 2 - textWidth // 2, frame_height - k * textHeight), font,
                    #              [0, 0, 0])
                    frame = cv.cvtColor(np.asarray(im), cv.COLOR_RGB2BGR)

            videoWriter.write(frame)

            frame_id += 1
            # change to next subtitle
            if (nowSub is not None) and (frame_id >= nowSub.end):
                nowSub = next(itr, None)
                if nowSub is not None:
                    resColor = iter(status[nowSub]["chosen_color"])
                    # resColor = iter(status[nowSub]["max_min_distance_color"])
                    text = nowSub.text
                    im = Image.fromarray(cv.cvtColor(frame, cv.COLOR_BGR2RGB))
                    draw = ImageDraw.Draw(im)
                    textWidth, textHeight = getTextInfoPIL(draw, text, font)
        else:
            videoWriter.release()
            break
    cap.release()
    return 0
Example #22
0
    def gotoMenu(self):
        while self.menu:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.quitGame()
                if event.type == pg.KEYUP:
                    if event.key == pg.K_s:
                        return
                    if event.key == pg.K_ESCAPE:
                        self.quitGame()
                    if event.key == pg.K_c:
                        input_updatebtn()

                self.start_btn.get_event(event)
                self.exit_btn.get_event(event)
                self.input_updatebtn.get_event(event)
                self.p_input.get_event(event)
                self.i_input.get_event(event)
                self.d_input.get_event(event)

            self.gameWindow.fill(utils.WHITE)

            """Text to display on screen"""
            title = utils.getFont(size=64, style='bold').render("Self-driving Car", False, utils.BLACK)
            titleRect = title.get_rect()
            titleRect.center = self.gameWindow.get_rect().center
            titleRect.y -= 250

            font = utils.getFont()
            settings_text = utils.getFont(style="bold").render("Controller Settings", False, utils.BLACK)
            settings_text_rect = settings_text.get_rect()
            settings_text_rect.center = self.gameWindow.get_rect().center
            settings_text_rect.y -= 200
            settings_text_rect.x -= 165

            proportional_word = font.render("Proportional", False, utils.BLACK)
            proportional_word_rect = proportional_word.get_rect()
            proportional_word_rect.center = self.gameWindow.get_rect().center
            proportional_word_rect.y -= 145
            proportional_word_rect.x -= 315

            integral_word = font.render("Integral", False, utils.BLACK)
            integral_word_rect = integral_word.get_rect()
            integral_word_rect.center = self.gameWindow.get_rect().center
            integral_word_rect.y -= 105
            integral_word_rect.x -= 315

            derivative_word = font.render("Derivative", False, utils.BLACK)
            derivative_word_rect = derivative_word.get_rect()
            derivative_word_rect.center = self.gameWindow.get_rect().center
            derivative_word_rect.y -= 65
            derivative_word_rect.x -= 315

            font.set_underline(True)
            coefficient_word = font.render("Coefficient", False, utils.BLACK)
            coefficient_word_rect = coefficient_word.get_rect()
            coefficient_word_rect.center = self.gameWindow.get_rect().center
            coefficient_word_rect.y -= 180
            coefficient_word_rect.x -= 315

            current_word = font.render("Current", False, utils.BLACK)
            current_word_rect = current_word.get_rect()
            current_word_rect.center = self.gameWindow.get_rect().center
            current_word_rect.y -= 180
            current_word_rect.x -= 25
            font.set_underline(False)

            p_value = font.render(str(round(self.controller_coeffs[0], 4)), False, utils.BLUE)
            p_value_rect = p_value.get_rect()
            p_value_rect.center = self.gameWindow.get_rect().center
            p_value_rect.y -= 145
            p_value_rect.x -= 25

            i_value = font.render(str(round(self.controller_coeffs[1], 4)), False, utils.BLUE)
            i_value_rect = i_value.get_rect()
            i_value_rect.center = self.gameWindow.get_rect().center
            i_value_rect.y -= 105
            i_value_rect.x -= 25

            d_value = font.render(str(round(self.controller_coeffs[2], 4)), False, utils.BLUE)
            d_value_rect = d_value.get_rect()
            d_value_rect.center = self.gameWindow.get_rect().center
            d_value_rect.y -= 65
            d_value_rect.x -= 25

            error_message = utils.getFont(size=16, style="bold").render(self.error_msg, False, utils.BLACK)
            error_message_rect = error_message.get_rect()
            error_message_rect.center = self.gameWindow.get_rect().center
            error_message_rect.y -= 80
            error_message_rect.x += 215
            """End text displays.  Make sure you blit/draw them all"""

            self.gameWindow.blit(title, titleRect)
            self.gameWindow.blit(settings_text, settings_text_rect)
            self.gameWindow.blit(coefficient_word, coefficient_word_rect)
            self.gameWindow.blit(proportional_word, proportional_word_rect)
            self.gameWindow.blit(integral_word, integral_word_rect)
            self.gameWindow.blit(derivative_word, derivative_word_rect)
            self.gameWindow.blit(current_word, current_word_rect)
            self.gameWindow.blit(p_value, p_value_rect)
            self.gameWindow.blit(i_value, i_value_rect)
            self.gameWindow.blit(d_value, d_value_rect)

            self.error_timer -= 1
            if self.error_timer <= 0:
                self.show_error_toggle = False
            else:
                self.show_error_toggle = True
            if self.show_error_toggle:
                self.gameWindow.blit(error_message, error_message_rect)

            self.start_btn.draw(self.gameWindow)
            self.exit_btn.draw(self.gameWindow)
            self.input_updatebtn.draw(self.gameWindow)
            self.p_input.update()
            self.p_input.draw(self.gameWindow)
            self.i_input.update()
            self.i_input.draw(self.gameWindow)
            self.d_input.update()
            self.d_input.draw(self.gameWindow)

            pg.display.update()
            self.clock.tick(self.FPS)
Example #23
0
    def playGame(self):  # maybe rename later?
        self.gotoMenu()

        gameActive = True
        rOffsets = []

        self.exit_btn.rect = pg.Rect(650, 570, 150, 30)

        for i in self.sensorList:
            rOffsets.append(i.rOffset)
        while gameActive:
            sensorRead = []
            colorPos = []

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    gameActive = False
                if event.type == pg.KEYUP:
                    if event.key == pg.K_ESCAPE:
                        self.quitGame()

                self.exit_btn.get_event(event)
                self.reset_btn.get_event(event)
                self.update_coeffs_btn.get_event(event)
                if self.see_sensors_btn:
                    self.show_sensors_btn.get_event(event)
                else:
                    self.hide_sensors_btn.get_event(event)
                if not self.see_coeff_box:
                    self.update_coeffs_btn.get_event(event)
                else:
                    self.confirm_update_btn.get_event(event)
                    self.p2_input.get_event(event)
                    self.i2_input.get_event(event)
                    self.d2_input.get_event(event)
                    self.cancel_btn.get_event(event)
                    self.defaults_btn.get_event(event)

            move = self.car.move(self.radian)

            self.gameWindow.fill(utils.WHITE)
            self.map.resetMap()
            self.car.update(self.map.activeMap)

            """
            bgOffset updates the background *and* also returns a tuple
            of the offset (x,y) coordinates between player location
            on the background and the screen pixel location. This tuple
            is used to draw the direction circle to the correct location.
            """

            bgOffset = self.map.update(self.gameWindow, self.car.rect, move)
            directionLoc = (self.car.rect.centerx + bgOffset[0],
                            self.car.rect.centery + bgOffset[1])
            self.direction.update(self.gameWindow, (directionLoc[0],
                                                    directionLoc[1]))

            retLocX = directionLoc[0] + int(round(125*self.cos_theta, 0))
            retLocY = directionLoc[1] + int(round(125*self.sin_theta, 0))
            self.dirReticle.update(self.gameWindow, (retLocX, retLocY))

            """
            Sensors move, then the sensors are read.
            The information from the read sensors is then
            passed to the PID controller
            """
            for i in self.sensorList:
                sensorRead.append(i.move(directionLoc, self.radian))
                colorPos.append((i.rect.centerx, i.rect.centery))

            errorCorrection = self.controller.PID(sensorRead, rOffsets, self.radian)

            if errorCorrection is not None:
                cos_theta, sin_theta, self.radian = errorCorrection

            error_message = utils.getFont(size=16, style="bold").render(self.error_msg, False, utils.BLACK)
            error_message_rect = error_message.get_rect()

            self.exit_btn.draw(self.gameWindow)
            self.reset_btn.draw(self.gameWindow)
            self.update_coeffs_btn.draw(self.gameWindow)
            if self.see_sensors_btn:
                self.show_sensors_btn.draw(self.gameWindow)
            else:
                self.hide_sensors_btn.draw(self.gameWindow)
            if not self.see_coeff_box:
                self.update_coeffs_btn.draw(self.gameWindow)
            else:
                self.confirm_update_btn.draw(self.gameWindow)
                self.cancel_btn.draw(self.gameWindow)
                self.p2_input.draw(self.gameWindow)
                self.p2_input.update()
                self.i2_input.draw(self.gameWindow)
                self.i2_input.update()
                self.d2_input.draw(self.gameWindow)
                self.d2_input.update()
                self.defaults_btn.draw(self.gameWindow)

                self.error_timer -= 1
                if self.error_timer <= 0:
                    self.show_error_toggle = False
                else:
                    self.show_error_toggle = True
                if self.show_error_toggle:
                    self.gameWindow.blit(error_message, error_message_rect)

            pg.display.update()
            self.clock.tick(self.FPS)

        self.quitGame()