Esempio n. 1
0
def main():
    game.init()

    while game.is_running:
        game.update()

    game.close()
Esempio n. 2
0
    def expand(self, v, game):
        """Choose un-tried action and expand tree.
        
        Args:
            v: parent node which has un-visited child node.
            game: game state which corresponds to passed node v

        Returns:
            child_node: insrance of new created node whose parent is v
        """
        act_index = 0
        while True:
            act_index = v.children.index(-1)    # get index of untried action
            v.unvisited -= 1

            if not game.is_legal(act_index):
                v.children[act_index] = -2  # -2 indicates this action is illegal

                # if all unvisited nodes are illegal one, 
                # then go tree_policy process and descend the tree again.

                if v.unvisited == 0: return self.tree_policy(v, game)
            else:
                break

        # add new expanded node to the tree
        child_node = Node(game.act_num)
        child_node.parent = v
        is_terminal, score = game.is_terminal(self.ME, act_index)
        if is_terminal:
            child_node.is_terminal = True
            child_node.val = score
        game.update(act_index)
        v.children[act_index] = child_node
        return child_node
Esempio n. 3
0
        def jumpleft_player(self,donkey,fireballs,game,princess): # 4step 
		for i in range(1,3):
		        game.resetperson(self)
			if game.checkwall(self.getxcordinate()+1,self.getycordinate()+1):
				self.checkair(game)
				break	
		        self.setxcordinate(self.getxcordinate()+1)
		        self.setycordinate(self.getycordinate()+1)
		        game.update(donkey,fireballs,self,princess)
		        game.setperson(self)
		        game.printboard(self)
		        time.sleep(0.1)
                game.resetperson(self)
		if game.checkwall(self.getxcordinate()-1,self.getycordinate()+1):
			self.checkair(game)
			game.update(donkey,fireballs,self,princess)
			return 
                self.setxcordinate(self.getxcordinate()-1)
                self.setycordinate(self.getycordinate()+1)
                game.update(donkey,fireballs,self,princess)
                game.setperson(self)
                game.printboard(self)
                time.sleep(0.1)
                game.resetperson(self)
		if game.checkwall(self.getxcordinate()-1,self.getycordinate()-1):
			self.checkair(game)
			game.update(donkey,fireballs,self,princess)
			return
                self.setxcordinate(self.getxcordinate()-1)
                self.setycordinate(self.getycordinate()+1)
		self.checkair(game)
                game.update(donkey,fireballs,self,princess)
                game.setperson(self)
Esempio n. 4
0
def user_play(game):
    key = KEY_RIGHT  # init key
    prevKey = key
    while True:
        key_arr = read_stdin()
        if len(key_arr) == 0:
            key = prevKey
        elif len(key_arr) == 3:
            if key_arr[2] == 'A':
                key = KEY_UP
            if key_arr[2] == 'B':
                key = KEY_DOWN
            if key_arr[2] == 'C':
                key = KEY_RIGHT
            if key_arr[2] == 'D':
                key = KEY_LEFT
        prevKey = key
        game.move_snake(key)
        game.update()
        game.render()
        print "render_dxy_state"
        print "----------------"
        game.render_dxy_state()
        print "----------------"

        if game.done:
            break

        time.sleep(0.25)
Esempio n. 5
0
def main():

    while True:
        game.handle_inputs()

        game.update()

        game.render()
