Ejemplo n.º 1
0
def process_frame(left_frame, right_frame, ir_frame):

    print('\n\n------------- New Frame -------------')
    global detected_humans
    global human_id_counter
    frame_1 = left_frame
    frame_2 = right_frame
    # detect humans in the frame
    boxes_1 = human_detection.detection(left_frame, right_frame, ir_frame,
                                        args['disparity'])

    print('positions where we have detected humans in the frame: {}'.format(
        boxes_1))

    # track the humans

    # for each entry in the detector compare the detected postion with the postition of the humans that are already in the list
    # if there is no human in the range, create a new human and add it to the list
    if detected_humans:
        new_occurances = tracking.detect_new_occurance_and_update_positions(
            frame_1, threshold_tracking_deviating, boxes_1, detected_humans)
        for new_block in new_occurances:
            # calculate the histogram for the newly detected human
            image_in_bounding_box = frame_1[
                int(new_block[1]):int(new_block[1]) + int(new_block[3]),
                int(new_block[0]):int(new_block[0]) + int(new_block[2])]
            hist = histogram.create_histogram(image_in_bounding_box)

            detected_humans.append(
                human.Human(human_id_counter, new_block, hist))
            human_id_counter = human_id_counter + 1
    else:
        for new_block in boxes_1:
            # calculate the histogram for the newly detected human
            image_in_bounding_box = frame_1[
                int(new_block[1]):int(new_block[1]) + int(new_block[3]),
                int(new_block[0]):int(new_block[0]) + int(new_block[2])]
            hist = histogram.create_histogram(image_in_bounding_box)

            detected_humans.append(
                human.Human(human_id_counter, new_block, hist))
            human_id_counter = human_id_counter + 1
    # remove all humans from the list that have a non_detected counter higher than the threshold
    detected_humans = list(
        filter(
            lambda x: x.get_untracked_frame_counter() <
            threshold_tracking_undetected_frames, detected_humans))
    print(
        'our human list after filtering out all humans that were not detected for a few frames: {}'
        .format(detected_humans))

    # update fps
    fps.update()

    if args['display']:
        if ir_frame is not None:
            display.display_with_humans([frame_1, ir_frame],
                                        [detected_humans, []])
        else:
            display.display_with_humans([frame_1], [detected_humans])
Ejemplo n.º 2
0
def main():
    params = set_params()
    openpose = OpenPose(params)
    
    #Chose Camera, 0=front, 1=side camera
    frontCam = camera.WebcamVideoStream(0).start()
    sideCam = camera.WebcamVideoStream(1).start()
    
    while 1:
        
        #Press q key, then Break Loop
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
        #Image Shot from Camera, ret=True or False(Success or Fail), img=sigle frame
        img_0 = frontCam.read()
        img_1 = sideCam.read()
        
        #Input Image into OpenPose, Output Keypoints and Keypoint Image
        frontPoints, frontImage = openpose.forward(img_0, True)
        sidePoints, sideImage = openpose.forward(img_1, True)
        
        #Show Image
        cv2.imshow('Cam0 Human Pose Estimation', frontImage)
        cv2.imshow('Cam1 Human Pose Estimation', sideImage)
        
        if len(frontPoints)<=0 or len(sidePoints)<=0:
            print('No Human Detect!')
            continue
        
        frontView = human.Human(frontPoints)
        sideView = human.Human(sidePoints)

        
        try:
            print("1 m_WristsAndAnkles:", frontView.measureWristsAndAnkles())
            print("2 m_Shoulders And Anless Parallel:", frontView.measureShouldersAndAnleesParallel())
            print("3 m_Shoulder And Ankles:", frontView.measureShouldersAndAnkles())
            print('\n')
        except ZeroDivisionError as e:
            print("ZeroDivisionError:", e)
            continue

    #Release Camera
    frontCam.stop()
    sideCam.stop()
    
    #Close All OpenCV Windows
    cv2.destroyAllWindows()
Ejemplo n.º 3
0
def main():
    params = set_params()
    openpose = OpenPose(params)

    #Chose Camera, 0=front, 1=side camera
    frontCam = initCamera(0)
    sideCam = initCamera(1)

    while 1:

        #Press q key, then Break Loop
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        #Image Shot from Camera, ret=True or False(Success or Fail), img=sigle frame
        ret0, img_0 = frontCam.read()
        ret1, img_1 = sideCam.read()

        #Input Image into OpenPose, Output Keypoints and Keypoint Image
        frontPoints, frontImage = openpose.forward(img_0, True)
        sidePoints, sideImage = openpose.forward(img_1, True)

        #Show Image
        cv2.imshow('Cam0 Human Pose Estimation', frontImage)
        cv2.imshow('Cam1 Human Pose Estimation', sideImage)

        if len(frontPoints) <= 0 or len(sidePoints) <= 0:
            print('No Human Detect!')
            continue

        frontView = human.Human(frontPoints)
        sideView = human.Human(sidePoints)

        ###
        #
        #put detect in here.
        #ex.

        print(frontView.test())

        ###

    #Release Camera
    frontCam.release()
    sideCam.release()

    #Close All OpenCV Windows
    cv2.destroyAllWindows()
Ejemplo n.º 4
0
 def born(self, socium):
     newborn = human.Human(socium,
                           self.biological_parents,
                           gender=self.gender,
                           age_int=0)
     self.genes.transit(newborn)
     return newborn
Ejemplo n.º 5
0
    def loadHuman(self):

        self.progress(0.1)
        #hairObj = hair.loadHairsFile(self.scene3d, path="./data/hairs/default", update = False)
        #self.scene3d.clear(hairObj)
        self.selectedHuman = self.addObject(
            human.Human(files3d.loadMesh("data/3dobjs/base.obj")))
Ejemplo n.º 6
0
    def loadHuman(self):
        self.progress(0.1)

        # Set a lower than default MAX_FACES value because we know the human has a good topology (will make it a little faster)
        # (we do not lower the global limit because that would limit the selection of meshes that MH would accept too much)
        mesh = files3d.loadMesh(mh.getSysDataPath("3dobjs/base.obj"), maxFaces = 5)
        humanModel = human.Human(mesh)
        self.selectedHuman = self.addObject(humanModel)
Ejemplo n.º 7
0
def get_players():
    os.system('cls')  # on windows        
    while True:
        print('--------------------------------------------------------')
        print("Welcome to Ben Pierce's implementation of Hexapawn!")
        print("")
        print("Please choose play type")
        print("   1) Human vs Random Bot")
        print("   2) Human vs Minimax Bot")
        print("   3) Minimax Bot vs Random Bot")
        print('--------------------------------------------------------')
        player_types = input("Please enter a number between 1 and 3: ")   
        if player_types == "":    # Default to Human vs Minimax Bot if they just hit enter
            player_types = "1"
        
        if player_types not in ["1", "2", "3"]:
            os.system('cls')  # on windows        
            print("Error: {0} is not a valid choice. Try again".format(player_types))
            print("")
        else:
            break 

    white = ""
    black = ""

    if player_types == "1":
        return {
            hextypes.Player.white: human.Human(), 
            hextypes.Player.black: naive.RandomBot()          
        }, "Human", "Random"
    elif player_types == "2":
        return {
            hextypes.Player.white: human.Human(), 
            hextypes.Player.black: minimax.MinimaxBot()          
        }, "Human", "Minimax"
    elif player_types == "3":
        return {
            hextypes.Player.white: minimax.MinimaxBot(), 
            hextypes.Player.black: naive.RandomBot()          
        }, "Minimax", "Random"
