Пример #1
0
def ShowLoading(check_event, color = COLOR_WHITE, min_duration = 0):
	# Show the loading animation in center of the window, until receiving the specified event type.
	font = pygame.font.SysFont("comicsansms", 50, bold = True)
	loading = [font.render(text, True, color) for text in LOADINGS]
	index = 0
	gameDisplay = pygame.display.get_surface()
	rect = loading[-1].get_rect(center = gameDisplay.get_rect().center)
	TaiTimer.CreateTimer(min_duration, USEREVENT)
	timertFired = chkEventOK = False
	myClock = pygame.time.Clock()
	while not timertFired or not chkEventOK:
		for event in pygame.event.get():
			if event.type == QUIT:
				return -1
			if event.type == check_event:
				chkEventOK = True
			if event.type == USEREVENT:
				timertFired = True
		TaiTimer.CheckTimerIteration()
		gameDisplay.fill(COLOR_BLACK, rect)
		gameDisplay.blit(loading[index], rect)
		index = (index + 1) % len(loading)
		pygame.display.update(rect)
		myClock.tick(5)
	# Show the tips on top of the "LOADING..." text.
	n = random.randint(0, len(TIPS) - 1)
	text = 'Tips:\n' + TIPS[n]
	try:
		img = pygame.image.load(IMGS[n]).convert_alpha()
		img = pygame.transform.smoothscale(img, (140, (140 * img.get_height() // img.get_width())))
	except: 
		img = None
	font = pygame.font.SysFont('comicsansms', 20, bold = False)
	TaiMsgBox.MessageBox(text, font = font, width = 600, right_image = img, text_ok = '   OK   ', bd_color = COLOR_LIGHTGRAY, bk_color = COLOR_DARKGRAY, text_color = COLOR_WHITE)
Пример #2
0
def _on_finish_sliding(direction):
    # Setup new timer for sliding in the next time. No need to setup timer if there are less than two back images.
    if len(gBkImgPool) >= 2:
        global gBkImgTimerID
        gBkImgTimerID = TaiTimer.CreateTimer(gBkImgDuration,
                                             _change_backimage,
                                             param=(direction, ))
Пример #3
0
def InitBackImageSlider(duration=4000,
                        fps=60,
                        animationType=TaiImageSlider.ANIMATION_SLIDING):
    global gBkImgPool
    gBkImgPool = sorted(glob.glob('BKIMG/*.jpg'), key=os.path.getmtime)
    if not gBkImgPool:
        return
    global gBkImgPrev, gBkImgCurr
    gBkImgPrev = pygame.image.load(gBkImgPool[-1]).convert()
    if gBkImgPrev.get_size() != (800, 600):
        gBkImgPrev = pygame.transform.smoothscale(gBkImgPrev, (800, 600))
    gBkImgCurr = pygame.image.load(gBkImgPool[0]).convert()
    if gBkImgCurr.get_size() != (800, 600):
        gBkImgCurr = pygame.transform.smoothscale(gBkImgCurr, (800, 600))
    global gBkImgSlider
    gBkImgSlider = TaiImageSlider.ImageSlider(gBkImgPrev,
                                              gBkImgCurr,
                                              fps=fps,
                                              animationType=animationType)
    global gBkImgTimerID, gBkImgDuration
    gBkImgDuration = duration
    # Setup timer for sliding. No need to slide if there are less than two back images.
    if len(gBkImgPool) >= 2:
        gBkImgTimerID = TaiTimer.CreateTimer(gBkImgDuration,
                                             _change_backimage,
                                             param=(1, ))
Пример #4
0
 def _slider_timer_proc(self):
     if self.tick == self.totTick:
         TaiTimer.KillTimer(self.timer_id)
         self.timer_id = -1
         (event, param) = self.callback
         if type(event) is int:
             pygame.event.post(pygame.event.Event(event, param))
         elif callable(event):
             event(*param)
     else:
         self.tick += 1
Пример #5
0
 def Slide(self, dura, direction=1, event=DO_NOTHING, param=None):
     if self.IsSliding():
         self.Stop()
     self.tick = 0
     self.totTick = dura * self.fps // 1000
     self.direction = 1 if direction > 0 else -1
     if type(event) is int and param is None: param = {}
     if callable(event) and param is None: param = ()
     self.callback = (event, param)
     self.timer_id = TaiTimer.CreateTimer(1000 // self.fps,
                                          self._slider_timer_proc,
                                          repeat=True)
Пример #6
0
def BackwardBackImageSliding():
    if not gBkImgSlider:
        return
    TaiTimer.KillTimer(gBkImgTimerID)
    if gBkImgSlider.IsSliding():
        if gBkImgSlider.SetDirection(-1):
            _prepare_sliding(-1)
    else:
        gBkImgSlider.SetImages(gBkImgPrev, gBkImgCurr)
        gBkImgSlider.Slide(1000,
                           direction=-1,
                           event=_on_finish_sliding,
                           param=(1, ))
        _prepare_sliding(-1)
Пример #7
0
def StartPlayChess():
    # Randomly decide who moves first and initialize the game data.
    piece_comp = 0
    while piece_comp == 0:
        piece_comp = random.randint(-1, 1)
    piece_user = -piece_comp
    InitGameBoard()

    # Set up global vars: the actor btn image and flag for locking user input
    UpdateScoreLabel(piece_comp, piece_user)
    gBtnActor.SetImage(gImgActor)

    # Init variables for game states for drawing
    bActorSoundPlayed = False
    piece_winner, movable_list, flip_list = 0, [], []
    actorBalloon, lastMove, highlightColor = None, None, None

    # If computer moves first, lock user input and make computer move first.
    if 1 == piece_comp:
        bLockUserInput = True
        ThreadComputerMove(piece_comp, 500)
    else:
        bLockUserInput = False
        movable_list = Mobility(piece_user)
        lastMove, highlightColor = movable_list[0], COLOR_DARKBLUE

    # Initialie bNeedUpdateScreen flag to True, making the screen paint for the first time.
    bNeedUpdateScreen = True
    # The game loop
    gameDisplay = pygame.display.get_surface()
    myClock = pygame.time.Clock()
    while True:
        # Process events: mouse clicking on reset button or the board, making the computer move, or restart a new game
        for event in pygame.event.get():
            if event.type == QUIT:
                return -1
            if event.type == USEREVENT_MUSIC_END:
                PlayBackgroundMusic()
            if event.type == USEREVENT_NEWGAME:
                bNeedUpdateScreen = True
                if piece_winner != 0:
                    return
                text = 'This chess tournament is still ongoing. Do you really want to abandon this round?'
                img = pygame.image.load(
                    'resources/Othello.png').convert_alpha()
                font = pygame.font.SysFont('comicsansms', 20, bold=False)
                if TaiMsgBox.MessageBox(text,
                                        font=font,
                                        width=500,
                                        bk_image=gImgWoodFrame,
                                        left_image=img,
                                        text_ok='   Yes   ',
                                        text_cancel='   No   ',
                                        bd_color=COLOR_LIGHTGRAY,
                                        text_color=COLOR_WHITE):
                    return
            # Processing mouse events.
            if event.type in (MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION):
                gAllBtns.ProcessMouseEvent(event)
            # In the play-chess mode, perform one-step back for backspace and swap pieces for key R.
            if event.type == KEYUP and not gShowBkImg and not bLockUserInput:
                if event.key == K_BACKSPACE:
                    bNeedUpdateScreen = True
                    lastMove = UndoMove(piece_user)
                    movable_list = Mobility(piece_user)
                    if lastMove < 0:
                        lastMove, highlightColor = movable_list[
                            0], COLOR_DARKBLUE
                    else:
                        highlightColor = COLOR_ORANGE
                    UpdateScoreLabel(piece_comp, piece_user)
                    flip_list, actorBalloon, piece_winner, bActorSoundPlayed = [], None, 0, False
                    gBtnActor.imgUp = gBtnActor.imgDn = gImgActor
                if event.key == K_r:
                    (piece_comp, piece_user) = (piece_user, piece_comp)
                    UpdateScoreLabel(piece_comp, piece_user)
                    movable_list, actorBalloon = [], None
                    bLockUserInput = True
                    ThreadComputerMove(piece_comp, 1000)
                    gAnimThinks.Play()
                    actorBalloon = gAnimThinks
            # Processing arrow keys and space/enter events in play-chess mode.
            if event.type == KEYDOWN and not gShowBkImg and not bLockUserInput:
                bNeedUpdateScreen = True
                if event.key == K_LEFT and lastMove % 8 != 0:
                    lastMove, highlightColor = lastMove - 1, COLOR_DARKBLUE
                if event.key == K_RIGHT and lastMove % 8 != 7:
                    lastMove, highlightColor = lastMove + 1, COLOR_DARKBLUE
                if event.key == K_UP and lastMove >= 8:
                    lastMove, highlightColor = lastMove - 8, COLOR_DARKBLUE
                if event.key == K_DOWN and lastMove < 56:
                    lastMove, highlightColor = lastMove + 8, COLOR_DARKBLUE
                if event.key in (K_SPACE,
                                 K_RETURN) and lastMove in movable_list:
                    pygame.event.post(
                        pygame.event.Event(USEREVENT_USERMOVE,
                                           {'pos': lastMove}))
            # Processing ESC key: send mouse button down and up event to simulate clicking at the actor's button.
            if event.type == KEYDOWN and event.key == K_ESCAPE:
                bNeedUpdateScreen = True
                OnEscapeKeyPressed()
            # Processing left and right key events in show-background-image mode.
            if event.type == KEYDOWN and gShowBkImg:
                if event.key == K_LEFT:
                    bNeedUpdateScreen = True
                    BackwardBackImageSliding()
                elif event.key == K_RIGHT:
                    bNeedUpdateScreen = True
                    ForwardBackImageSliding()
            # Processing mouse click on the chess tile if it is user's turn currently.
            if event.type == MOUSEBUTTONDOWN and not bLockUserInput:
                n = GetUserInput(event.pos)
                if n in movable_list:
                    pygame.event.post(
                        pygame.event.Event(USEREVENT_USERMOVE, {'pos': n}))
            # Processing for user selected an allowable tile and made a move.
            if event.type == USEREVENT_USERMOVE:
                bNeedUpdateScreen = True
                flip_list = UserMakeMove(piece_user, event.pos)
                gPieceSlider.Slide(200, direction=piece_user)
                gSndUserChess.play()
                UpdateScoreLabel(piece_comp, piece_user)
                movable_list, actorBalloon, lastMove, highlightColor = [], None, event.pos, COLOR_BLUE
                piece_winner = CheckGameOver()
                if piece_winner == 0:
                    if len(Mobility(piece_comp)) == 0:
                        movable_list = Mobility(piece_user)
                        actorBalloon = gImgPass
                        TaiTimer.CreateTimer(200, gSndActorPass.play)
                    else:
                        bLockUserInput = True
                        ThreadComputerMove(piece_comp, 1000)
                        gAnimThinks.Play()
                        actorBalloon = gAnimThinks
            # Processing after computer figured out the best move.
            if event.type == USEREVENT_COMPUTERMOVE:
                bNeedUpdateScreen = True
                bLockUserInput = False
                lastMove, highlightColor = event.bestMove, COLOR_ORANGE
                flip_list = CompMakeMove(piece_comp, event.bestMove)
                gPieceSlider.Slide(200, direction=piece_comp)
                gSndActorChess.play()
                UpdateScoreLabel(piece_comp, piece_user)
                gAnimThinks.Stop()
                actorBalloon = None
                movable_list = Mobility(piece_user)
                piece_winner = CheckGameOver()
                if piece_winner == 0 and len(movable_list) == 0:
                    TaiTimer.CreateTimer(200, gSndPlayerPass.play)
                    bLockUserInput = True
                    ThreadComputerMove(piece_comp, 2000)
                    gAnimThinks.Play()
                    actorBalloon = gAnimThinks
        # Processing end of game when piece_winner != 0 and it has not been processed (bActorSoundPlayed not True)
        if piece_winner != 0 and not bActorSoundPlayed:
            bActorSoundPlayed = True
            if piece_winner == piece_comp:
                gSndActorWin.play()
                gBtnActor.SetImage(gImgActorWin)
                actorBalloon = gImgOhYeah
            else:
                gSndActorLose.play()
                gBtnActor.SetImage(gImgActorLose)
                actorBalloon = gImgOhNo
        # Call Tai's timer check iteration function before drawing the display.
        TaiTimer.CheckTimerIteration()
        # Redraw everything and update to the display screen
        bNeedUpdateScreen = bNeedUpdateScreen or BackImageNeedRedraw(
        ) or gPieceSlider.NeedRedraw() or gAnimThinks.NeedRedraw(
        ) or gAllBtns.NeedRedraw()
        if bNeedUpdateScreen:
            bNeedUpdateScreen = False
            DrawBackImageSlider(gameDisplay, (0, 0))
            if not gShowBkImg:
                DrawCoverView(gameDisplay, gCoverView)
                DrawGameBoard(gameDisplay, GetBoard(), movable_list, flip_list,
                              lastMove, highlightColor)
                DrawLevelInCenter(gameDisplay, gLevelItems[gLevelIndex],
                                  Rect(665, 200, 70, 60))
                DrawScore(gameDisplay, piece_comp, piece_user)
            if actorBalloon:
                DrawActorBalloon(gameDisplay, actorBalloon)
            gAllBtns.DrawAll()
            # Update everything to the screen.
            pygame.display.update()
        # Controlling the running speed of this game.
        myClock.tick(FRAME_PER_SECOND)
Пример #8
0
def _computer_move(piece, nNotifyDelay):
    # Computer thinks for the best move. After that, delay some time before notifying main thread,
    # so that it doesn't response too fast at lower game search level.
    n = CompCalcMove(piece, gGameTreeSearchLevel[gLevelIndex])
    TaiTimer.CreateTimer(nNotifyDelay, USEREVENT_COMPUTERMOVE, {'bestMove': n})
    TaiTimer.CreateTimer(nNotifyDelay, gBtnReset.Enable, (True, ))
Пример #9
0
 def Stop(self):
     if self.IsSliding():
         TaiTimer.KillTimer(self.timer_id)
         self.timer_id = -1
Пример #10
0
	def Pause(self):
		if self.IsPlaying():
			TaiTimer.KillTimer(self.timer_id)
			self.timer_id = -1
Пример #11
0
	def Stop(self):
		if self.IsPlaying():
			TaiTimer.KillTimer(self.timer_id)
			self.timer_id = -1
			self.index = 0
			self.lastDrawIndex = self.index
Пример #12
0
	def Play(self, event = DO_NOTHING, param = None):
		self.Stop()
		if type(event) is int and param is None: param = {}
		if callable(event) and param is None: param = ()
		self.callback = (event, param)
		self.timer_id = TaiTimer.CreateTimer(self.dura, self._anim_timer_proc, repeat = True)