Esempio n. 6
0
def run_game(): 
	print (welcome_message) 
	print ("") 
	print (instructions)
	choice=input("Pick H or T\n")
	while choice.upper() not in ['H', 'T']:
		 choice=input("Invalid input. Please pick H or T\n")

	#flip a coin 
	i=random.randint(0,1) 
	winner='HT'[i] 
	if winner==choice:
		turn='player'
		print ("Congratulations! You go first :)")
	else:
		turn='ai' 
		print ("Sorry, you go second :(")
	
	#game starts 
	game_ongoing=True 
	game_state = game.GameState(turn) #create a new game 

	while game_ongoing:


		if game_state.getTurn()=='ai': #AI's Turn 
			ai_status=ai.play(game_state)
			if ai_status==game.PLAYER_LOST: 
				print ("AI WON!")
				game_ongoing=False 
			if ai_status==game.TIE:
				game_ongoing=False
				print ("TIE!") 

		else: #Player Turn  
			game_state.printBoard() #display board for player 

			move=input("Please pick a tile\n") 
			status=game.update(game_state, move) 

			while status==game.NOT_VALID_MOVE: 
				move=input("Invalid tile. Please pick a tile that isn't occupied\n") 
				status=game.update(game_state, move) 

			#picked a valid tile, game updated accordingly 
			if status==game.PLAYER_WON:
				print ("CONGRATS! YOU WON!")
				game_ongoing=False 

			if status==game.TIE:
				game_ongong=False 
				print ("TIE!")

			
	game_state.printBoard() #display board for player 
Esempio n. 7
0
File: main.py Progetto: tvhong/one
def run():
    global movingLeft,movingRight,running,lastMove
    while True:
        handleGlobalEvents()
        
        if running:
            if game.checkGameEnd():
                # TODO: show scores, restart, give candies, whatever
                return

            handleEvents()
            
            # update game state
            lines = game.update()
            lineEaten(lines)
            
            projectPiece = game.getProjection()

            # drawing
            graphics.reset()
            graphics.drawStatus(game.score,game.level)
            graphics.drawNextPiece(game.getNextPiece())
            graphics.drawBoard()
            if projectPiece:
                graphics.drawProjectPiece(projectPiece)
            for piece in game.getPieces():
                graphics.drawPiece(piece)
            if lines != []:
                graphics.drawLineEffect(lines)
            pygame.display.update()

        FPSCLOCK.tick(FPS)
Esempio n. 8
0
def main():
    global surface,FPSCLOCK
    pygame.init()
    surface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
    FPSCLOCK = pygame.time.Clock()
    graphics.init(surface)
    board = []
    for i in range(BOARDROWS):
        board.append([BLANK]*BOARDCOLS)
    assert len(board) == BOARDROWS
    for i in range(BOARDROWS):
        assert len(board[i]) == BOARDCOLS
    board[0][0] = TYPE_O
    board[0][1] = TYPE_O
    board[1][0] = TYPE_O
    board[1][1] = TYPE_O

    board[5][5] = TYPE_I
    board[6][5] = TYPE_I
    board[7][5] = TYPE_I
    board[8][5] = TYPE_I

    game.start()
    
    while (True):
        if game.checkGameEnd():
            print 'the game has ended!!'
            FPSCLOCK.tick(FPS)
            continue
        for event in pygame.event.get(QUIT):
            terminate()
        for y in range(BOARDROWS):
            for x in range(BOARDCOLS):
                print game.board[y][x],
            print ''
            
        print 'number of pieces: ',len(game.getPieces())
        #graphics.drawBoard(board)
        graphics.reset()
        for piece in game.getPieces():
            # print 'drawing a piece!!!'
            print piece
            graphics.drawPiece(piece)
        graphics.drawStatus(1000,20)
        pygame.display.update()
        game.update()
        FPSCLOCK.tick(FPS)
Esempio n. 9
0
def run():
    '''Holds the main loop.'''

    while running:
        # Reading inputs from the user
        handle_events()

        # Processing next step
        if game.active: game.update()
        if menu.active: menu.update()

        # Drawing everything
        if game.visible: game.draw()
        if menu.active: menu.draw()

        # Waiting in order to mainting fps.
        clock.tick(fps)
        pygame.display.flip()