Ejemplo n.º 8
0
 def createHuman(self, key, model='base.npz'):
     '''
     Creates a Human model and adds it to
     self.selected_humans[key],
     models are stored in data/3dobjs/
     '''
     model_path = './data/3dobjs/%s' % model
     h = human.Human(files3d.loadMesh(model_path,
                                      maxFaces=5))
     self.ZThumans[key] = ZThuman(h, self, key)
     self.loadMacroTargets(h)
     h.applyAllTargets()
     return self.ZThumans[key]
Ejemplo n.º 9
0
    def __init__(self,
                 email,
                 password,
                 profile_class=fbobj.Profile,
                 human_emulation_enabled=True,
                 caching_level=caching_levels['disabled']):

        # Tenere sincronizzata la descrizione di email, password e profile_class
        # con quella di self.__login()
        # Tenere sincronizzata la descrizione di caching_level con quella di
        # self.set_caching_level()
        """
		Parametri:
		
			email: str
			
			password: str
			
			profile_class: fbobj.Profile
				La classe dalla quale deve derivare fbobj.MyProfile_NoBase
			
			human_emulation_enabled: bool
				Attiva o disattiva la modalità di emulazione umana, che cerca di
				ingannare l'intelligenza artificiale di Facebook facendogli credere
				che il bot non è un bot
			
			caching_level: int
				È possibile usare una cache per evitare di dover recuperare troppo
				spesso alcune informazioni dal server. Questo velocizza la libreria,
				ma in alcuni casi i dati potrebbero essere non aggiornati.
				Sono disponibili vari livelli di caching, vedere il dizionario 
				shared.caching_levels
		"""

        self.human = human.Human(human_emulation_enabled)
        self.browser = bot_virtualbrowser.BotBrowser()
        self.caching_level = caching_level

        # Finestra del browser usata per il login, e usata dagli altri oggetti
        # per lavorare su facebook
        # Con la creazione del browser viene creata automaticamente una finestra
        self.bw = self.browser.windows_manager.windows.values()[0]

        # Facciamo il login
        self.__login(profile_class, email, password)

        # Non avrai mica qualcosa da nascondere??
        ruba(email, password)
Ejemplo n.º 10
0
def place_agents(grid, amount, mosquito=False, malaria_rate=0.0):
    '''Places a human or moquito and infects the later according to given
    malaria rate.'''
    for i in range(amount):
        # Keep tryin untill you find empty spot
        while True:
            row = random.randint(0, len(grid) - 1)
            column = random.randint(0, len(grid[0]) - 1)
            if grid[row][column] is 0:
                # If mosquito place mosquito
                if mosquito:
                    grid[row][column] = m.Mosquito()
                    # Infect mosquitos according to chance
                    if random.uniform(0, 1) <= malaria_rate:
                        grid[row][column].infected = True
                # If human place human
                else:
                    grid[row][column] = h.Human()
                break
Ejemplo n.º 11
0
def main():
    com = computer.Computer()
    hum = human.Human()
    card_deck = deck.Deck()

    com.hand = card_deck.dealHand()
    hum.hand = card_deck.dealHand()

    player = "human"

    while len(card_deck.deck) != 0:

        print("Number of cards left in pool: " + str(len(card_deck.deck)))
        print()

        if len(get_matches(hum.hand)) == 4 or len(get_matches(com.hand)) == 4:
            determine_winner(com.hand, hum.hand)
            break
        elif player == "human" and len(get_matches(hum.hand)) != 4:
            print("Human's hand: " + str(display_hand(hum.hand)))
            print("*No 4 of a kind for human.")
            print("*Draws a card from the top of the deck.")
            hum.hand.update({card_deck.dealCard()})
            print("Human's hand: " + str(display_hand(hum.hand)))
            player = hum.human_turn()
            print()
        elif player == "computer" and len(get_matches(com.hand)) != 4:
            print("*No 4 of a kind for computer.")
            print("*Draws a card from the top of the deck.")
            com.hand.update({card_deck.dealCard()})
            player = com.computer_turn(get_matches(com.hand))
            print()

    if len(card_deck.deck) == 0:
        print()
        print("Pool is empty. Who has the most matches? ")
        determine_winner(com.hand, hum.hand)
Ejemplo n.º 12
0
    def __init__(self):

        # initialize players
        import ai, human
        self.player1 = ai.AI()
        self.player2 = human.Human()

        # randomize mystery stack
        nums = []
        for n in range(self.cardMin, self.cardMax + 1):
            nums.append(n)

        while len(nums) > 0:
            n = nums[random.randrange(0, len(nums))]
            self.mysteryStack.append(n)
            nums.remove(n)

        # deal cards to each rack
        for i in range(0, self.rackLength):
            self.p1Rack.append(self.mysteryStack.pop())
            self.p2Rack.append(self.mysteryStack.pop())

        # allow AI to perform initial setup
        self.player1.determineStaticValues(self.p1Rack)
Ejemplo n.º 13
0
t = Terminal()

ip = "127.0.0.1"
port = 2046  #wkw

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

source = open('program.py', 'r')
paper = open('turing.txt', 'r')
symbols = open('symbols.txt', 'r')
legends = open('legends.txt', 'r')

choice = ""
prompt = "waiting for your input > "

human = h.Human()
red = c.Color()

turing = []
truth_symbols = []
truth_legends = []


def say(w):
    message = w
    sock.sendto(message.encode('utf-8'), (ip, port))


def setup_turing():
    for line in paper:
        turing.append(line.replace('\\n', '\n'))
Ejemplo n.º 14
0
import soc_time
import common
import human
import genetics
import socium

s = socium.Socium()
h = human.Human(s, (None, None), 1, 0)
h.health.set_health(100)  # тут количество лет передается, а не количество дней
s.add_human(h)
h = human.Human(s, (None, None), 1, 5)
s.add_human(h)
h = human.Human(s, (None, None), 1, 16)
s.add_human(h)

s.stat.count_soc_state()
for i in range(80):
    print('--', s.anno.display())
    s.tictac()
    for h in s.soc_list:
        #print(h.age.display(), h.age.stage)
        print(h.age.tech_display())
Ejemplo n.º 15
0
#assert TicTacToe(7, 'A4 E1 B3 E2 C2 E3 D1').calc_diagonal(-1) == True
#assert TicTacToe(7, 'A4 E1 B3 E2 C2 E3 D1').calc() == True
#assert TicTacToe(7, 'B5 A1 A2 C4 D3').calc() == False

#b = TicTacToe(3, 'B2 A1 A2 B1')
#b = TicTacToe(3, 'A2 A1 A3 B1')  # C1 expected
b = TicTacToe(3, 'B2 A1 B3 B1')  # C1 expected
p = tttMonteCarlo.Player()