Esempio n. 10
0
    def tree_policy(self, v, game):
        """Descend tree until un-visited node is found.

        Descends the tree with updating state of passed game object
        until un-visited node(action) is found.
        If v is terminal state, then just return v.

        Args:
            v: start node to descend the tree.(mostly root node)
            game: game object which corresponds to the state of v
        
        Returns:
            v: the node which has un-visited child node or terminal node.
        """
        while True:
            if v.is_terminal: return v
            if v.unvisited != 0: return self.expand(v, game)
            act_index = self.best_child(v, self.C)
            v = v.children[act_index]
            game.update(act_index)
        return v
Esempio n. 11
0
def update():
    game.update()
    graphics.update()
    controls.clear()
Esempio n. 12
0
def main_loop():
    pygame.init()
    pygame.display.set_caption(game.NAME)
    clock = pygame.time.Clock()

    background = pygame.Surface(game.screen.get_size()).convert()
    background.fill(pygame.Color(0, 0, 0))

    input_queue = multiprocessing.Queue()

    while True:
        # Choose player mode
        options = ["AI Demo", "Two players", "Three players", "Four players"]
        selection = Menu(options).show()
        if selection is False:
            return
        else:
            game.num_players = selection + 1

        # Choose level
        levels = level.get_levels()
        selection = Menu([lvl.name for lvl in levels]).show()
        if selection is False:
            continue
        else:
            game.level = levels[selection]

            # If single player, add an AI player
            if game.num_players == 1:
                game.num_players = 4
                game.init_level()

                ai_engines = []
                ai_processes = []
                ai_engines.append(ai_classes[0])
                ai_engines.append(ai_classes[1])
                ai_engines.append(ai_classes[2])
                ai_engines.append(ai_classes[1])
                shared_apples = multiprocessing.Array(process.GameObject,
                        list((apple.x, apple.y) for apple in game.apples))
                shared_players = multiprocessing.Array(process.MovableGameObject,
                        list(((player.x, player.y), player.direction)
                            for player in game.players))
                ai_processes = [_class(player_index=i, board=game.shared_board, players=shared_players, apples=shared_apples, player=game.players[i], args=(input_queue,)) for i, _class in enumerate(ai_engines)]
                # Load threaded AI
                if game.use_multiprocessing:
                    map(lambda proc: proc.start(), ai_processes)
                game.players[1].name = 'The Spirit of AI'
                game.players[1].name = 'Bebe Bot'
                game.players[2].name = 'The Will of AI'
                game.players[3].name = 'Bot Choy'
            else:
                game.init_level()

        # Start game loop
        return_to_menu = False
        game_status = None
        ai_frame_count = 1
        start_time = time.time()

        while not return_to_menu:
            clock.tick(game.frames_per_second)

            while True:
                # Process key presses from AI threads.
                # Pulls values from input queue, creates pygame Events, and
                # submits to event queue.
                try:
                    pygame.event.post(pygame.event.Event(KEYDOWN, {'key':
                        input_queue.get_nowait(),}))
                except Queue.Empty, qe:
                    break

            # Process non multiprocessing AI moves
            if not game.use_multiprocessing:
                # map(lambda proc: proc.execute(), ai_processes)
                for proc in ai_processes:
                    if not isinstance(proc, JasonAI):
                        proc.execute()

                if ai_frame_count < 3:
                    ai_frame_count += 1
                else:
                    for proc in ai_processes:
                        if isinstance(proc, JasonAI):
                            proc.execute()
                    ai_frame_count = 1

            # Get input
            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    return_to_menu = True
                    # Shutdown all AI processes
                    if game.use_multiprocessing:
                        map(lambda proc: proc.shutdown(), ai_processes)
                    break

                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        game.players[0].grow = True
                    elif event.key == K_RETURN and game_status == "win":
                        game.init_level()
                        game_status = None
                        continue
                    elif event.key in game.player_controls[0]:
                        game.players[0].set_direction(game.player_controls[0].index(event.key))
                    elif event.key in game.player_controls[1] and game.num_players > 1:
                        game.players[1].set_direction(game.player_controls[1].index(event.key))
                    elif event.key in game.player_controls[2] and game.num_players > 2:
                        game.players[2].set_direction(game.player_controls[2].index(event.key))
                    elif event.key in game.player_controls[3] and game.num_players > 3:
                        game.players[3].set_direction(game.player_controls[3].index(event.key))

            # Update effects
            for effect in game.effects:
                effect.update()

            # Update game
            game.update()

            # Update shared board
            for i, v in enumerate([(apple.x, apple.y) for apple in game.apples]):
                shared_apples[i] = v

            for i, v in enumerate([((player.x, player.y), player.direction, player.get_length()) for player in game.players]):
                shared_players[i] = v

            # Draw the screen
            game.screen.blit(background, (0, 0))
            game.draw()
            for effect in game.effects:
                effect.draw()

            # Draw scoreboard
            score_icon_size = 30
            score_width = 55
            score_margin = 120
            all_score_widths = game.num_players * score_width + (game.num_players-1) * score_margin
            score_x = (game.WINDOW_WIDTH - all_score_widths)/2
            score_y = game.WINDOW_HEIGHT - game.SCOREBOARD_HEIGHT + (game.SCOREBOARD_HEIGHT-score_icon_size)/2
            for i, player in enumerate(game.players):
                icon = pygame.Rect(score_x + i*(score_width+score_margin), score_y, score_icon_size, score_icon_size)
                text = str(len(player.kills))

                score = pygame.font.SysFont('impact', 30).render(text, 1, pygame.Color("white"))
                score_pos = score.get_rect(left = icon.right + 10, centery = icon.centery)

                game.screen.blit(score, score_pos)
                pygame.draw.rect(game.screen, player.color, icon)

            runtime = int(time.time() - start_time)
            runtime_min = runtime // 60
            runtime_sec = runtime % 60
            if runtime_min < 10:
                runtime_min = "0" + str(runtime_min)
            if runtime_sec < 10:
                runtime_sec = "0" + str(runtime_sec)
            runtime_text = "%s : %s" % (runtime_min, runtime_sec)

            time_text = pygame.font.SysFont('impact', 24).render(runtime_text, 1, pygame.Color("white"))
            time_pos = time_text.get_rect(x = game.WINDOW_WIDTH - 95, y = game.WINDOW_HEIGHT - 54)
            game.screen.blit(time_text, time_pos)

            # Check for the win condition
            winners = filter(lambda p: len(p.kills) >= game.level.kills_to_win, game.players)
            if winners:
                game_status = 'win'

                # Check for ties
                least_deaths = min(len(w.deaths) for w in winners)
                winners = filter(lambda w: len(w.deaths) == least_deaths, winners)
                if len(winners) > 1:
                    title = pygame.font.SysFont("impact", 100).render("Draw!", 1, pygame.Color("white"))
                else:
                    title = pygame.font.SysFont("impact", 100).render(winners[0].name + " wins!", 1, pygame.Color("white"))

                # Draw title
                title_pos = title.get_rect(centerx = game.WINDOW_WIDTH/2, centery = 200)
                game.screen.blit(title, title_pos)

                # Draw subtitle
                subtext = pygame.font.SysFont("verdana", 15).render("Press [ENTER] to play again, or [ESC] to return to the main menu.", 1, pygame.Color("white"))
                subtext_pos = subtext.get_rect(centerx = game.WINDOW_WIDTH/2, y = title_pos.bottom + 10)
                game.screen.blit(subtext, subtext_pos)

                # Draw summary
                header_width = 200
                header_height = 30
                header_margin = 0
                header_x = (game.WINDOW_WIDTH - header_width * game.num_players) / 2
                header_y = subtext_pos.bottom + 50
                cell_margin = 20

                for i, player in enumerate(game.players):
                    # Draw header box
                    header = pygame.Rect(header_x + (header_width+header_margin)*i, header_y, header_width, header_height)
                    pygame.draw.rect(game.screen, player.color, header)

                    # Draw header text
                    text = pygame.font.SysFont("arial", 16, bold=True).render(player.name, 1, pygame.Color("white"))
                    text_pos = text.get_rect(centerx = header.centerx, centery = header.centery)
                    game.screen.blit(text, text_pos)

                    # Draw death summary
                    s = "Total deaths: " + str(len(player.deaths))
                    death_summary_font = pygame.font.SysFont("arial", 14, bold=True).render(s, 1, pygame.Color("white"))
                    death_summary_pos = death_summary_font.get_rect(centerx = header.centerx, centery = header.bottom + cell_margin)
                    game.screen.blit(death_summary_font, death_summary_pos)

                    strings = []
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.SnakePart) and c.player is not player, player.deaths))) + " by collision")
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.Missile) and c.player is not player, player.deaths))) + " by missile")
                    strings.append(str(len(filter(lambda c: isinstance(c, game_objects.Wall), player.deaths))) + " by wall")
                    strings.append(str(len(filter(lambda c: (isinstance(c, game_objects.Missile) and c.player is player) or (isinstance(c, game_objects.SnakePart) and c.player is player), player.deaths))) + " by suicide")

                    for i, s in enumerate(strings):
                        text = pygame.font.SysFont("arial", 13).render(s, 1, pygame.Color("white"))
                        text_pos = text.get_rect(centerx = header.centerx, centery = death_summary_pos.bottom + (i+1)*cell_margin)
                        game.screen.blit(text, text_pos)

                    # Draw kill summary
                    s = "Total kills: " + str(len(player.kills))
                    kill_summary_font = pygame.font.SysFont("arial", 14, bold=True).render(s, 1, pygame.Color("white"))
                    kill_summary_pos = kill_summary_font.get_rect(centerx = header.centerx, centery = header.bottom + cell_margin + 130)
                    game.screen.blit(kill_summary_font, kill_summary_pos)

                    for i, opponent in enumerate(player.kills):
                        text = pygame.font.SysFont("arial", 13).render(opponent.name, 1, opponent.color)
                        text_pos = text.get_rect(centerx = header.centerx, centery = kill_summary_pos.bottom + (i+1)*cell_margin)
                        game.screen.blit(text, text_pos)


            # Display!
            pygame.display.flip()
Esempio n. 13
0
import pygame, game, sys

# Game initialization
game.init()
game.load_screen(0)

clock = pygame.time.Clock()

# Gameloop
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()

	game.update()
	game.draw()

	pygame.display.flip()

	clock.tick(30)
Esempio n. 14
0
import pygame
import game

pygame.init()

pygame.display.set_caption('R')
clock = pygame.time.Clock()
fps = 60

gameDisp = pygame.display.set_mode(
    (800, 600), pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)


def quitfunc():
    pygame.quit()
    quit()


while True:

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

    game.update()
    game.draw()

    pygame.display.update()
    clock.tick(fps)

pygame.quit()
Esempio n. 15
0
def update(dt):
    for el in update_list:
        el.update(dt)
    
    game.update()
Esempio n. 16
0
def update():
    game.update()
    graphics.update()
Esempio n. 17
0
        if event.type == pygame.QUIT:
            running = False
        # CAMERA SCROLLING
        if event.type == pygame.MOUSEMOTION:
            x, y = event.pos
            if x > var.SCREEN_WIDTH - var.SCROLLING_CONST:
                var.scroling_X_Inc = True
            else:
                var.scroling_X_Inc = False
            if x < var.SCROLLING_CONST:
                var.scroling_X_Dec = True
            else:
                var.scroling_X_Dec = False
            if y > var.SCREEN_HEIGHT - var.SCROLLING_CONST:
                var.scroling_Y_Inc = True
            else:
                var.scroling_Y_Inc = False
            if y < var.SCROLLING_CONST:
                var.scroling_Y_Dec = True
            else:
                var.scroling_Y_Dec = False

        # INPUT
        InputManager.instance.event_handler(event)

    # GAME UPDATE
    game.update(screen, frame_time / 1000)
    # DISPLAY UPDATE
    pygame.display.update()
    clock.tick(60)