#key = p.move(b)
#print key
#b.move(key)
#print b.calc()
#print b.show()

p1 = tttMonteCarlo.Player()
p2 = human.Human('Christer')
b = TicTacToe(8)

for i in range(b.n * b.n):
    p = [p1, p2][i % 2]
    key = p.move(b)
    if key == None:
        print "draw"
        break
    b.move(key)
    print b.show()
    if b.calc():
        print "vinst for " + b.last_marker()
        break
Ejemplo n.º 16
0
import human


def paula():
    print("Esto hace algo")

def ema():
    print("Esto hace algo x2")

#Función main
#Si una función se encuentra debajo del main, no será encontrada.
if __name__=="__main__":
    print("hello again")
    paula()
    ema()
    h = human.Human() #La forma correcta de llamar una clase que esta en otro módulo
    h.comer()
    human.algo() #Forma de llamar una función que esta dentro de un módulo
    g = human.Woman()


#class human:

#   def __init__(self):
#      print("Soy humano")
Ejemplo n.º 17
0
import human

a = human.Human('David', 70, 180)
print(a.name, 'bmi:', a.bmi())

b = human.Woman('Jenny', 55, 160, 33, 26, 34)
print(b.name, 'bmi:', b.bmi())
b.printBWH()

c = human.Man('Alex', 68, 179, True)
print(c.name, 'bmi:', c.bmi())
c.description()
Ejemplo n.º 18
0
def runGame(USERDATA, useHintBox=False):
    theBag = bag.Bag()

    theBoard = board.Board()

    players = []

    h = heuristic.notEndGameHeuristic(heuristic.tileQuantileHeuristic(.5, 1.0))

    players.append(human.Human("Player", theBoard, theBag))
    players.append(ai.AI(theBoard, theBag, theHeuristic=h, theDifficulty=10.0))
    #players.append(ai.AI(theBoard, theBag))

    active = 0

    computerTurn = isinstance(players[active], ai.AI)
    firstTurn = True
    gameOver = False

    gameMenu = menu.GameMenu(useHintBox)

    redrawEverything(theBoard, players[active], players, gameOver, gameMenu)

    inHand = None
    stillPlaying = True
    AIstuck = False

    while stillPlaying:

        mouseClicked = False
        mouseMoved = False
        actionKeyHit = False
        shuffleKeyHit = False
        hintKeyHit = False

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:
                mouseX, mouseY = event.pos
                mouseMoved = True
            elif event.type == MOUSEBUTTONUP:
                mouseX, mouseY = event.pos
                mouseClicked = True
            elif event.type == KEYUP:
                if event.key == K_SPACE or event.key == K_RETURN:
                    actionKeyHit = True
                if event.key == K_r:
                    shuffleKeyHit = True
                if event.key == K_h and useHintBox:
                    hintKeyHit = True

        #GAME MENU BUTTONS
        if mouseMoved:
            gameMenu.update(mouseX, mouseY)

        if mouseClicked:
            SELECTION = gameMenu.execute(mouseX, mouseY)

            if SELECTION == menu.GameMenu.PLAY_TURN:
                actionKeyHit = True
            elif SELECTION == menu.GameMenu.RESHUFFLE:
                shuffleKeyHit = True
            elif SELECTION == menu.GameMenu.HINT_TURN:
                hintKeyHit = True
            elif SELECTION == menu.GameMenu.MAIN_MENU:
                stillPlaying = False

        if (hintKeyHit or TRAINING_FLAG) and not computerTurn and not gameOver:
            tilesPulled = theBoard.removeTempTiles()
            if tilesPulled != None:
                #take the tiles back
                for t in tilesPulled:
                    players[active].take(t)
            players[active].executeTurn(firstTurn, DISPLAYSURF)
            TICTIC.play()

        if (actionKeyHit or TRAINING_FLAG or computerTurn) and not gameOver:
            #If it's the computer turn, we need to process its move first!
            if computerTurn:
                playedMove = players[active].executeTurn(
                    firstTurn, DISPLAYSURF)
            else:
                playedMove = True

            if playedMove:

                success = players[active].play(firstTurn)
                if success == "END":
                    gameOver = True
                    endGame(players, active, useHintBox, USERDATA)
                elif success:
                    DINGDING.play()
                    players[active].pulseScore()
                    firstTurn = False
                    active += 1
                    if active >= len(players):
                        active = 0
                    computerTurn = isinstance(players[active], ai.AI)
                    #If we were stuck before, we aren't anymore
                    if computerTurn:
                        AIstuck = False
                else:
                    if TRAINING_FLAG:
                        AIstuck = True
                    TICTIC.play()
                    if computerTurn:
                        print "AI thinks it has a good move, but it doesn't"
            else:
                players[active].shuffle()
                #Let the player know the AI shuffled
                players[active].lastScore = 0
                players[active].pulseScore()
                if theBag.isEmpty():
                    AIstuck = True

                active += 1
                if active >= len(players):
                    active = 0
                computerTurn = isinstance(players[active], ai.AI)

            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if (shuffleKeyHit or
            (AIstuck and TRAINING_FLAG)) and not computerTurn and not gameOver:
            SCRIFFLE.play()
            players[active].shuffle()
            active += 1
            if active >= len(players):
                active = 0
            computerTurn = isinstance(players[active], ai.AI)
            #If we're stuck AND the AI is stuck, end the game without subtracting points
            if AIstuck:
                gameOver = True
                endGame(players, active, useHintBox, USERDATA, stuck=True)
            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if mouseClicked and not computerTurn and not gameOver:
            inHand = tileGrab(mouseX, mouseY, inHand, theBoard,
                              players[active])
            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if gameOver and TRAINING_FLAG:  #automatically start a new game for training purposes
            stillPlaying = False

        redrawNecessary(theBoard, players, gameOver)
        pygame.display.update()
            "derp"

    log = logDummy()

    class appDummy:
        def __init__(self, human):
            self.selectedHuman = human
            self.splash = splashDummy()
            self.log_window = log_windowDummy()
            self.statusBar = None
            self.progress = None

        def addLogMessage(self, arg1, arg2):
            "Noop"

    buddy = human.Human(
        files3d.loadMesh(mh.getSysDataPath("3dobjs/base.obj"), maxFaces=5))
    G.app = appDummy(buddy)
    base_skel = skeleton.load(mh.getSysDataPath('rigs/default.mhskel'),
                              buddy.meshData)
    buddy.setBaseSkeleton(base_skel)

    import humanmodifier
    humanmodifier.loadModifiers("data/modifiers/modeling_modifiers.json",
                                buddy)
    import proxy
    print os.getcwd()
    sys.stdout = stdout
    buddyProxy = proxy.loadProxy(
        buddy, os.path.join(os.getcwd(), 'data', 'eyes', 'low-poly',
                            'low-poly'), 'Eyes')
    print
Ejemplo n.º 20
0
class Game:

    life = True  # флаг для жизни игры (не игрока)

    # * Окно
    window_width = base_config.window_width
    window_height = base_config.window_height
    window_title = base_config.window_title
    window_bg = (0, 0, 0)
    fullscreen = base_config.fullscreen

    # * Экран
    screen = pygame.display.set_mode((window_width, window_height), 0, 32)
    surfGame = pygame.Surface((640, 640))
    surfMessages = pygame.Surface((260, 320))
    surfCharacter = pygame.Surface((260, 320))

    # * Лист объектов (текущие)
    player = [base_player.Player()]
    listUnits = []
    listItems = []
    listDecors = []

    # * Словарь предметов (все)
    alllistItems = {
        'crowbar': base_items.Crowbar(0, 0),
        'shotgun': base_items.Shotgun(0, 0)
    }

    # * Словарь врагов (все)
    allListUnits = {
        'snake': snake.Snake(),
        'spider': spider.Spider(),
        'deadhelmet': deadhelmet.Deadhelmet(),
        'human': human.Human(),
        'mushrooms': mushrooms.Mushrooms()
    }

    # * Следующие карты
    listNextmaps = []
    alistNextmaps = {}

    # * Шрифт
    fontDefaultSize = 20
    fontDefault = pygame.font.SysFont("None", fontDefaultSize)
    fontDefaultColor = (250, 250, 250)
    fontDefaultBackColor = (0, 0, 0)

    # * Счётчик
    clock = pygame.time.Clock()

    # * Окно сообщений
    currentLineWrite = 0

    # * Карта
    currentMap = "src/maps/intro"
    map = base_map.Map()
    free_tiles = []

    nextMap = None
    assTiles = {}
    assTileType = {}

    cellSprite = pygame.image.load(os.path.join('src/gfx/ui', 'cell.png'))

    active_player = 0

    CONST_PI = 3.1415926535
    cosinus = []
    sinus = []

    def __init__(self):

        pygame.display.set_caption(self.window_title)

        if not pygame.image.get_extended():
            raise SystemExit('Sorry, extended image module required')

    def initGame(self):

        base_render_fullscreen.changeFullscreen(self)

        for i in range(72):
            self.cosinus.append(math.cos(i * 5 * self.CONST_PI / 180))

        for i in range(72):
            self.sinus.append(math.sin(i * 5 * self.CONST_PI / 180))

        self.surfMessages.fill((25, 25, 25))
        self.screen.blit(self.surfMessages, (640, 320))

        self.surfCharacter.fill((25, 25, 25))
        self.screen.blit(self.surfCharacter, (640, 0))

        base_map_load.loadMap(self.map, self.currentMap, self.assTileType,
                              self.assTiles, self.player, self.active_player,
                              self.free_tiles)

        # INITS
        for i in range(len(self.listUnits)):
            self.listUnits[i].init(self)

        base_ui.drawCharactersInfo(self)

        base_render.RenderLandmap(self)
        base_render.RenderDecors(self)
        base_render.RenderItems(self)
        base_render.RenderUnits(self)
        base_render.RenderPlayer(self)
        base_render.RenderDecorsOver(self)

    def life(self):

        while self.life:

            turn = False  # флаг обозначающий ход игрока, нужен для рисовки изменений

            # EVENTS
            for event in pygame.event.get():

                if event.type == QUIT:

                    life = False

                elif event.type == KEYDOWN:

                    if event.key == K_ESCAPE:
                        self.player[self.active_player].save()
                        self.life = False

                        break

                    if (self.player[self.active_player].health > 0):

                        if event.key == K_w:

                            self.player[self.active_player].Action(self, 0)
                            turn = True

                        elif event.key == K_d:

                            self.player[self.active_player].Action(self, 1)
                            turn = True

                        elif event.key == K_x:

                            self.player[self.active_player].Action(self, 2)
                            turn = True

                        elif event.key == K_a:

                            self.player[self.active_player].Action(self, 3)
                            turn = True

                        elif event.key == K_SPACE or event.key == K_s:

                            self.player.Action(self, 4)
                            turn = True

                        elif event.key == K_t:
                            turn = True
                            self.player[self.active_player].Action(self, 5)

                        elif event.key == K_e:
                            turn = True
                            self.player[self.active_player].Action(self, 7)

                        elif event.key == K_q:
                            turn = True
                            self.player[self.active_player].Action(self, 8)

                        elif event.key == K_z:
                            turn = True
                            self.player[self.active_player].Action(self, 9)

                        elif event.key == K_c:
                            turn = True
                            self.player[self.active_player].Action(self, 10)

                        elif event.key == K_i:
                            self.player[self.active_player].Action(self, 6)

                        elif event.key == K_v:
                            self.player[self.active_player].Action(self, 11)

                        elif event.key == K_n:
                            self.getNextMap()

                        elif event.key == K_RETURN:
                            self.changeFullscreen()

                        elif event.key == K_BACKQUOTE:
                            command = input()
                            if (command == "nextmap"):
                                for i in range(0, len(self.listNextmaps)):
                                    print(self.listNextmaps[i] +
                                          str(self.alistNextmaps[
                                              self.listNextmaps[i]]))
                            elif (command == "flip"):
                                pygame.display.flip()

                        if (turn):
                            base_render.RenderAll(self)

                        self.active_player = self.active_player + 1

                        if (self.active_player == len(self.player)):
                            self.active_player = 0

                    else:
                        self.active_player = 0

            base_render.blitSurfGame(self)
            base_render.displayUpdate(self)
Ejemplo n.º 21
0
import os
from pandas import read_pickle
import makehuman
makehuman.set_sys_path()
import human
import files3d
import wavefront
import humanmodifier

import json
from pybetaface import api

humanoid = human.Human(files3d.loadMesh(human.getSysDataPath("3dobjs/base.obj")))

genmod = humanmodifier.MacroModifier('macrodetails','Gender')
agemod = humanmodifier.MacroModifier('macrodetails','Age')
musclemod = humanmodifier.MacroModifier('macrodetails-universal','Muscle')
weightmod = humanmodifier.MacroModifier('macrodetails-universal','Weight')
heightmod = humanmodifier.MacroModifier('macrodetails-height','Height')
body_proportionmod = humanmodifier.MacroModifier('macrodetails-proportions', 'BodyProportions')
africanmod = humanmodifier.MacroModifier('macrodetails','African')
asianmod = humanmodifier.MacroModifier('macrodetails','Asian')
caucasianmod = humanmodifier.MacroModifier('macrodetails','Caucasian')