Esempio n. 18
0
# Game initialization hier werden alle objekte erstellt und alle wichtigen variablen erstellt

# todo options fahrzeug wählen dafür muss ich eine neue class options erstellen und einenen neuen status
game.init()
menu = menu.Menu()
options = options.Options()

clock = pygame.time.Clock()


# Gameloop
while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			sys.exit()
	if menu.status == 0:
		menu.update()
		menu.draw()
		options.waitselect = 10
	elif menu.status == 1:
		menu.status = game.update()
		game.draw()
	elif menu.status == 2:
		menu.status = options.update()
		options.draw()
		menu.waitselect = 10

	pygame.display.flip()

	clock.tick(30)
Esempio n. 19
0
    def checkCommandsGame(self, session, chat_id, msg):
        if session.userIsGaming(msg['from']['id'], chat_id) == 1:

            game = self.getGame(chat_id)

            #controllo se il tizio che ha lanciato l'attacco è il corrente attaccante,controllo se il suo avversario corrisponde
            pprint(game)

            #controllo se ha un evocazione troll
            if game.rightTurnAttack(
                    msg['from']['id']) == 1 and game.trollEffect(
                        msg['from']['id']) == 1:
                self.bot.sendMessage(
                    msg["chat"]["id"],
                    game.gamer[game.attackTurn].name + " perdi turno ! ")
                game.newRound()
                game.currentDefensor = 0

            #ATTACCO- al termine imposto il turno DEFENSE e l'id del currentDefensor

            elif game.checkResultTargetAttack(msg['from']['id'],
                                              msg['text']) == 1:

                pprint("SONO IN ATTACK")
                #game.attack(msg['from']['id'])
                att = 0
                #doppio turno
                if game.currentEffect == 2:
                    att = self.atk.doubleAttack(game.gamer,
                                                game.currentDefensor.name)
                    game.currentEffect = 0
                else:
                    att = self.atk.attack(game.gamer,
                                          game.currentDefensor.name)
                #è troll
                if att == 1:
                    self.bot.sendMessage(
                        game.gamer[1],
                        "Il troll non perdona , hai perso! 🤡🤡 ")
                    player = game.getPlayer(msg['from']['id'])
                    game.updatePoint(player, self.atk.pointAttack)
                    game.newRound()
                else:
                    self.bot.sendMessage(
                        game.gamer[1], game.currentDefensor.name +
                        " devi difenderti! 🛡🛡")
                    game.currentIndexGifAttack = self.atk.pointAttack
                    game.currentTurn = 'Defense'
                game.effectUsed = 0

            elif msg['text'] == costant.kboardAttack or msg[
                    'text'] in costant.evocation:
                if game.rightTurnAttack(msg['from']['id']) == 1:
                    #game.prepareAttack(msg['from']['id'])

                    #devo passare il player e il bot
                    player = game.getPlayer(msg['from']['id'])
                    self.atk.prepareAttack(player, game.gamer)
                else:
                    self.bot.sendSticker(msg["chat"]["id"],
                                         sticker=costant.oak)

            #DIFESA-alla fine della difesa imposto il turno ATTACK e setto l'id del prossimo gamer
            elif msg['text'] == costant.kboardDefense:
                if game.rightTurnDefense(msg['from']['id']) == 1:
                    dfs = defense.Defense(self.bot)
                    defensePoint = dfs.defense(msg["chat"]["id"])
                    #attacco 2x
                    if game.currentEffect == 1:
                        game.currentIndexGifAttack = game.currentIndexGifAttack * 2
                        game.currentEffect = 0
                    if game.currentEffect == 3:
                        defensePoint *= 2
                        self.bot.sendMessage(
                            msg["chat"]["id"],
                            game.gamer[game.attackTurn].name +
                            " difesa per 2 ! ")
                        game.currentEffect = 0
                    if game.currentEffect == 4:
                        self.bot.sendMessage(
                            msg["chat"]["id"],
                            game.gamer[game.attackTurn].name +
                            " sei il RE, non puoi essere attaccato ! ")
                        game.newRound()
                        game.currentEffect = 0
                        game.currentDefensor = 0
                    else:
                        game.computePoint(defensePoint)

            #PREGHIERA
            elif msg['text'] == costant.kboardPrayer:
                game.prayer()

            #EVOCAZIONE
            elif msg['text'] == costant.kboardEvocation:
                if game.rightTurnEvocation(msg['from']['id']) == 1:
                    evc = evocation.Evocation(self.bot)
                    effect = evc.evocation(msg["chat"]["id"])
                    if effect == 1:
                        game.setEvocation(evc.gifEv, msg["chat"]["id"])
                        evc.gifEv = 0
                    else:
                        game.setTrollEvocation(evc.gifTroll, msg["chat"]["id"])
                        evc.gifTroll = 0
                    game.effectOn = 0
                    game.newRound()
                else:
                    self.bot.sendSticker(msg["chat"]["id"],
                                         sticker=costant.oak)

            #USA EFFETTO
            elif msg['text'] == costant.kboardEffect:
                if game.rightTurnAttack(msg['from']['id']) == 1:
                    pprint("sto inright turno attack")
                    evc = game.showEffects(msg["chat"]["id"])
                    if evc == -1:
                        self.bot.sendSticker(msg["chat"]["id"],
                                             sticker=costant.oak)

                else:
                    self.bot.sendSticker(msg["chat"]["id"],
                                         sticker=costant.oak)

            #EFFETTO SCELTO
            elif game.rightTurnAttack(
                    msg['from']['id']) == 1 and game.effectUsed == 0:
                if self.checkMsgEffectAtt(msg['text']) == 1:
                    pprint("sono in effetto scelto")
                    game.useAttEffect(msg['text'], msg['from']['id'])
                    #decrementare indice effetti
                    #impotare game.effectUsed a 1 a inizio effetto
                    #rimostro la tastiera per attaccare inviando il messaggio
                    #impostare game.effectUsed a 0 quando finisce l'attacco
                    #implemento l'effetto nell'attack
                    #impostare current effect a 0 quando finisce l'attacco

            #INDIETRO
            if msg['text'] == costant.back:
                if msg['from']['id'] != game.gamer[game.attackTurn].id:
                    self.atk.back(game.gamer[game.attackTurn],
                                  msg["chat"]["id"])
                else:
                    self.bot.sendSticker(msg["chat"]["id"],
                                         sticker=costant.oak)
                    self.bot.sendMessage(
                        msg["chat"]["id"], game.gamer[game.attackTurn].name +
                        " attendi che termini la fase di attacco ! ")

            if msg['text'].lower() == costant.kboardEscape:
                """1 se ho eliminato solo 1 utente, -1 se il gioco viene chiuso"""
                string = session.close(chat_id, msg)
                pprint(string)
                if string == "una chiusura":
                    game.update(msg)
                    session.removeGamerFromChatIdAndUser(msg, chat_id)

                elif string == "due chiusure":
                    self.game.remove(game)
                    session.removeGroupFromChatId(chat_id)
Esempio n. 20
0
    if (running == 1):
        #--------------------------
        #Render Background
        screen.blit(background,topleft)
        #--------------------------
        #Scanline
        screen.blit(scanlines.update(),topleft)
        #--------------------------

        #States
        #----Menu and Text State
        if menu.isActive():
            screen.blit(menu.update(),topleft)
        #----Game State
        elif game.isActive():
            screen.blit(game.update(),topleft)
        #--------------------------
        #Final Rendering
        screen.blit(resources.getForeground(),topleft)
        pygame.display.flip()
        #--------------------------
        #Frame Control
        clock.tick(framerate)
    else:
        pygame.time.wait(500)
pygame.quit()

try:
    sys.exit("Good night")
except SystemExit:
    # Cleanup
Esempio n. 21
0
p_rect = pygame.Rect((0, 0), (p_w, p_h))
p_col_fill = (64, 64, 196, 127)
p_col_stroke = (128, 128, 196, 127)

panel = gui.Panel(0,
                  0,
                  rect=p_rect,
                  fill=p_col_fill,
                  stroke=p_col_stroke,
                  stroke_size=3)
text = gui.Text(0,
                0,
                parent=panel,
                padding=4,
                text="Text",
                color=(162, 162, 162),
                size=32)
gui_group = pygame.sprite.LayeredDirty(panel, text)