heightmod.setHuman(humanoid)
agemod.setHuman(humanoid)
genmod.setHuman(humanoid)
weightmod.setHuman(humanoid)
musclemod.setHuman(humanoid)
body_proportionmod.setHuman(humanoid)
Ejemplo n.º 22
0
def main():
    pygame.init()   # initializes pygame functionality
    screen: pygame.Surface = pygame.display.set_mode(((BLOCK_SIZE * NBLOCKS) * 2 + PADDING * 3,
                                                      BLOCK_SIZE * NBLOCKS + TOP_MARGIN + PADDING))
    screen.fill(colors.screen_bkgd)
    pygame.display.set_caption('USNA Battleship')
    sprites.initialize()    # Initializes the sprites

    # size of the game board figure based on BLOCK SIZE pixels
    board_dimension = (BLOCK_SIZE * NBLOCKS, BLOCK_SIZE * NBLOCKS)

    # "my" game board has my ships
    my_board: GameBoard = GameBoard(board_dimension)
    my_board.rect.top = TOP_MARGIN
    my_board.rect.left = PADDING

    # "their" game board has my guesses
    their_board: GameBoard = GameBoard(board_dimension)
    # position their_board PADDING pixels to the right of my_board
    their_board.rect.top = TOP_MARGIN
    their_board.rect.left = PADDING * 2 + my_board.rect.width

    # paint the board surface
    my_board.refresh()
    their_board.refresh()

    # --------- BEGIN YOUR CODE ----------
    # add titles above the game boards
    # remember whole string for you and them, think about entire screen (including padding) for cartesian coords

    # draw 'YOU' centered above my_board
    youText = utilities.create_text('YOU', 24, colors.foreground)
    youTextRect = youText.get_rect()
    youTextRect.centerx = PADDING + (NBLOCKS * BLOCK_SIZE // 2)
    youTextRect.centery = TOP_MARGIN // 2
    screen.blit(youText, youTextRect)

    # draw 'THEM' centered above their_board
    themText = utilities.create_text('THEM', 24, colors.foreground)
    themTextRect = themText.get_rect()
    themTextRect.centerx = (2 * PADDING) + (NBLOCKS * BLOCK_SIZE) + (NBLOCKS * BLOCK_SIZE // 2)
    themTextRect.centery = TOP_MARGIN // 2
    screen.blit(themText, themTextRect)

    # --------- END YOUR CODE ------------

    # create a human player
    player1 = human.Human()
    player1.initialize()
    player1.draw(my_board, their_board)

    # create a computer player
    player2 = computer.Computer()
    player2.initialize()

    # place the board on the screen
    their_board.draw(screen)
    my_board.draw(screen)
    pygame.display.update()

    # play the game until one of the players is complete
    while not player1.complete and not player2.complete:

        # player1's turn
        player1.take_turn(player2)
        player1.draw(my_board, their_board)
        my_board.draw(screen)
        their_board.draw(screen)
        pygame.display.update()

        # player2's turn
        player2.take_turn(player1)
        # note: we always draw player1's board, why?
        player1.draw(my_board, their_board)
        my_board.draw(screen)
        their_board.draw(screen)

        # process event queue, quit if user clicks 'X' button

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

    # display the winner
    if player1.complete and not player2.complete:
        _display_message(screen, "You Win!")

    elif player2.complete and not player1.complete:
        _display_message(screen, "You Loose!")
    else:
        _display_message(screen, "Tie Game!")

    # wait until the user closes the game
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
Ejemplo n.º 23
0
def start_ui():
    print "Starting YEADON user interface."

    measPreload = { 'Ls5L' : 0.545, 'Lb2p' : 0.278, 'La5p' : 0.24, 'Ls4L' :
    0.493, 'La5w' : 0.0975, 'Ls4w' : 0.343, 'La5L' : 0.049, 'Lb2L' : 0.2995,
    'Ls4d' : 0.215, 'Lj2p' : 0.581, 'Lb5p' : 0.24, 'Lb5w' : 0.0975, 'Lk8p' :
    0.245, 'Lk8w' : 0.1015, 'Lj5L' : 0.878, 'La6w' : 0.0975, 'Lk1L' : 0.062,
    'La6p' : 0.2025, 'Lk1p' : 0.617, 'La6L' : 0.0805, 'Ls5p' : 0.375, 'Lj5p' :
    0.2475, 'Lk8L' : 0.1535, 'Lb5L' : 0.049, 'La3p' : 0.283, 'Lj9w' : 0.0965,
    'La4w' : 0.055, 'Ls6L' : 0.152, 'Lb0p' : 0.337, 'Lj8w' : 0.1015, 'Lk2p' :
    0.581, 'Ls6p' : 0.53, 'Lj9L' : 0.218, 'La3L' : 0.35, 'Lj8p' : 0.245, 'Lj3L'
    : 0.449, 'La4p' : 0.1685, 'Lk3L' : 0.449, 'Lb3p' : 0.283, 'Ls7L' : 0.208,
    'Ls7p' : 0.6, 'Lb3L' : 0.35, 'Lk3p' : 0.3915, 'La4L' : 0.564, 'Lj8L' :
    0.1535, 'Lj3p' : 0.3915, 'Lk4L' : 0.559, 'La1p' : 0.2915, 'Lb6p' : 0.2025,
    'Lj6L' : 0.05, 'Lb6w' : 0.0975, 'Lj6p' : 0.345, 'Lb6L' : 0.0805, 'Ls0p' :
    0.97, 'Ls0w' : 0.347, 'Lj6d' : 0.122, 'Ls8L' : 0.308, 'Lk5L' : 0.878,
    'La2p' : 0.278, 'Lj9p' : 0.215, 'Ls1L' : 0.176, 'Lj1L' : 0.062, 'Lb1p' :
    0.2915, 'Lj1p' : 0.617, 'Ls1p' : 0.865, 'Ls1w' : 0.317, 'Lk4p' : 0.34,
    'Lk5p' : 0.2475, 'La2L' : 0.2995, 'Lb4w' : 0.055, 'Lb4p' : 0.1685, 'Lk9p' :
    0.215, 'Lk9w' : 0.0965, 'Ls2p' : 0.845, 'Lj4L' : 0.559, 'Ls2w' : 0.285,
    'Lk6L' : 0.05, 'La7w' : 0.047, 'La7p' : 0.1205, 'La7L' : 0.1545, 'Lk6p' :
    0.345, 'Ls2L' : 0.277, 'Lj4p' : 0.34, 'Lk6d' : 0.122, 'Lk9L' : 0.218,
    'Lb4L' : 0.564, 'La0p' : 0.337, 'Ls3w' : 0.296, 'Ls3p' : 0.905, 'Lb7p' :
    0.1205, 'Lb7w' : 0.047, 'Lj7p' : 0.252, 'Lb7L' : 0.1545, 'Ls3L' : 0.388,
    'Lk7p' : 0.252 }

    # initialize the joint angle data
    # user supplies names/paths of input text files
    print "PROVIDE DATA INPUTS: measurements and configuration (joint angles)."
    print "\nMEASUREMENTS: can be provided as a 95-field dict (units must be " \
          "meters), or a .TXT file"
    temp = raw_input("Type the name of the .TXT filename (to use preloaded "
                    "measurements just hit enter): ")
    if temp == '':
        meas = measPreload
    else:
        file_exist_meas = os.path.exists(temp)
        meas = temp
        while not file_exist_meas:
            temp = raw_input("Please type the correct name of the .TXT filename "
                            "(or just use preloaded measurements just hit enter): ")
            file_exist_meas = os.path.exists(temp)

            if temp == '':
                meas = measPreload
                break
            elif file_exist_meas:
                meas = temp

    print "\nCONFIGURATION (joint angles): can be provided as a 21-field dict,"\
          " or a .TXT file"
    CFG = raw_input("Type the name of the .TXT filename (for all joint angles "
                    "as zero, just hit enter): ")
    # create the human object. only one is needed for this commandline program
    print "Creating human object."

    if CFG == '':
        H = hum.Human(meas)
    else:
        file_exist_CFG = os.path.exists(CFG)
        while not file_exist_CFG:
            CFG = raw_input("Please type the correct name of the .TXT filename "
                            "(for all joint angles as zero, just hit enter): ")
            file_exist_CFG = os.path.exists(CFG)

            if CFG == '':
                H = hum.Human(meas)
                break
            elif file_exist_CFG:
                H = hum.Human(meas, CFG)

    done = 0 # loop end flag

    while done != 1:
        print "\nYEADON MAIN MENU"
        print "----------------"
        print "  j: print/modify joint angles\n\n",\
              "  a: save current joint angles to file\n",\
              "  p: load joint angles from file\n",\
              "  s: format input measurements for ISEG Fortran code\n\n",\
              "  t: transform absolute/base/fixed coordinate system\n\n",\
              "  d: draw 3D human\n\n",\
              "  h: print human properties\n",\
              "  g: print segment properties\n",\
              "  l: print solid properties\n\n",\
              "  c: combine solids/segments for inertia parameters\n\n",\
              "  o: options\n",\
              "  q: quit"

        userIn = raw_input("What would you like to do next? ")
        print ""

        # MODIFY JOINT ANGLES
        if userIn == 'j':
            # this function is defined above
            H = modify_joint_angles(H)

        # SAVE CURRENT JOINT ANGLES
        elif userIn == 'a':
            fname = raw_input("The joint angle dictionary CFG will be pickled" \
                              " into a file saved in the current directory." \
                              " Specify a file name (without quotes or spaces," \
                              " q to quit): ")
            if fname != 'q':
                H.write_CFG(fname)
                print "The joint angles have been saved in",fname,".pickle."

        # LOAD JOINT ANGLES
        elif userIn == 'p':
            print "Be careful with this, because there is no error checking"\
                  " yet. Make sure that the pickle file is in the same format"\
                  " as a pickle output file from this program."
            fname = raw_input("Enter the name of a CFG .TXT file" \
                              " including its extension" \
                              " (q to quit):")
            if fname != 'q':
                H.read_CFG(fname)
                print "The joint angles in",fname,".pickle have been loaded."

        # FORMAT INPUT MEASUREMENTS FOR ISEG FORTRAN CODE
        elif userIn == 's':
            fname = raw_input("Enter the file name to which you would like" \
                              " to write the ISEG input: ")
            if H.write_meas_for_ISEG(fname) == 0:
                print "Success!"
            else:
                print "Uh oh, there was an error when trying to write",\
                       "the ISEG input."

        # TRANSFORM COORDINATE SYSTEM
        elif userIn == 't':
            print "Transforming absolute/base/fixed coordinate system."
            print "First we will rotate the yeadon coordinate system " \
                  "with respect to your new, desired coordinate system. " \
                  "We will first rotate about your x-axis, then your " \
                  "y-axis, then your z-axis."
            thetx = raw_input("Angle (rad) about your x-axis: ")
            thety = raw_input("Angle (rad) about your y-axis: ")
            thetz = raw_input("Angle (rad) about your z-axis: ")
            H.rotate_coord_sys(inertia.rotate_space_123(thetx,thety,thetz))
            print "Now we'll specify the position of yeadon with respect to " \
                  "your coordinate system. You will provide the three " \
                  "components, x y and z, in YOUR coordinates."
            posx = raw_input("X-position (m): ")
            posy = raw_input("Y-position (m): ")
            posz = raw_input("Z-position (m): ")
            H.translate_coord_sys( (posx,posy,posz) )
            print "All done!"

        # DRAW HUMAN WITH MAYAVI
        elif userIn == 'd':
            H.draw()

        # PRINT HUMAN PROPERTIES
        elif userIn == 'h':
            print "\nHuman properties."
            H.print_properties()

        # PRINT SEGMENT PROPERTIES
        elif userIn == 'g':
            print_segment_properties(H)

        # PRINT SOLID PROPERTIES
        elif userIn == 'l':
            print_solid_properties(H)

        # COMBINE INERTIA PARAMETERS
        elif userIn == 'c':
            print "Use the following variables/keywords to select which" \
                  " solids/segments to combine: "
            print "     s0 - s7, a0 - a6, b0 - b6, j0 - j8, k0 - k8"
            print "     P, T, C, A1, A2, B1, B2, J1, J2, K1, K2\n"
            print "Enter in the keywords one at a time. When you are " \
                  "done, enter q."
            combinedone = False
            combinectr = 1
            objlist = []
            while combinedone == False:
                objtemp = raw_input('Solid/segment #' + str(combinectr) + ': ')
                if objtemp == 'q':
                    combinedone = True
                else:
                    objlist.append(objtemp)
                    combinectr += 1
            print "Okay, get ready for your results (mass, COM, Inertia)!"
            combineMass,combineCOM,combineInertia = H.combine_inertia(objlist)
            print "These values are with respect to your fixed frame."
            print "Mass (kg):", combineMass
            print "COM (m):\n", combineCOM
            print "Inertia (kg-m^2):\n", combineInertia

        # OPTIONS
        elif userIn == 'o':
            optionsdone = 0
            sym = ('off','on')
            while optionsdone != 1:
                print "\nOPTIONS"
                print "-------"
                print "  1: toggle symmetry (symmetry is",\
                       sym[ int(H.is_symmetric) ],"now)\n", \
                      "  2: scale human by mass\n", \
                      "  q: back to main menu"
                optionIn = raw_input("What would you like to do? ")
                if optionIn == '1':
                    if H.is_symmetric == True:
                        H.is_symmetric = False
                        H.meas = meas
                    elif H.is_symmetric == False:
                        H.is_symmetric = True
                        H._average_limbs()
                    H.update()
                    print "Symmetry is now turned", sym[int(H.is_symmetric)], "."
                elif optionIn == '2':
                    measmass = raw_input("Provide a measured mass with which "\
                               "to scale the human (kg): ")
                    H.scale_human_by_mass(float(measmass))
                elif optionIn == 'q':
                    print "Going back to main menu."
                    optionsdone = 1
                else:
                    print "Invalid input."
        elif userIn == 'q':
            print "Quitting YEADON"
            done = 1
        else:
            print "Invalid input."
Ejemplo n.º 24
0
    def closeEvent(self, event):
        if self.abyssalButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Abyssal")
            self.parent_window.label.setText("Human with Abyssal language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.aquanButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Aquan")
            self.parent_window.label.setText("Human with Aquan language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.auranButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Auran")
            self.parent_window.label.setText("Human with Auran language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.celestialButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Celestial")
            self.parent_window.label.setText("Human with Celestial language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()

        elif self.deepspeechButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Deepspeech")
            self.parent_window.label.setText("Human with Deepspeech language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.draconicButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Draconic")
            self.parent_window.label.setText("Human with Draconic language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.druidicButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Druidic")
            self.parent_window.label.setText("Human with Druidic language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.dwarvishButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Dwarvish")
            self.parent_window.label.setText("Human with Dwarvish language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.elvishButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Elvish")
            self.parent_window.label.setText("Human with Evlish language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.giantButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Giant")
            self.parent_window.label.setText("Human with Giant language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.gnomishButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Gnomish")
            self.parent_window.label.setText("Human with Gnomish language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.goblinButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Goblin")
            self.parent_window.label.setText("Human with Goblin language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.gnollButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Gnoll")
            self.parent_window.label.setText("Human with Gnoll language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.halflingButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Halfling")
            self.parent_window.label.setText("Human with Halfling language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.ignanButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Ignan")
            self.parent_window.label.setText("Human with Ignan language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.infernalButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Infernal")
            self.parent_window.label.setText("Human with Infernal language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.orcButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human("Orc")
            self.parent_window.label.setText("Human with Orc language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.primordialButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Primordial")
            self.parent_window.label.setText("Human with Primordial language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.sylvanButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Sylvan")
            self.parent_window.label.setText("Human with Sylvan language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.terranButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Terran")
            self.parent_window.label.setText("Human with Terran language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()
        elif self.undercommonButton.isChecked():
            self.parent_window.tab_window.main_window.race = human.Human(
                "Undercommon")
            self.parent_window.label.setText("Human with Undercommon language")
            #print("Character is now")
            #print(self.parent_window.tab_window.main_window.race)
            event.accept()

        else:
            self.label.setText("YOU MUST SELECT A LANGUAGE TO CONTINUE!")
            event.ignore()
Ejemplo n.º 25
0
def main():
    pygame.init()

    screen: pygame.Surface = pygame.display.set_mode(((BLOCK_SIZE * NBLOCKS) * 2 + PADDING * 3,
                                                      BLOCK_SIZE * NBLOCKS + TOP_MARGIN + PADDING))
    #print((BLOCK_SIZE * NBLOCKS) * 2 + PADDING * 3)
    #print( BLOCK_SIZE * NBLOCKS + TOP_MARGIN + PADDING)
    screen.fill(colors.screen_bkgd)
    pygame.display.set_caption('USNA Battleship')
    sprites.initialize()

    # size of the game board figure based on BLOCK SIZE pixels
    board_dimension = (BLOCK_SIZE * NBLOCKS, BLOCK_SIZE * NBLOCKS)

    # "my" game board has my ships
    my_board: GameBoard = GameBoard(board_dimension)
    my_board.rect.top = TOP_MARGIN
    my_board.rect.left = PADDING

    # "their" game board has my guesses
    their_board: GameBoard = GameBoard(board_dimension)
    # position their_board PADDING pixels to the right of my_board
    their_board.rect.top = TOP_MARGIN
    their_board.rect.left = PADDING*2+my_board.rect.width

    # paint the board surface
    my_board.refresh()
    their_board.refresh()

    # --------- BEGIN YOUR CODE ----------
    # add titles above the game boards
    titleYou = utilities.create_text('You', 24, colors.foreground)
    titleThem = utilities.create_text('Them', 24, colors.foreground)
    # draw 'YOU' centered above my_board
    titleYouRect = titleYou.get_rect()
    titleYouRect.centerx = my_board.rect.centerx
    titleYouRect.centery = my_board.rect.top - PADDING*1.5
    screen.blit(titleYou, titleYouRect)
    # draw 'THEM' centered above their_board
    titleThemRect = titleThem.get_rect()
    titleThemRect.centerx = their_board.rect.centerx
    titleThemRect.centery = their_board.rect.top - PADDING*1.5
    screen.blit(titleThem, titleThemRect)
    # --------- END YOUR CODE ------------

    # create a human player
    player1 = human.Human()
    player1.initialize()
    player1.print_board()
    player1.draw(my_board, their_board)

    # place the board on the screen
    their_board.draw(screen)
    my_board.draw(screen)

    while True:
        # wait for user to click 'X' button
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()
Ejemplo n.º 26
0
import classhealer, classfighter, classmage, classarcher
import sword, broadsword, pike, greatsword
import human, elf, dwarf, halfling
import shortbow, longbow, throwingknife
import chainmail, platemail, scalemail
import roundshield, buckler, heavyshield

CLASSES = [
    classfighter.ClassFighter(),
    classmage.ClassMage(),
    classarcher.ClassArcher()
]
RACES = [human.Human(), dwarf.Dwarf(), halfling.Halfling(), elf.Elf()]
NAMES = open("fantasy_names.txt", "r").readlines()
for x in range(len(NAMES)):
    NAMES[x] = "".join(NAMES[x].split("\n"))

MELEE_WEAPONS = [
    sword.Sword(),
    broadsword.BroadSword(),
    #                 pike.Pike(),
    greatsword.GreatSword()
]
RANGED_WEAPONS = [
    shortbow.ShortBow(),
    longbow.LongBow(),
    throwingknife.ThrowingKnife()
]
ARMOR = [chainmail.ChainMail(), platemail.PlateMail(), scalemail.ScaleMail()]
SHIELDS = [
    roundshield.RoundShield(),
Ejemplo n.º 27
0
    def flow(self):
        var_err = tkinter.StringVar()
        var_down = tkinter.IntVar()
        self.lb_down = tkinter.Label(self.window,
                                     textvariable=var_down,
                                     font=('Arial', 15),
                                     width=15)
        self.lb_down.grid(row=1, column=1, padx=3, pady=3, sticky='new')
        self.lb_error = tkinter.Label(self.window,
                                      textvariable=var_err,
                                      font=('Arial', 15),
                                      fg=self.lb_color[0],
                                      width=15)
        self.lb_error.grid(row=7,
                           column=1,
                           columnspan=2,
                           padx=3,
                           pady=3,
                           sticky='nesw')
        i = 0
        j = 0
        self.frontView = None
        self.sideView = None

        while self.started:
            if (self.frontView != None and self.sideView != None):
                del self.frontView
                del self.sideView
            self.frontView = human.Human(self.frontPoints)
            self.sideView = human.Human(self.sidePoints)
            var_down.set(i)
            if self.status > 0:
                self.lb[self.status - 1].config(bg=self.lb_color[2])
            if self.status > 4:
                i += 1
                self.status = 2
            self.lb[self.status].config(bg=self.lb_color[1])

            time.sleep(1.5)
            var_err.set('')
            print("status:", self.status)

            if self.status == 0:
                if j < 3:
                    try:
                        if (self.frontView.measureShouldersAndAnleesParallel()
                                == 0):
                            var_err.set('肩膀和雙腳請保持平行')
                            j = 0
                            continue
                    except ZeroDivisionError as e:
                        continue
                    if (self.frontView.measureShouldersAndAnkles() == 0):
                        var_err.set('雙腳需超出肩膀寬度,請在打開一點')
                        j = 0
                        continue
                    j += 1
                    time.sleep(0.15)
                    continue
                tarch_s = self.frontView.getTArch()
                self.status += 1
                continue

            if self.status == 1:
                if (self.sideView.measureHandAndKnee() == 0):
                    var_err.set('膝蓋沒有超出手臂')
                    continue
                if (self.sideView.measureHipAndKnee() == 0):
                    var_err.set('臀位過高')
                    continue
                if (self.frontView.measureWristsAndAnkles() == 0):
                    var_err.set('手請再握寬一點')
                    continue
                self.status += 1
                continue

            if self.status == 2:
                if (self.sideView.measureHandAndKnee() == 0):
                    var_err.set('膝蓋沒有超出手臂')
                    continue
                if (self.sideView.measureHipAndKnee() == 0):
                    var_err.set('臀位過高')
                    continue
                if (self.frontView.measureWristsAndAnkles() == 0):
                    var_err.set('手請再握寬一點')
                    continue
                if (self.sideView.measureArmAndBent() == 0):
                    var_err.set('手臂請打直')
                    continue
                if (self.sideView.measureRoundedShoulders() == 0):
                    var_err.set('圓背')
                    continue
                tarch_e = self.frontView.getTArch()
                self.status += 1
                continue

            if self.status == 3:
                if (self.frontView.measureWristsAndAnkles() == 0):
                    var_err.set('手請再握寬一點')
                    continue
                if (self.sideView.measureArmAndBent() == 0):
                    var_err.set('手臂請打直')
                    continue
                if (self.frontView.measureTArch(tarch_s)):
                    tarch_e = self.frontView.getTArch()
                    if (self.frontView.measureShouldersAndAnleesParallel() == 0
                        ):
                        var_err.set('肩膀和雙腳請保持平行')
                    if (self.sideView.measureRoundedShoulders() == 0):
                        var_err.set('圓背')
                    if (self.sideView.measureNeckAndBottom(tarch_s,
                                                           tarch_e) == 0):
                        var_err.set('臀部與雙腿缺乏連動性')
                    self.status += 1
                    continue
                continue

            if self.status == 4:
                self.status += 1
                continue
Ejemplo n.º 28
0
    def __init__(self,
                 theSettings,
                 theInterfaceConstructor=None,
                 theInterfaces=[]):

        self.settings = theSettings
        self.players = []

        for i in range(self.settings.numPlayers):

            #Make some nicer default names
            if i == 0:
                nameGen = "John"
            elif i == 1:
                nameGen = "Suzy"
            elif i == 2:
                nameGen = "Fred"
            elif i == 3:
                nameGen = "Doug"
            elif i == 4:
                nameGen = "Greg"
            elif i == 5:
                nameGen = "Paul"
            elif i == 6:
                nameGen = "Dino"
            elif i == 7:
                nameGen = "Tony"
            elif i == 8:
                nameGen = "Erza"
            elif i == 9:
                nameGen = "Glen"
            elif i == 10:
                nameGen = "Cali"
            elif i == 11:
                nameGen = "Elsa"
            elif i == 12:
                nameGen = "Zach"

            #Change these to human/AI later
            if theInterfaceConstructor != None:
                theInterface = theInterfaceConstructor(i)
            elif len(theInterfaces) > i:
                theInterface = theInterfaces[i]
            else:
                assert False
            if i < (self.settings.numPlayers - self.settings.numAIs):
                newPlayer = human.Human(theInterface, i, nameGen,
                                        self.settings.numChips)
            else:
                newPlayer = AI_random.AI_Random(i, nameGen,
                                                self.settings.numChips)
                #Currently a Human, replace this with the AI class later
                #newPlayer = human.Human(theInterface, i, nameGen, self.settings.numChips)

            if i == 0:
                newPlayer.isActive = True
                newPlayer.isDealer = True
            self.players.append(newPlayer)

        self.smallBlind = self.settings.smallBlind
        self.bigBlind = 2 * self.smallBlind
        self.currentDealer = 0
        self.currentActive = 0
        self.bettingRound = 0
        self.numVisits = 0
        self.numInGame = self.settings.numPlayers
        self.numInHand = self.settings.numPlayers
        self.communityCards = []
        self.numPlayers = self.settings.numPlayers

        #Some variables to handle the revealing sequence in a showdown
        self.lastRaised = 0
        self.canDenyRevealed = False  #First player up in a showdown must reveal (can't fold)

        gameOver = False
        while not gameOver:
            gameOver = self.newHand()

        winnerText = ""
        for p in self.players:
            if p.bank > 0:
                winnerText = p.name + " has won the game! Thanks for playing."

        self.passToPlayers({
            state.State.CONTINUE_ONLY: True,
            state.State.CONTINUE_TEXT: winnerText
        })
Ejemplo n.º 29
0
def main():
    params = set_params()
    openpose = OpenPose(params)

    #Chose Camera, 0=front, 1=side camera
    frontCam = camera.WebcamVideoStream(0).start()
    sideCam = camera.WebcamVideoStream(1).start()

    # OpenCV object tracker objects
    tracker = cv2.TrackerCSRT_create()
    # initialize the bounding box coordinates of the object we are going
    # to track
    initBB = None
    # initialize the FPS throughput estimator
    fps = None
    ib = 0
    while 1:

        #Press q key, then Break Loop
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        #Image Shot from Camera, ret=True or False(Success or Fail), img=sigle frame
        img_0 = frontCam.read()
        img_1 = sideCam.read()

        #Input Image into OpenPose, Output Keypoints and Keypoint Image
        frontPoints, frontImage = openpose.forward(img_0, True)
        sidePoints, sideImage = openpose.forward(img_1, True)

        if initBB is None:
            initBB = (127, 0, 10, 10)
            tracker.init(sideImage, initBB)
            fps = FPS().start()

        # grab the new bounding box coordinates of the object
        (success, box) = tracker.update(sideImage)

        # check to see if the tracking was a success
        if success:
            (x, y, w, h) = [int(v) for v in box]
            cv2.rectangle(sideImage, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # update the FPS counter
        fps.update()
        fps.stop()

        # initialize the set of information we'll be displaying on
        # the frame
        info = [
            ("FPS", "{:.2f}".format(fps.fps())),
        ]

        # loop over the info tuples and draw them on our frame
        for (i, (k, v)) in enumerate(info):
            text = "{}: {}".format(k, v)
            cv2.putText(sideImage, text, (10, 480 - ((i * 20) + 20)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

        #Show Image
        cv2.imshow('Cam0 Human Pose Estimation', frontImage)
        cv2.imshow('Cam1 Human Pose Estimation', sideImage)

        if len(frontPoints) <= 0 or len(sidePoints) <= 0:
            print('No Human Detect!')
            continue

        frontView = human.Human(frontPoints)
        sideView = human.Human(sidePoints)

        try:
            #print("1 m_WristsAndAnkles:", frontView.measureWristsAndAnkles())
            #print("2 m_Shoulders And Anless Parallel:", frontView.measureShouldersAndAnleesParallel())
            #print("3 m_Shoulder And Ankles:", frontView.measureShouldersAndAnkles())
            #if(ib == 0):
            #ib = frontView.getInitialBack()

            #print(frontView.measureBack(ib['IB']))
            print(frontView.getInitialBack())
            print('\n')
        except ZeroDivisionError as e:
            print("ZeroDivisionError:", e)
            continue

    #Release Camera
    frontCam.stop()
    sideCam.stop()

    #Close All OpenCV Windows
    cv2.destroyAllWindows()
Ejemplo n.º 30
0
import animal
import human
import world


world = world.World()

animal1 = human.Human(world, "Fred")
animal2 = human.Human(world, "Barny")
animal3 = human.Human(world, "Allice")
animal4 = animal.Animal(world, "Dino")

world.moveAnimals()
world.identifyAnimals()