camera = camera.Camera(player, SCREEN_WIDTH * TILE_SIZE,
                       SCREEN_HEIGHT * TILE_SIZE, MAP_WIDTH * TILE_SIZE,
                       MAP_HEIGHT * TILE_SIZE)

while 1:
    game.update(player, camera.x, camera.y, update_group, object_group)
    text.set_text('HP: ' + str(player.components['fighter'].hp) + '/' +\
                  str(player.components['fighter'].max_hp))
    # render the screen
    camera.update()
    renderer.update(update_group, gui_group)
Esempio n. 22
0
delta_time = 0
clock = pygame.time.Clock()

t = pygame.Surface((width,height))
t.set_alpha(180)
t.fill((0,0,0))

image = pygame.image.load("img/miljo.png")
image = pygame.transform.scale(image,(width, height))

while(1):
    delta_time = float(clock.tick(400))

    for event in pygame.event.get():
        if(event.type == pygame.QUIT):
            sys.exit()


    game.input(delta_time)

    game.update(delta_time)

    screen.blit(image,(0,0,width,height))


    game.render(screen)

    screen.blit(t, (0,0))

    pygame.display.flip()
Esempio n. 23
0
objs = rl.map.place_objects(map, 0, entity.Monster, 2, 4, "monster", creatures_anim_sheet, 384, True, player)

objs = [player] + objs
object_group = pygame.sprite.Group(*objs)
objs2 = [tilemap, player] + objs
update_group = pygame.sprite.LayeredDirty(*objs2)

# Gui

ts = TILE_SIZE * SCALE
p_w = SCREEN_WIDTH * ts
p_h = ts
p_rect = pygame.Rect((0, 0), (p_w, p_h))
p_col_fill = (64, 64, 196, 127)
p_col_stroke = (128, 128, 196, 127)

panel = gui.Panel(0, 0, rect=p_rect, fill=p_col_fill, stroke=p_col_stroke, stroke_size=3)
text = gui.Text(0, 0, parent=panel, padding=4, text="Text", color=(162, 162, 162), size=32)
gui_group = pygame.sprite.LayeredDirty(panel, text)

camera = camera.Camera(player, SCREEN_WIDTH * TILE_SIZE, SCREEN_HEIGHT * TILE_SIZE,
                MAP_WIDTH * TILE_SIZE, MAP_HEIGHT * TILE_SIZE)

while 1:
    game.update(player, camera.x, camera.y, update_group, object_group)
    text.set_text('HP: ' + str(player.components['fighter'].hp) + '/' +\
                  str(player.components['fighter'].max_hp))    
    # render the screen
    camera.update()
    renderer.update(update_group, gui_group)
Esempio n. 24
0
        if (event.type == pygame.KEYUP):
            if (event.key < 300):
                if (inputControl.keys[event.key]):
                    inputControl.keyTap[event.key] = True
                inputControl.keys[event.key] = False

    screen.fill(setup.black)

    if stage == Menu:
        stage = gui.menuSetup(screen)
    elif stage == Game:
        if (state == 0):
            #Create a new game state
            state = game.State()
            print(state.startFlag)
        stage = game.update(screen, state)

    if (stage != Game):
        state = 0

    #If we've reached stage -1, quit
    done = done or stage == -1

    pygame.display.flip()
    pygame.display.update()

pygame.display.quit()
pygame.quit()
print("Done")