예제 #1
0
def init_monster_in_game(monster_name, monster_number, ground, lives, IA):
    list_monsters = ["ghost", "golem", "human", "goblin"]
    if ground == "1":
        start_x_monster_1 = 60
        start_x_monster_2 = 850
        end = 1210
    elif ground == "2":
        start_x_monster_1 = 60
        start_x_monster_2 = 740
        end = 1100
    else:
        start_x_monster_1 = 350
        start_x_monster_2 = 650
        end = 1050

    if monster_number == 1:
        if monster_name == list_monsters[0]:
            monster = Ghost(start_x_monster_1, 417, end, lives, 0, IA, 1)
        elif monster_name == list_monsters[1]:
            monster = Golem(start_x_monster_1, 410, end, lives, 0, IA, 1)
        elif monster_name == list_monsters[2]:
            monster = Human(start_x_monster_1, 420, end, lives, 0, IA, 1)
        else:
            monster = Goblin(start_x_monster_1, 430, end, lives, 0, IA, 1)
    else:
        if monster_name == list_monsters[0]:
            monster = Ghost(start_x_monster_2, 417, end, lives, 0, IA, 1)
        elif monster_name == list_monsters[1]:
            monster = Golem(start_x_monster_2, 410, end, lives, 0, IA, -1)
        elif monster_name == list_monsters[2]:
            monster = Human(start_x_monster_2, 420, end, lives, 0, IA, -1)
        else:
            monster = Goblin(start_x_monster_2, 430, end, lives, 0, IA, -1)

    return monster
예제 #2
0
 def generateInteractuatorHuman(self, human, availableId):
     a = math.pi * human.angle / 180.  #a radianes
     dist = float(QtCore.qrand() % 300 + 50)
     human2 = None
     while human2 is None:
         if time.time() - self.generation_time > MAX_GENERATION_WAIT:
             raise RuntimeError('MAX_GENERATION_ATTEMPTS')
         xPos = human.xPos + dist * math.sin(a)
         yPos = human.yPos - dist * math.cos(a)
         l = [1, -1]
         option = random.choice(l)
         angle = human.angle + 180 + (option * QtCore.qrand() % 25)
         # print('angle human2:', angle)
         if angle > 180.: angle = -360. + angle
         # print('angle human2 normalize:', angle)
         angleHead = angle + random.choice([-1, 1]) * QtCore.qrand() % 100
         human2 = Human(availableId, xPos, yPos, angle, angleHead)
         if not self.room.containsPolygon(human2.polygon()):
             dist -= 5
             if dist < 20:
                 human.setAngle(human.angle + 180)
                 a = math.pi * human.angle / 180.
                 dist = float(QtCore.qrand() % 300 + 50)
             human2 = None
     return human2
예제 #3
0
    def __init__(self):
        # determine if single player, multiplayer or simulation
        self.games_to_play = 3
        print("Press 1 for single player:")
        print("Press 2 for head to head play")
        print("Press 3 to watch computers duel")
        #input validation
        while True:
            try:
                choice = int(input())
                if choice < 1 or choice > 3:
                    print(
                        "oops we need a number between 1 and 3 please try again"
                    )
                else:
                    break
            except ValueError:
                print("oops we need a number between 1 and 3 please try again")
        #creating the players
        if choice == 1:
            self.player_one = Human()
            self.player_two = Computer("Player 2")
            self.game_set()

        elif choice == 2:
            self.player_one = Human()
            self.player_two = Human()
            self.game_set()
        else:
            self.player_one = Computer("Player 1")
            self.player_two = Computer("Player 2")
            self.game_set()
예제 #4
0
파일: game.py 프로젝트: ZooDoz/Python4NN
    def start(self):
        board = Board()
        board.init_board()

        if randint(1, 2) == 1:
            p1 = 1
            p2 = 2
        else:
            p1 = 2
            p2 = 1

        ai = Human("ai", p1)
        human = Human("human", p2)

        players = {}
        players[p1] = ai
        players[p2] = human

        play_turn = [p1, p2]

        while (1):
            player = board.get_player(play_turn)
            move = players[player].get_action(board, play_turn)
            board.update(player, move)
            self.graphic(board, human, ai)
            end, winner = self.game_end(board)
            if end:
                if winner != -1:
                    print("Game end. Winner is", players[winner].type)
                break
예제 #5
0
파일: main.py 프로젝트: 1314liuwei/PyQt5
class QmyWideget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self._ui = Ui_Widget()
        self._ui.setupUi(self)  # 创建UI

        self.human = Human(18, '小明')  # 绑定自定义信号
        self.human.nameChanged.connect(self.my_nameChanged)
        self.human.ageChanged[int].connect(self.my_ageChanged_int)
        self.human.ageChanged[str].connect(self.my_ageChanged_str)

    # ============自定义槽函数============
    def my_nameChanged(self, name):  # nameChanged(str)响应
        self._ui.lineEdit_nameStr.setText('Hello, %s!' % name)

    @pyqtSlot(int)
    def my_ageChanged_int(self, age):  # ageChanged(int)响应
        self._ui.lineEdit_ageInt.setText(str(age))

    @pyqtSlot(str)
    def my_ageChanged_str(self, info):  # ageChanged(str)响应
        self._ui.lineEdit_ageStr.setText(info)

    # ============自动关联槽函数============
    def on_slider_SetAge_valueChanged(self, value):  # 滑块改变年龄
        self.human.setAge(value)

    def on_pushButton_clicked(self):  # 设置姓名
        name = self._ui.lineEdit_inputName.text()
        self.human.setName(name)
예제 #6
0
    def	search_spouce(self):
        def success_marry_chanse(person1, person2):
            attraction = (genetics.lust_coef(person1.age.year) *
                          genetics.lust_coef(person2.age.year))
            genes_difference = person1.compare_genes(person2)
            attraction = attraction/genes_difference # шанс пожениться больше у людей с похожими геномами
            return attraction >= random.random()

        # если есть возможность создать хоть одну пару
        if min(self.stat.unmarried_adult_men_number, self.stat.unmarried_adult_women_number) > 0:
            s = f'Холостых мужчин: {self.stat.unmarried_adult_men_number}\nХолостых женщин: {self.stat.unmarried_adult_women_number}'
            Human.write_chronicle(s)
            # Проходимся по тому полу, которого меньше в штуках
            if self.stat.unmarried_adult_men_number < self.stat.unmarried_adult_women_number:
                a = self.stat.unmarried_adult_men
                b = self.stat.unmarried_adult_women
            else:
                b = self.stat.unmarried_adult_men
                a = self.stat.unmarried_adult_women
            random.shuffle(b)
            # за один раз можно попытать счастья только с одним избранником
            # цикл идет по представителям пола, который сейчас в меньшинстве
            for person in a:
                if person.close_ancestors.isdisjoint(b[-1].close_ancestors): # если не являются близкими родственниками
                    if success_marry_chanse(person, b[-1]):
                        self.marry(person, b[-1])
                    b.pop() # человек удаляется из списка кандидатов в супруги независтмо от того, заключил он брак или нет
예제 #7
0
파일: myWidget.py 프로젝트: ml0042993/PyQt5
class QmyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Widget()
        self.ui.setupUi(self)

        self.boy = Human("Boy", 16)
        #创建三个连接,将实例中的三个信号与3个自定义槽函数关联
        self.boy.nameChanged.connect(self.do_nameChanged)
        self.boy.ageChanged.connect(self.do_ageChanged_int)
        self.boy.ageChanged[str].connect(self.do_ageChanged_str)

##===========由connectSoltByName()自动与组件的信号关联的槽函数=======

    def on_sliderSetAge_valueChanged(self, value):
        #注意自动关联的槽函数的书写格式,不能随意改变
        self.boy.setAge(value)

    def on_btnSetName_clicked(self):
        hisName = self.ui.editNameInput.text()
        self.boy.setName(hisName)


##=======自定义槽函数======

    def do_nameChanged(self, name):
        self.ui.editNameHello.setText("Hello," + name)

    @pyqtSlot(int)
    def do_ageChanged_int(self, age):
        self.ui.editAgeInt.setText(str(age))

    @pyqtSlot(str)
    def do_ageChanged_str(self, info):
        self.ui.editAgeStr.setText(info)
예제 #8
0
def alien_battle():
  human = Human()
  alien = Alien()

  print("There is an human in front of you")
  action = input("What will you do run to ship or shot the human? (run / shoot): ")

  while alien.distance > 0 or human.health > 0 or alien.lifeForce > 0:

    if action == "run":
      alien.run()
      human.attack(human)
    elif action == "shoot":
      alien.alienAttack(human)
      human.attack(alien)
      

    if alien.distance == 0:
      print("You made it to the ship!")
      print("The Game is now over!")
      break
    elif human.health == 0:
      print("You killed the human!")
      print("The Game is now over!")
      break
    elif alien.lifeForce == 0:
      print("The human kills you!")
      print("The Game is now over!")
      break

    print("Distance to ship is: " + str(alien.distance) + " feet!")
    print("Human Life is: " + str(human.health))
    print("Alien life is: " + str(alien.lifeForce)) 

    action = input("What will you do run to bunker or shot the human? (run / shoot) ")
예제 #9
0
 def playerpick(self):
     print 'PLAYERPICK EXECUTED'
     player1 = raw_input('Player 1: ').lower()
     player2 = raw_input('Player 2: ').lower()
     # Add ends to this list as they are created
 
     if player1 == 'human':
         from human import Human
         self.player1 = Human(1, self)
     elif player1 == 'roteai':
         raise RuntimeError
     elif player1 == 'learnai':
         #player1 = learnAI()
         pass
     else:
         from human import Human
         self.player1 = Human(1, self)
 
     if player2 == 'human':
         from human import Human
         self.player2 = Human(2, self)
     elif player2 == 'roteai':
         raise RuntimeError
     elif player2 == 'learnai':
         #player2 = learnAI()
         pass
     else:
         from human import Human
         player2 = Human(2, self)
     
     print
예제 #10
0
 def generateComplementaryHuman(self, human, availableId):
     a = math.pi * human.angle / 180.
     #dist = float(QtCore.qrand()%300+50)
     dist = int(random.uniform(105, 225))  #Original: 65 y 225
     xa = int(random.uniform(0, 10))
     human2 = None
     while human2 is None:
         if time.time() - self.generation_time > MAX_GENERATION_WAIT:
             raise RuntimeError('MAX_GENERATION_ATTEMPTS')
         if (xa == 9 or xa == 8):  # Generación totalmente aleatoria
             xPos = QtCore.qrand() % 400 - 200
             yPos = QtCore.qrand() % 400 - 200
             human2 = Human(availableId, xPos, yPos,
                            (QtCore.qrand() % 360) - 180)
         else:
             xPos = (human.xPos + dist * math.sin(a))
             yPos = (human.yPos - dist * math.cos(a))
             c = human.angle + 180
             c_1 = (human.angle + 180) + 60  # Amplitud de 60
             c_2 = (human.angle + 180) - 60  # Amplitud de 60
             d = int(random.uniform(c_1, c_2))
             human2 = Human(availableId, xPos, yPos, d)
         if not self.room.containsPolygon(human2.polygon()):
             dist -= 5  # Original 30
             if dist < 30:
                 human.setAngle(human.angle + 180)
                 a = math.pi * human.angle / 180.
                 dist = float(random.uniform(105, 225))  # Original: 55 y 65
                 #dist = float(QtCore.qrand()%300+50)
             human2 = None
     return human2
예제 #11
0
    def test_find(self):
        s = Station(1)
        h = Human(1, s)
        _ = Cat(1, s)

        with self.assertRaises(LoveException):
            h.search()
예제 #12
0
 def player_creator(self, choice):
     if choice == 1:
         self.player_one = Human()
         self.player_two = Computer()
     elif choice == 2:
         self.player_one = Human()
         self.player_one = Human()
예제 #13
0
    def __init__(self):
        self.p1 = None
        self.p2 = None
        self.moves = []

        while True:
            p1 = raw_input('player 1: human or cpu?\n')
            if p1 == 'human' or p1 == 'cpu':
                break
            else:
                print "error, please enter 'human' or 'cpu'"
        if p1 == 'human':
            self.p1 = Human(1)
        else:
            self.p1 = CPU(1)

        while True:
            p2 = raw_input('player 2: human or cpu?\n')
            if p2 == 'human' or p2 == 'cpu':
                break
            else:
                print "error, please enter 'human' or 'cpu'"
        if p2 == 'human':
            self.p2 = Human(2)
        else:
            self.p2 = CPU(2)

        while True:
            out = raw_input('how many games?\n')
            try:
                self.num_games = int(out)
                break
            except:
                print 'error, please enter a number'
예제 #14
0
파일: gui.py 프로젝트: F1000Research/yeadon
 def _update_measurement_file_name(self):
     # Must convert to str (from unicode), because Human parses it
     # differently depending on its type, and there's no consideration for
     # it being unicode.
     self.H = Human(str(self.measurement_file_name))
     self.scene.mlab.clf()
     self._init_draw_human()
예제 #15
0
class QmyWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)  #调用父类构造函数,创建窗体
        self.ui = Ui_Widget()  #创建UI对象
        self.ui.setupUi(self)  #构造UI界面

        self.boy = Human("Boy", 16)
        self.boy.nameChanged.connect(self.do_nameChanged)

        self.boy.ageChanged.connect(self.do_ageChanged_int)
        self.boy.ageChanged[str].connect(self.do_ageChanged_str)

## 由connectSlotsByName() 自动与组件的信号连接的槽函数

    def on_sliderSetAge_valueChanged(self, value):
        self.boy.setAge(value)

    def on_btnSetName_clicked(self):
        hisName = self.ui.editNameInput.text()
        self.boy.setName(hisName)


## 自定义槽函数

    def do_nameChanged(self, name):
        self.ui.editNameHello.setText("Hello," + name)

    @pyqtSlot(int)
    def do_ageChanged_int(self, age):
        self.ui.editAgeInt.setText(str(age))

    @pyqtSlot(str)
    def do_ageChanged_str(self, info):
        self.ui.editAgeStr.setText(info)
예제 #16
0
    def __init__(self, anno=1000, estimate_people=100):
        # список всех людей в социуме, на данный момент включая мертвых (проверить)
        self.roll_genome()

        Socium.class_var_init(estimate_people)
        Human.init_files()
        Family.init_files()
        FoodDistribution.init_files()
        self.soc_list: List[Human] = list()
        self.families: List[Family] = list()

        self.stat = statistics.Soc_stat(self)
        self.soc_food = FoodDistribution(self)

        self.person_stat_file = open('./person_features_table.csv', 'w', encoding="UTF16")
        self.person_stat = csv.writer(self.person_stat_file, delimiter='\t', lineterminator='\n')
        pers_stat_header = list()
        for i in genetics.GN:
            pers_stat_header.append(i)
        hextend = ['макс. возр. отца', 'возр. отца при рождении', 'макс. возр. матери', 'возр. матери при рождении', 'каким по счету родился', 'кол-во супругов', 'кол-во детей', 'возраст смерти']
        pers_stat_header.extend(hextend)
        self.person_stat.writerow(pers_stat_header)
        # текущий год
        self.anno: Anno = Anno(anno)
        # локальный счетчик смертей, после появления чужака обнуляется
        self.short_death_count: int = 0
        # общий счетчик смертей
        self.global_death_count: int = 0
        # давно умершие родственники (чтобы зря не крутить большие циклы)
        self.forgotten: List = []
        self.people_alive: List = []
예제 #17
0
파일: gui.py 프로젝트: F1000Research/yeadon
 def __init__(self, meas_in=None):
     HasTraits.__init__(self, trait_value=True)
     if meas_in:
         measurement_file_name = meas_in
     else:
         measurement_file_name = 'Path to measurement input text file.'
     self.H = Human(meas_in if meas_in else self.measPreload)
     self._init_draw_human()
예제 #18
0
파일: main.py 프로젝트: 1314liuwei/PyQt5
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self._ui = Ui_Widget()
        self._ui.setupUi(self)  # 创建UI

        self.human = Human(18, '小明')  # 绑定自定义信号
        self.human.nameChanged.connect(self.my_nameChanged)
        self.human.ageChanged[int].connect(self.my_ageChanged_int)
        self.human.ageChanged[str].connect(self.my_ageChanged_str)
예제 #19
0
    def __init__(self,name='DEFAULT',logger=util.generic_logger):
        if name=='BERTNERNIE':

            modA  = DestinyModule()
            modDock = UnityModule()    
            modB   = ZvezdaModule()
            modDrag = DragonCargoModule()
            modDrag.setup_simple_resupply()
                   
            self.station = Station(modDock, "BnE Station", logger)
            self.station.berth_module(None,None,modB, None, True)
            self.station.berth_module(None,None,modA, None, True)    
            self.station.berth_module(None,None,modDrag, None, True)
            
            '''rob = Robot('Robby')     
            rob.station = station
            station.actors[rob.id]=rob
            rob.location = modB.node('hall0')
            rob.xyz = modB.location'''
            
            ernie = Human('Ernest',station=self.station,logger=self.station.logger)
            self.station.actors[ernie.id] = ernie
            ernie.location = modA.node('hall0')
            ernie.xyz = modA.location
            
            bert = Human('Bertholomew',station=self.station,logger=self.station.logger)
            self.station.actors[bert.id] = bert
            bert.location = modB.node('hall0')
            bert.xyz = modB.location
            
            ernie.needs['WasteCapacityLiquid'].amt=0.1
            ernie.needs['Food'].set_amt_to_severity('HIGH')
            ernie.nutrition = [0.5, 0.5, 0.5, 0.5, 0.5]
            #modB.equipment['Electrolyzer'][3].broken=True

        elif name == 'DOCKINGTEST':
            '''Ernie, in a station badly needing resupply, gets a Dragon shipment.
                He installs a docking computer, docks Dragon, unloads food, loads waste, undocks Dragon, Dragon reenters'''
   
            modB   = ZvezdaModule()
            self.station = Station(modB, "Docker Station", logger)
            
            modDrag = DragonCargoModule()
            modDrag.setup_simple_resupply()
                       
            #TODO: position Dragon on "docking" approach, add docking task
            self.station.begin_docking_approach(modDrag)
            print modDrag.location, modDrag.orientation
            
            ernie = Human('Ernest',station=self.station,logger=self.station.logger)
            self.station.actors[ernie.id] = ernie
            ernie.location = modB.node('hall0')
            ernie.xyz = modB.location
                                    
        else: #'DEFAULT'
            modDock = UnityModule()                   
            self.station = Station(modDock, 'NewbieStation',logger)
예제 #20
0
 def __init__(self):
     self.menuOptions = [
         "1P Game", "2P Game", "Game Setup", "Rules / Help", "Exit Game"
     ]
     self.p1 = Player("P1")
     self.p2 = Player("P2")
     self.bestOf = 3
     self.mode = "RPSLS"
     self.gameOptions = ["Toggle P1AI", "Toggle RPS Classic Mode"]
     self.p1AI = False
예제 #21
0
    def __init__(self, parent=None):
        super().__init__(parent)  #调用父类构造函数,创建窗体
        self.ui = Ui_Widget()  #创建UI对象
        self.ui.setupUi(self)  #构造UI界面

        self.boy = Human("Boy", 16)
        self.boy.nameChanged.connect(self.do_nameChanged)

        self.boy.ageChanged.connect(self.do_ageChanged_int)
        self.boy.ageChanged[str].connect(self.do_ageChanged_str)
예제 #22
0
파일: myWidget.py 프로젝트: ml0042993/PyQt5
    def __init__(self):
        super().__init__()
        self.ui = Ui_Widget()
        self.ui.setupUi(self)

        self.boy = Human("Boy", 16)
        #创建三个连接,将实例中的三个信号与3个自定义槽函数关联
        self.boy.nameChanged.connect(self.do_nameChanged)
        self.boy.ageChanged.connect(self.do_ageChanged_int)
        self.boy.ageChanged[str].connect(self.do_ageChanged_str)
예제 #23
0
 def __init__(self, root):
     self.__root = root
     self.__board = Board(root)
     self.__bag = Bag()
     self.__human = Human(root)
     self.__ai = Ai(root, self.__board, self.__bag)
     self.__turn = 1
     self.__player = self.__human
     self.__human_score = StringVar()
     self.__ai_score = StringVar()
예제 #24
0
파일: main.py 프로젝트: jessep13/car
def setup():
  print("\033c")
  print("Please enter in the following information: ")
  name = input("What is your name: ")
  age = int(input("What is your age: "))
  while not validSetup(age):
    age = int(input("What is your age: "))
  gender = input("what is your gender: ")
  person = Human(name, age, gender)
  person.test()
예제 #25
0
    def test_move(self):
        test_human = Human("James", energy=50)
        self.assertEqual(test_human.move(50), True, "Return should be true.")

        test_human = Human("James", energy=50)
        self.assertEqual(test_human.move(60), False, "Return should be false.")

        test_human = Human("James", energy=50)
        test_human.move(30)
        self.assertEqual(test_human.energy, 20, "Energy should be thirty.")
예제 #26
0
 def __init__(self, name, age, father, mother):
     Human.__init__(self, name, age)
     if isinstance(father, Father):
         self.father = father
     else:
         raise ValueError('Father must be of a type Father')
     if isinstance(mother, Mother):
         self.mother = mother
     else:
         raise ValueError('Mother must be of a type Mother')
예제 #27
0
 def create_players(self, player1_response, player2_response):
     player1 = player1_response.rstrip().lower()
     player2 = player2_response.rstrip().lower()
     if player1 == "human":
         self.player1 = Human("X", self.io)
     else:
         self.player1 = Computer("X")
     if player2 == "human":
         self.player2 = Human("O", self.io)
     else:
         self.player2 = Computer("O")
예제 #28
0
 def __init__(self, *args, **kwargs):
     # Cách điển hình để thừa kế thuộc tính là gọi super
     # super(Batman, self).__init__(*args, **kwargs)
     # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO.
     # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả.
     # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn,
     # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó
     Human.__init__(self, 'anonymous', *args, **kwargs)
     Bat.__init__(self, *args, can_fly=False, **kwargs)
     # ghi đè giá trị của thuộc tính name
     self.name = 'Sad Affleck'
    def __init__(self, model, boxsize):
        """
        Class constructor.
        @param model: caffe models
        @param weights: caffe models weights
        """
        Human.__init__(self, boxsize)

        # Reshapes the models input accordingly
        self.model, self.weights = model
        self.net = None
예제 #30
0
 def define_contestants(self):
     # prompts user to pick a human or ai opponent
     self.opening_statement()
     opponent = input("\nPress 1 to play against a Human or type anything else to play against an AI"
                      "\n >")
     if opponent == '1':
         self.player_one = Human()
         self.player_two = Human()
     else:
         self.player_one = Human()
         self.player_two = Ai()
예제 #31
0
 def marry(self, person, engaged):
     tup = (person.id, engaged.id, person.name.display(), person.age.year, engaged.name.display(), engaged.age.year)
     Human.write_chronicle(Human.chronicle_marriage.format(*tup))
     pair:List[Human] = [person, engaged]
     male_index = None # определяем семьи мужчины и женщины, чтобы правильно их соединить
     for p in range(2):
         pair[p].spouses.marry(pair[1 - p])
         pair[p].score.update(pair[p].score.MARRY_SCORE)
         if pair[p].gender is common.Gender.MALE:
             male_index = p
     pair[male_index].family.unite_families(pair[1 - male_index].family)
예제 #32
0
    def test_human_move(self):
        s1 = Station(1)
        s2 = Station(2)
        h = Human(1, s1)

        s1.add_connection(s2)
        self.assertEqual(h.state, s1)
        self.assertEqual(h.memory, [s1])
        h.action()
        self.assertEqual(h.state, s2)
        self.assertEqual(h.memory, [s1, s2])
예제 #33
0
 def __init__(self, *args, **kwargs):
     # Typically to inherit attributes you have to call super:
     #super(Batman, self).__init__(*args, **kwargs)      
     # However we are dealing with multiple inheritance here, and super()
     # only works with the next base class in the MRO list.
     # So instead we explicitly call __init__ for all ancestors.
     # The use of *args and **kwargs allows for a clean way to pass arguments,
     # with each parent "peeling a layer of the onion".
     Human.__init__(self, 'anonymous', *args, **kwargs)
     Bat.__init__(self, *args, can_fly=False, **kwargs)
     # override the value for the name attribute
     self.name = 'Sad Affleck'
예제 #34
0
 def run_game(self):
     multiplayer = self.multiplayer()
     rounds_to_win = self.rounds()
     if multiplayer:
         self.player_two = Human("Player Two")
     while self.player_one.wins < rounds_to_win and self.player_two.wins < rounds_to_win:
         self.player_choice_prompt(self.player_one)
         if self.player_two.name == "Player Two":
             self.player_choice_prompt(self.player_two)
         else:
             self.computer_choice()
         self.results()
     self.display_winner()
예제 #35
0
 def __init__(self, window, players=[Human(1), Human(2)], theme_mode=0):
     """Chess board."""
     self.name = "Chess"
     self.theme_mode = theme_mode
     self.loadThemes()
     self.window = window
     self.window.name = self.name
     if not self.window.built:
         self.window.build()
     self.players = players
     self.board = Board()
     self.cursor = None
     self.click = None
예제 #36
0
def run_game():
    """
    runs the game :D
    """
    game_board = Board()

    player1 = Human("1")
    player2 = AI("2")
    print(player1, "vs", player2)
    # players_turn = 1

    while not game_board.has_winner:
        col = player1.get_move(game_board)
        game_board.add_piece(col, player1.piece)
        col = player2.get_move(game_board)
        game_board.add_piece(col, player2.piece)
        game_board.print_board()
예제 #37
0
    def __init__(self, humanBoard, computerBoard, humanScore, computerScore, 
                            humanIsFirstPlayer, humanIsNext, diceQueue, didLoad):
        self.human = Human(humanScore)
        self.computer = Computer(computerScore)
        self.diceQueue = diceQueue
        self.humanIsFirstPlayer = humanIsFirstPlayer
        self.humanIsNext = humanIsNext
        self.exitCode = 0
        self.board = Board(humanBoard, computerBoard)
        self.turnCount = 0
        self.returnList = [False, 0, 0]

        if didLoad:
            self.resumeRound()
        else:
            self.newRound()
예제 #38
0
    def __init__(self):
        sf.Drawable.__init__(self)

        self.objects = []

        self.tt = sf.Time()

        self.mobs = []
        self.mobs.append(Mob(ETTIN))
        self.mobs.append(Mob(BARLOG))
        self.mobs.append(Mob(CYCLOPS))
        self.mobs.append(Mob(DEMON))
        self.mobs.append(Mob(STONEGOLEM))
        self.mobs.append(Mob(TIGERWORM))

        self.mobs[0].position = (100, 150)
        self.mobs[1].position = (650, 150)
        self.mobs[2].position = (100, 350)
        self.mobs[3].position = (200, 550)
        self.mobs[4].position = (600, 350)
        self.mobs[5].position = (600, 550)

        self.player = Human()
        self.player.position = (350, 350)

        for mob in self.mobs:
            for i in range(3):
                for a in range(5):
                    for d in range(8):
                        mob.pending_actions.insert(0, (a, d, 1000))

        for a in range(12):
            for d in range(8):
                self.player.pending_actions.insert(0, (a, d, 1000))

        for a in range(12):
            for d in range(8):
                self.player.pending_actions.insert(0, (a, d, 1000))
예제 #39
0
 def loadModels(self):
     """loadModels
     parameters:
         self
     returns:
         none
     Description:
         Loads the models and related collisions. Most game init goes here.
     """
     # create the environment
     self.env = collision.loadAndPositionModelFromFile("../assets/3d/mayaActors/arena_collisions_nogrid.egg")
     self.envBoxes = objects.genBulletBoxes(self.env,self.world)
     #load objects out of the environment
     #human
     self.mover = Human(self,self.world,self.worldNP)
     tmp = self.env.find("**/PlayerSpawn1")
     self.mover.bulletInit(self.world,tmp.getPos())
     tmp.detachNode()
     #AI players
     self.players = objects.loadPlayers(self.env,self.world,self.worldNP)
     for i in range(0,5):
         self.players[i].bulletInit(self.world,self.players[i].instance.getPos())
     
     #Spawners
     collisionHandler=0
     self.aTrapSpawn = objects.loadTrapAs(self.env, self.world, self.worldNP)
     self.bTrapSpawn = objects.loadTrapBs(self.env, self.world, self.worldNP)
     self.ammoSpawn = objects.loadAmmo(self.env, self.world, self.worldNP)
     
     #optimization
     self.env.flattenStrong()
     render.analyze()
     
     self.crowd = loader.loadModel("../assets/3d/Actors/crowd.egg")
     self.crowd.reparentTo(render)
     self.crowd.setScale(10)
     self.crowd.setPos(0,0,-1000)
예제 #40
0
class World(DirectObject):
    global traverser, queue
    def __init__(self):
        startMenu = menu.Menu(self)
    
    #Please do not remove this function, it makes the menu work.
    def beginGame(self):
        """beginGame
        parameters:
            self
        returns:
            none
        Description:
            What would normalley be the contants of __init__. Called only after the menu.
        """
        self.configurePanda()
        camera.setPosHpr(0, -15, 0, 0, 0, 0) # x,y,z,heading, pitch, roll
        #world init
        self.setupBullet()
        self.loadModels()
        self.setupLights()
        #self.initMove()
        self.accept("escape",sys.exit)
                
        self.overlay = overlay.Overlay(self)
        #self.ball = ball.Ball(self)

        self.onRay = list()
        self.offRay = list()
        self.activeRay = list()
    def configurePanda(self):
        """configurePanda
        parameters:
            self
        returns:
            none
        Description:
            Set the rendering and display options for panda.
        """
        props = WindowProperties()
        props.setCursorHidden(True) 
        #props.setSize(1440, 900)
        #props.setFullscreen(1) 
        base.win.requestProperties(props)
        render.setShaderAuto()
        base.disableMouse()
        base.setFrameRateMeter(True)
        #render.setAntialias(AntialiasAttrib.MAuto)
        #render.setAntialias(AntialiasAttrib.MMultisample,4)
        self.filters = CommonFilters(base.win, base.cam)
        self.filters.setBloom(blend=(1,0,0,1), desat=-0.5, intensity=6.0, size=2)
        #self.filters.setAmbientOcclusion()
        #self.filters.setCartoonInk()
    def setupBullet(self):
        """setupBullet
        parameters:
            self
        returns:
            none
        Description:
            Initialize bullet and (if needed) the bullet debug renderer.
        """
        taskMgr.add(self.update, 'updateWorld')
        self.worldNP = render.attachNewNode('World')
        # World
        #self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        #self.debugNP.show()
        #self.debugNP.node().showWireframe(True)
        #self.debugNP.node().showConstraints(False)
        #self.debugNP.node().showBoundingBoxes(False)
        #self.debugNP.node().showNormals(False)
        
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, 0))
        #self.world.setDebugNode(self.debugNP.node())
        
    def loadModels(self):
        """loadModels
        parameters:
            self
        returns:
            none
        Description:
            Loads the models and related collisions. Most game init goes here.
        """
        # create the environment
        self.env = collision.loadAndPositionModelFromFile("../assets/3d/mayaActors/arena_collisions_nogrid.egg")
        self.envBoxes = objects.genBulletBoxes(self.env,self.world)
        #load objects out of the environment
        #human
        self.mover = Human(self,self.world,self.worldNP)
        tmp = self.env.find("**/PlayerSpawn1")
        self.mover.bulletInit(self.world,tmp.getPos())
        tmp.detachNode()
        #AI players
        self.players = objects.loadPlayers(self.env,self.world,self.worldNP)
        for i in range(0,5):
            self.players[i].bulletInit(self.world,self.players[i].instance.getPos())
        
        #Spawners
        collisionHandler=0
        self.aTrapSpawn = objects.loadTrapAs(self.env, self.world, self.worldNP)
        self.bTrapSpawn = objects.loadTrapBs(self.env, self.world, self.worldNP)
        self.ammoSpawn = objects.loadAmmo(self.env, self.world, self.worldNP)
        
        #optimization
        self.env.flattenStrong()
        render.analyze()
        
        self.crowd = loader.loadModel("../assets/3d/Actors/crowd.egg")
        self.crowd.reparentTo(render)
        self.crowd.setScale(10)
        self.crowd.setPos(0,0,-1000)
    def setupLights(self):
        """setupLights
        parameters:
            self
        returns:
            none
        Description:
            Stick in some general lights.
        """
        self.ambientLight = lights.setupAmbientLight()
        
        self.dirLight = DirectionalLight("dirLight")
        self.dirLight.setColor((.4,.4,.4,1))
        self.dirLightNP = render.attachNewNode(self.dirLight)
        self.dirLightNP.setHpr(0,-25,0)
        render.setLight(self.dirLightNP)
        
        #self.light = lights.loadModelSpotlightByName(self.human,"humanlight","humanlight1","segwaLight")
        
        #panda2 = collision.loadAndPositionModelFromFile("panda-model",scale=.005,pos=tifLeftLight.getPos())
        
    def update(self, task):
        """update
        parameters:
            self
        returns:
            none
        Description:
            Game Loop
        """
        dt = globalClock.getDt()
        # Update the spawners
        for i in self.aTrapSpawn:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.trap1Collide(contacts,self.mover)
        for i in self.bTrapSpawn:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.trap2Collide(contacts,self.mover)
        for i in self.ammoSpawn:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.ammoCollide(contacts,self.mover)
        # update the traps and projectiles
        for i in human.floatTrap.traps:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.check(contacts,self.mover,self.players)
        for i in human.clawTrap.traps:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.check(contacts,self.mover,self.players)
        for i in Projectile.projectiles:
            contacts = self.world.contactTest(i.sphere).getContacts()
            if len(contacts)>0:
                i.check(contacts,self.mover,self.players)
        # step forward the physics simulation
        self.world.doPhysics(dt,1)
        
        return task.cont
예제 #41
0
파일: gui.py 프로젝트: F1000Research/yeadon
class YeadonGUI(HasTraits):
    """A GUI for the yeadon module, implemented using the traits package."""

    # Input.
    measurement_file_name = File()

    # Drawing options.
    show_mass_center = Bool(False)
    show_inertia_ellipsoid = Bool(False)

    # Configuration variables.
    opts = {'enter_set': True, 'auto_set': True, 'mode': 'slider'}
    for name, bounds in zip(Human.CFGnames, Human.CFGbounds):
        # TODO : Find a better way than using locals here, it may not be a good
        # idea, but I don't know the consequences.
        locals()[name] =  Range(float(rad2deg(bounds[0])),
            float(rad2deg(bounds[1])), 0.0, **opts)

    reset_configuration = Button()

    # Display of Human object properties.
    Ixx = Property(Float, depends_on=sliders)
    Ixy = Property(Float, depends_on=sliders)
    Ixz = Property(Float, depends_on=sliders)
    Iyx = Property(Float, depends_on=sliders)
    Iyy = Property(Float, depends_on=sliders)
    Iyz = Property(Float, depends_on=sliders)
    Izx = Property(Float, depends_on=sliders)
    Izy = Property(Float, depends_on=sliders)
    Izz = Property(Float, depends_on=sliders)
    x = Property(Float, depends_on=sliders)
    y = Property(Float, depends_on=sliders)
    z = Property(Float, depends_on=sliders)

    scene = Instance(MlabSceneModel, args=())

    input_group = Group(Item('measurement_file_name'))

    vis_group = Group(Item('scene',
        editor=SceneEditor(scene_class=MayaviScene), height=580, width=430,
        show_label=False))

    config_first_group = Group(
            Item('somersault'),
            Item('tilt'),
            Item('twist'),
            Item('PTsagittalFlexion', label='PT sagittal flexion'),
            Item('PTbending', label='PT bending'),
            Item('TCspinalTorsion', label='TC spinal torsion'),
            Item('TCsagittalSpinalFlexion',
                label='TC sagittal spinal flexion'),
            label='Whole-body, pelvis, torso',
            dock='tab',
            )
    config_upper_group = Group(
            Item('CA1extension', label='CA1 extension'),
            Item('CA1adduction', label='CA1 adduction'),
            Item('CA1rotation', label='CA1 rotation'),
            Item('CB1extension', label='CB1 extension'),
            Item('CB1abduction', label='CB1 abduction'),
            Item('CB1rotation', label='CB1 rotation'),
            Item('A1A2extension', label='A1A2 extension'),
            Item('B1B2extension', label='B1B2 extension'),
            label='Upper limbs',
            dock='tab',
            )
    config_lower_group = Group(
            Item('PJ1extension', label='PJ1 extension'),
            Item('PJ1adduction', label='PJ1 adduction'),
            Item('PK1extension', label='PK1 extension'),
            Item('PK1abduction', label='PK1 abduction'),
            Item('J1J2flexion', label='J1J2 flexion'),
            Item('K1K2flexion', label='K1K2 flexion'),
            label='Lower limbs',
            dock='tab',
            )
    config_group = VGroup(
            Label('Configuration'),
            Group(config_first_group, config_upper_group, config_lower_group,
                layout='tabbed',
                ),
            Item('reset_configuration', show_label=False),
            Label('P: pelvis (red); T: thorax (orange); C: chest-head (yellow)'),
            Label('A1/A2: left upper arm/forearm-hand; B1/B2: right arm'),
            Label('J1/J2: left thigh/shank-foot; K1/K2: right leg'),
            show_border=True,
            )

    inertia_prop = VGroup(
            Label('Mass center (from origin of coord. sys.) (m):'),
            HGroup(
                Item('x', style='readonly', format_func=format_func),
                Item('y', style='readonly', format_func=format_func),
                Item('z', style='readonly', format_func=format_func)
                ),
            Label('Inertia tensor (about origin, in basis shown) (kg-m^2):'),
            HSplit( # HSplit 2
                Group(
                    Item('Ixx', style='readonly', format_func=format_func),
                    Item('Iyx', style='readonly', format_func=format_func),
                    Item('Izx', style='readonly', format_func=format_func),
                    ),
                Group(
                    Item('Ixy', style='readonly', format_func=format_func),
                    Item('Iyy', style='readonly', format_func=format_func),
                    Item('Izy', style='readonly', format_func=format_func),
                    ),
                Group(
                    Item('Ixz', style='readonly', format_func=format_func),
                    Item('Iyz', style='readonly', format_func=format_func),
                    Item('Izz', style='readonly', format_func=format_func)
                    ),
                ), # end HSplit 2
            Label('X, Y, Z axes drawn as red, green, blue arrows, respectively.'),
                show_border=True,
            ) # end VGroup

    view = View(
            VSplit(
                input_group,
                HSplit(vis_group,
                    VSplit(
                        config_group,
                        Item('show_mass_center'),
                        Item('show_inertia_ellipsoid'),
                        inertia_prop
                        )
                    ),
                ),
            resizable=True,
            title='Yeadon human inertia model'
            ) # end View

    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 }

    def __init__(self, meas_in=None):
        HasTraits.__init__(self, trait_value=True)
        if meas_in:
            measurement_file_name = meas_in
        else:
            measurement_file_name = 'Path to measurement input text file.'
        self.H = Human(meas_in if meas_in else self.measPreload)
        self._init_draw_human()

    def _init_draw_human(self):
        self.H.draw(self.scene.mlab, True)

        if self.show_mass_center:
            self.H._draw_mayavi_mass_center_sphere(self.scene.mlab)

        if self.show_inertia_ellipsoid:
            self.H._draw_mayavi_inertia_ellipsoid(self.scene.mlab)

    @on_trait_change('scene.activated')
    def set_view(self):
        """Sets a reasonable camera angle for the intial view."""
        self.scene.mlab.view(azimuth=90.0, elevation=-90.0)

    def _get_Ixx(self):
        return self.H.inertia[0, 0]

    def _get_Ixy(self):
        return self.H.inertia[0, 1]

    def _get_Ixz(self):
        return self.H.inertia[0, 2]

    def _get_Iyx(self):
        return self.H.inertia[1, 0]

    def _get_Iyy(self):
        return self.H.inertia[1, 1]

    def _get_Iyz(self):
        return self.H.inertia[1, 2]

    def _get_Izx(self):
        return self.H.inertia[2, 0]

    def _get_Izy(self):
        return self.H.inertia[2, 1]

    def _get_Izz(self):
        return self.H.inertia[2, 2]

    def _get_x(self):
        return self.H.center_of_mass[0, 0]

    def _get_y(self):
        return self.H.center_of_mass[1, 0]

    def _get_z(self):
        return self.H.center_of_mass[2, 0]

    @on_trait_change('measurement_file_name')
    def _update_measurement_file_name(self):
        # Must convert to str (from unicode), because Human parses it
        # differently depending on its type, and there's no consideration for
        # it being unicode.
        self.H = Human(str(self.measurement_file_name))
        self.scene.mlab.clf()
        self._init_draw_human()

    @on_trait_change('show_inertia_ellipsoid')
    def _update_show_inertia_ellipsoid(self):
        if self.show_inertia_ellipsoid:
            self.H._draw_mayavi_inertia_ellipsoid(self.scene.mlab)
        else:
            self.H._ellipsoid_mesh.remove()

    def _maybe_update_inertia_ellipsoid(self):
        if self.show_inertia_ellipsoid:
            self.H._update_mayavi_inertia_ellipsoid()

    @on_trait_change('show_mass_center')
    def _update_show_mass_center(self):
        if self.show_mass_center:
            self.H._draw_mayavi_mass_center_sphere(self.scene.mlab)
        else:
            self.H._mass_center_sphere.remove()

    def _maybe_update_mass_center(self):
        if self.show_mass_center:
            self.H._update_mayavi_mass_center_sphere()

    @on_trait_change('reset_configuration')
    def _update_reset_configuration(self):
        # TODO: This is really slow because it sets every trait one by one. It
        # would be nice to set them all to zero and only call the redraw once.
        for cfg in sliders:
            setattr(self, cfg, self.trait(cfg).default_value()[1])

    @on_trait_change('somersault')
    def _update_somersault(self):
        self.H.set_CFG('somersault', deg2rad(self.somersault))
        self._update_mayavi(['P', 'T', 'C', 'A1', 'A2', 'B1', 'B2', 'J1', 'J2',
            'K1', 'K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('tilt')
    def _update_tilt(self):
        self.H.set_CFG('tilt', deg2rad(self.tilt))
        self._update_mayavi(['P', 'T', 'C', 'A1', 'A2', 'B1', 'B2', 'J1', 'J2',
            'K1', 'K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('twist')
    def _update_twist(self):
        self.H.set_CFG('twist', deg2rad(self.twist))
        self._update_mayavi(['P', 'T', 'C', 'A1', 'A2', 'B1', 'B2', 'J1', 'J2',
            'K1', 'K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PTsagittalFlexion')
    def _update_PTsagittalFlexion(self):
        self.H.set_CFG('PTsagittalFlexion', deg2rad(self.PTsagittalFlexion))
        self._update_mayavi(['T', 'C', 'A1', 'A2', 'B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PTbending')
    def _update_PTFrontalFlexion(self):
        self.H.set_CFG('PTbending', deg2rad(self.PTbending))
        self._update_mayavi(['T', 'C', 'A1', 'A2', 'B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('TCspinalTorsion')
    def _update_TCSpinalTorsion(self):
        self.H.set_CFG('TCspinalTorsion', deg2rad(self.TCspinalTorsion))
        self._update_mayavi(['C', 'A1', 'A2', 'B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('TCsagittalSpinalFlexion')
    def _update_TCLateralSpinalFlexion(self):
        self.H.set_CFG('TCsagittalSpinalFlexion',
                deg2rad(self.TCsagittalSpinalFlexion))
        self._update_mayavi(['C', 'A1', 'A2', 'B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CA1extension')
    def _update_CA1extension(self):
        self.H.set_CFG('CA1extension', deg2rad(self.CA1extension))
        self._update_mayavi(['A1', 'A2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CA1adduction')
    def _update_CA1adduction(self):
        self.H.set_CFG('CA1adduction', deg2rad(self.CA1adduction))
        self._update_mayavi(['A1', 'A2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CA1rotation')
    def _update_CA1rotation(self):
        self.H.set_CFG('CA1rotation', deg2rad(self.CA1rotation))
        self._update_mayavi(['A1', 'A2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CB1extension')
    def _update_CB1extension(self):
        self.H.set_CFG('CB1extension', deg2rad(self.CB1extension))
        self._update_mayavi(['B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CB1abduction')
    def _update_CB1abduction(self):
        self.H.set_CFG('CB1abduction', deg2rad(self.CB1abduction))
        self._update_mayavi(['B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('CB1rotation')
    def _update_CB1rotation(self):
        self.H.set_CFG('CB1rotation', deg2rad(self.CB1rotation))
        self._update_mayavi(['B1', 'B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('A1A2extension')
    def _update_A1A2extension(self):
        self.H.set_CFG('A1A2extension', deg2rad(self.A1A2extension))
        self._update_mayavi(['A2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('B1B2extension')
    def _update_B1B2extension(self):
        self.H.set_CFG('B1B2extension', deg2rad(self.B1B2extension))
        self._update_mayavi(['B2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PJ1extension')
    def _update_PJ1extension(self):
        self.H.set_CFG('PJ1extension', deg2rad(self.PJ1extension))
        self._update_mayavi(['J1', 'J2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PJ1adduction')
    def _update_PJ1adduction(self):
        self.H.set_CFG('PJ1adduction', deg2rad(self.PJ1adduction))
        self._update_mayavi(['J1', 'J2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PK1extension')
    def _update_PK1extension(self):
        self.H.set_CFG('PK1extension', deg2rad(self.PK1extension))
        self._update_mayavi(['K1', 'K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('PK1abduction')
    def _update_PK1abduction(self):
        self.H.set_CFG('PK1abduction', deg2rad(self.PK1abduction))
        self._update_mayavi(['K1', 'K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('J1J2flexion')
    def _update_J1J2flexion(self):
        self.H.set_CFG('J1J2flexion', deg2rad(self.J1J2flexion))
        self._update_mayavi(['J2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    @on_trait_change('K1K2flexion')
    def _update_K1K2flexion(self):
        self.H.set_CFG('K1K2flexion', deg2rad(self.K1K2flexion))
        self._update_mayavi(['K2'])
        self._maybe_update_mass_center()
        self._maybe_update_inertia_ellipsoid()

    def _update_mayavi(self, segments):
        """Updates all of the segments and solids."""
        for affected in segments:
            seg = self.H.get_segment_by_name(affected)
            for solid in seg.solids:
                solid._mesh.scene.disable_render = True
        for affected in segments:
            self.H.get_segment_by_name(affected)._update_mayavi()
        for affected in segments:
            seg = self.H.get_segment_by_name(affected)
            for solid in seg.solids:
                solid._mesh.scene.disable_render = False
예제 #42
0
class Game:
    """Deals with updating board and game arbitration"""
    # Note that player1 will always go first and will
    # always be X. Player2 will be O and go second.
    def __init__(self):
        self.result = False
        self.turn = 0
        self.board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
    
    
    def playerpick(self):
        print 'PLAYERPICK EXECUTED'
        player1 = raw_input('Player 1: ').lower()
        player2 = raw_input('Player 2: ').lower()
        # Add ends to this list as they are created
    
        if player1 == 'human':
            from human import Human
            self.player1 = Human(1, self)
        elif player1 == 'roteai':
            raise RuntimeError
        elif player1 == 'learnai':
            #player1 = learnAI()
            pass
        else:
            from human import Human
            self.player1 = Human(1, self)
    
        if player2 == 'human':
            from human import Human
            self.player2 = Human(2, self)
        elif player2 == 'roteai':
            raise RuntimeError
        elif player2 == 'learnai':
            #player2 = learnAI()
            pass
        else:
            from human import Human
            player2 = Human(2, self)
        
        print
             
    def is_over(self):
        if (self.board[0][0] == 'X' and self.board[0][1] == 'X' and self.board[0][2] == 'X') or\
           (self.board[0][0] == 'O' and self.board[0][1] == 'O' and self.board[0][2] == 'O'):
            return True
        #mid horiz
        elif (self.board[1][0] == 'X' and self.board[1][1] == 'X' and self.board[1][2] == 'X') or\
             (self.board[1][0] == 'O' and self.board[1][1] == 'O' and self.board[1][2] == 'O'):
            return True
        #low horiz
        elif (self.board[2][0] == 'X' and self.board[2][1] == 'X' and self.board[2][2] == 'X') or\
             (self.board[2][0] == 'O' and self.board[2][1] == 'O' and self.board[2][2] == 'O'):
            return True

        #left vert
        elif (self.board[0][0] == 'X' and self.board[1][0] == 'X' and self.board[2][0] == 'X') or\
             (self.board[0][0] == 'O' and self.board[1][0] == 'O' and self.board[2][0] == 'O'):
            return True
        #mid vert
        elif (self.board[0][1] == 'X' and self.board[1][1] == 'X' and self.board[2][1] == 'X') or\
             (self.board[0][1] == 'O' and self.board[1][1] == 'O' and self.board[2][1] == 'O'):
            return True
        #right vert
        elif (self.board[0][2] == 'X' and self.board[1][2]  == 'X'and self.board[2][2] == 'X') or\
             (self.board[0][2] == 'O' and self.board[1][2] == 'O' and self.board[2][2] == 'O'):
            return True

        #left-right diag
        elif (self.board[0][0] == 'X' and self.board[1][1] == 'X' and self.board[2][2] == 'X') or\
             (self.board[0][0] == 'O' and self.board[1][1] == 'O' and self.board[2][2] == 'O'):
            return True
        #right-left diag
        elif (self.board[0][2] == 'X' and self.board[1][1] == 'X' and self.board[2][0] == 'X') or\
             (self.board[0][2] == 'O' and self.board[1][1] == 'O' and self.board[2][0] == 'O'):
            return True
        else:
            return False

    def print_board(self):
        print '''
         %s | %s | %s
        -----------
         %s | %s | %s
        -----------
         %s | %s | %s
        ''' % (self.board[0][0],self.board[0][1],self.board[0][2],\
               self.board[1][0],self.board[1][1],self.board[1][2],\
               self.board[2][0],self.board[2][1],self.board[2][2])

    def play(self):
        # TODO
        turn = 0
#       print
#       print self
#       print
        while self.is_over() == False:
            if turn % 2 == 0:
                one = self.player1
                self.player1.turn()
            elif turn % 2 == 1:
                two = self.player2
                self.player2.turn()
            turn += 1
예제 #43
0
class Objects(sf.Drawable):
    def __init__(self):
        sf.Drawable.__init__(self)

        self.objects = []

        self.tt = sf.Time()

        self.mobs = []
        self.mobs.append(Mob(ETTIN))
        self.mobs.append(Mob(BARLOG))
        self.mobs.append(Mob(CYCLOPS))
        self.mobs.append(Mob(DEMON))
        self.mobs.append(Mob(STONEGOLEM))
        self.mobs.append(Mob(TIGERWORM))

        self.mobs[0].position = (100, 150)
        self.mobs[1].position = (650, 150)
        self.mobs[2].position = (100, 350)
        self.mobs[3].position = (200, 550)
        self.mobs[4].position = (600, 350)
        self.mobs[5].position = (600, 550)

        self.player = Human()
        self.player.position = (350, 350)

        for mob in self.mobs:
            for i in range(3):
                for a in range(5):
                    for d in range(8):
                        mob.pending_actions.insert(0, (a, d, 1000))

        for a in range(12):
            for d in range(8):
                self.player.pending_actions.insert(0, (a, d, 1000))

        for a in range(12):
            for d in range(8):
                self.player.pending_actions.insert(0, (a, d, 1000))

    def draw(self, target, states):
        # get the view to draw according it
        view = target.view

        position = view.center - (view.size // 2)
        psubgrid = (32, 32)

        q, r = divmod(position, 32)
        i, k = q

        of = (r + view.size) // psubgrid
        j, l = of

        i, j, k, l = int(i), int(j) + 1, int(k), int(l) + 1

        # draw items on the ground
        for x in range(i, i+j):
            for y in range(k, k+l):
                index = y*self.size.x+x

                sprite = self.objects[1][index]

                if sprite:
                    sprite.position = sf.Vector2(x, y) * 32
                    target.draw(sprite)

        # draw objects (house, monsters, players)
        for x in range(i, i+j):
            for y in range(k, k+l):
                index = y*self.size.x+x

                sprite = self.objects[2][index]

                if sprite:
                    sprite.position = sf.Vector2(x, y) * 32
                    target.draw(sprite)

        target.draw(self.player, states)

        for mob in self.mobs:
            target.draw(mob, states)

    def update(self, elapsed_time):
        self.tt += elapsed_time
        if self.tt.seconds > 3.333:
            from random import randint
            newgenre = randint(0, 1)
            newskin = randint(0, 2)
            newunderwear = randint(0, 7)

            newmantle = MantleItem()
            newmantle.appearance = randint(0, 5)

            self.player.gender = newgenre
            self.player.skin_color = newskin
            self.player.underwear_color = newunderwear

            self.player.mantle = newmantle

            self.tt = sf.Time()

        self.player.update(elapsed_time)

        for mob in self.mobs:
            mob.update(elapsed_time)

    def load_map(self, amd, objects):
        block = amd.size.x * amd.size.y * [None]
        item = amd.size.x * amd.size.y * [None]
        object = amd.size.x * amd.size.y * [None]

        self.objects = (block, item, object)
        self.size = amd.size

        for x in range(amd.width):
            for y in range(amd.height):

                sprite = amd.grid[x][y][2]
                frame = amd.grid[x][y][3]

                if sprite:
                    index = y*self.size.x+x
                    image_index = 256 + sprite * 256 + frame
                    try:
                        mysprite = sf.Sprite(objects[image_index][0])
                        mysprite.position = sf.Vector2(x, y) * 32 + objects[image_index][1]
                        self.objects[2][index] = mysprite
                    except: pass

    def unload_map(self):
        pass
예제 #44
0
    def test_owner(self):
        s = Station(1)
        h = Human(1, s)
        c = Cat(1, s)

        self.assertTrue(h.isowner(c))
예제 #45
0
class Tournament(object):

#----------------------------------------------------------------------------------------------------
#   Function Name: __init__
#   Purpose: To initialize the object
#   Parameters: 
#           The human board
#           The computer board
#           The human score
#           The computer score
#           The humanIsFirstPlayer flag
#           The humanIsNext flag
#           The list of loaded dice rolls
#           The didLoad flag
#   Return Value:  none
#   Local Variables: 
#           All the same variables initializing the classes data members
#   Algorithm: 
#           1. Set up all the parameters as object data member
#           2. If the user is loading a game, resume around, if not then start a new one
#----------------------------------------------------------------------------------------------------


    def __init__(self, humanBoard, computerBoard, humanScore, computerScore, 
                            humanIsFirstPlayer, humanIsNext, diceQueue, didLoad):
        self.human = Human(humanScore)
        self.computer = Computer(computerScore)
        self.diceQueue = diceQueue
        self.humanIsFirstPlayer = humanIsFirstPlayer
        self.humanIsNext = humanIsNext
        self.exitCode = 0
        self.board = Board(humanBoard, computerBoard)
        self.turnCount = 0
        self.returnList = [False, 0, 0]

        if didLoad:
            self.resumeRound()
        else:
            self.newRound()


#----------------------------------------------------------------------------------------------------
#   Function Name: newRound
#   Purpose: To start a new round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           numSquares - The number of squares that the user would like
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Get the number of squares that the user would like to have
#           2. Reset the boards with the new amount of squares
#           3. Choose the first player
#           4. Begin a new round
#----------------------------------------------------------------------------------------------------


    def newRound(self):
        numSquares = self.getNumSquares()
        self.board.resetBoards(numSquares)
        self.chooseFirstPlayer()
        self.returnList[2] = 0
        cround = cRound(self.board, self.human, self.computer, self.turnCount, 
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()


#----------------------------------------------------------------------------------------------------
#   Function Name: resumeRound
#   Purpose: To resume a round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Set the turn count to an arbitrary large number
#           2. Set the handicap square in the return list to 0
#           3. Play a round with loaded data
#           4. Ask the player if they would like to play again
#           5. If so, begin a another round
#----------------------------------------------------------------------------------------------------


    def resumeRound(self):
        self.turnCount = 4
        self.returnList[2] = 0
        cround = cRound(self.board, self.human, self.computer, self.turnCount,
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()

#----------------------------------------------------------------------------------------------------
#   Function Name: subsequentRound
#   Purpose: To start a subsequent round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           numSquares - The number of squares that the user would like
#           cround - An instance of a round to be played
#   Algorithm: 
#           1. Set the turncount to 0
#           2. Get the number of squares from the suer
#           3. Reset the boards using the new numSquares
#           4. Compute and apply the handicap
#           5. Choose the first player
#           6. Play a round
#           7. Ask if the user wants to play another round
#           8. If so, then recurse
#----------------------------------------------------------------------------------------------------

    def subsequentRound(self):
        self.turnCount = 0
        numSquares = self.getNumSquares()
        self.board.resetBoards(numSquares)
        self.computeHandicap()
        self.chooseFirstPlayer()
        cround = cRound(self.board, self.human, self.computer, self.turnCount,
                                    self.humanIsNext, self.humanIsFirstPlayer, self.diceQueue, 
                                    self.returnList)
        cround.play()
        self.askToPlayAgain()
        self.subsequentRound()

#----------------------------------------------------------------------------------------------------
#   Function Name: getNumSquares
#   Purpose: To retrieve the number of board squares from the user
#   Parameters: none
#   Return Value:  squares - the desired  number of squares
#   Local Variables: 
#           squares - the desired number of squares
#   Algorithm: 
#           1. Ask for the user's validated input
#           2. Return their input 
#----------------------------------------------------------------------------------------------------

    def getNumSquares(self):
        squares = Interface.validateRange(
            "How many squares would you like to use? (9, 10, or 11): ",
                 9, 11)
        return squares


#----------------------------------------------------------------------------------------------------
#   Function Name: computeHandicap
#   Purpose: To compute and apply the handicap from the previous round
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           ones - the ones place value from the winning score
#           tens - the tens place value from the winning score
#           handicapSquare - the square to be handicapped
#           boardSize - the size of the game board
#   Algorithm: 
#           1. Compute which square is the handicapped one 
#           2. If the square is out of the bounds of the game board, then make it
#                   the largest square on the gameboard
#           3. Set the handicap square in the return list to be sent to round
#           4. Apply the handicap
#----------------------------------------------------------------------------------------------------


    def computeHandicap(self):
        ones = self.returnList[1]%10
        tens = int(self.returnList[1]/10)
        handicapSquare = ones + tens
        boardSize = len(self.board.humanBoard)

        if handicapSquare > boardSize:
            handicapSquare = boardSize

        self.returnList[2] = handicapSquare

        self.applyHandicap(handicapSquare)


#----------------------------------------------------------------------------------------------------
#   Function Name: applyHandicap
#   Purpose: To correctly apply the handicap
#   Parameters: The handicapSquare
#   Return Value:  none
#   Local Variables: none
#   Algorithm: 
#           1. If the human own and is the first player, give handicap to Computer
#           2. If human won and was not the first player, give human the handicap
#           3. If computer won and was the first player, give human the handicap
#           4. If computer won ans was not the first player, give computer the handicap
#----------------------------------------------------------------------------------------------------

    def applyHandicap(self, handicapSquare):
        if self.returnList[0] and self.humanIsFirstPlayer:
            Interface.printMsg("The Computer gets a handicap.")
            self.board.computerBoard[handicapSquare-1] = "*"
        if self.returnList[0] and not self.humanIsFirstPlayer:
            Interface.printMsg("You get a handicap.")
            self.board.humanBoard[handicapSquare-1] = "*"
        if not self.returnList[0] and not self.humanIsFirstPlayer:
            Interface.printMsg("You get a handicap.")
            self.board.humanBoard[handicapSquare-1] = "*"
        if not self.returnList[0] and self.humanIsFirstPlayer:
            Interface.printMsg("The Computer gets a handicap.")
            self.board.computerBoard[handicapSquare-1] = "*"



#----------------------------------------------------------------------------------------------------
#   Function Name: chooseFirstPlayer
#   Purpose: To choose the first player
#   Parameters: none
#   Return Value:  none
#   Local Variables: 
#           humanRoll - the human's roll
#           computerRoll - the computer's roll
#   Algorithm: 
#           1. If the dice queue has contents in it then:
#               a. Load the humanRoll from dice queue
#               b. Pop that roll from the queue
#               c. Load the computer roll from the dice queue
#               d. Pop that roll from the queue
#           3. Otherwise:
#               a. Generate a random roll for the human
#               b. Generate a random roll for the computer
#           4. If the human roll is greater than computer roll, then set
#                   humanIsFirstPlayer and humanIsNext to 1
#           5. If the human roll is less than the computer roll then set
#                   humanIsFirstPlayer and humanIsNext to 0
#           6. If the rolls are equal, then recurse
#----------------------------------------------------------------------------------------------------


    def chooseFirstPlayer(self):
        if self.diceQueue:
            Interface.printMsg("You are rolling...")
            humanRoll = self.diceQueue[0][0] + self.diceQueue[0][1]
            self.diceQueue.pop(0)
            Interface.printMsg("You rolled " + repr(humanRoll))
            Interface.printMsg("The Computer is rolling...")
            computerRoll = self.diceQueue[0][0] + self.diceQueue[0][1]
            Interface.printMsg("The Computer rolled " + repr(computerRoll))
            self.diceQueue.pop(0)
        else:
            Interface.printMsg("You are rolling...")
            humanRoll = self.human.rollDice()
            Interface.printMsg("You rolled " + repr(humanRoll))
            Interface.printMsg("The Computer is rolling...")
            computerRoll = self.computer.rollDice()
            Interface.printMsg("The Computer rolled " + repr(computerRoll))

        if humanRoll > computerRoll:
            Interface.printMsg("You go first!")
            self.humanIsFirstPlayer = 1
            self.humanIsNext = 1
        elif humanRoll < computerRoll:
            Interface.printMsg("The Computer goes first!")
            self.humanIsFirstPlayer = 0
            self.humanIsNext = 0
        else:
            Interface.printMsg("It was a tie!")
            self.chooseFirstPlayer()

#----------------------------------------------------------------------------------------------------
#   Function Name: askToPlayAgain
#   Purpose: To see if the user would like to play another round
#   Parameters: none
#   Return Value:  True if they will play again
#   Local Variables: 
#           willPlay - a flag indicating if the user will play another round
#   Algorithm: 
#           1. Get the user's input on whether they will play again or not
#           2. If they want to play again, return true
#           3. Otherwise terminate the program
#----------------------------------------------------------------------------------------------------


    def askToPlayAgain(self):
        willPlay = Interface.validateBoolean("Would you like to play another round? (y/n): ")

        if willPlay:
            return True
        self.terminate()


#----------------------------------------------------------------------------------------------------
#   Function Name: terminate
#   Purpose: To display the winner and terminate the program
#   Parameters: none
#   Return Value:  none
#   Local Variables: none
#   Algorithm: 
#           1. Infer and display the winner of the tournament
#           2. Exit the program
#----------------------------------------------------------------------------------------------------

    def terminate(self):
        print "\n\n"
        print ("\tHuman:  " + repr(self.human.score) + 
                    "\t\tComputer:  " + repr(self.computer.score))
        print "\n\n"
        if self.computer.score < self.human.score:
            print "\tYou won the tournament!"
        if self.computer.score > self.human.score:
            print "\tThe Computer won the tournament!"
        if self.computer.score == self.human.score:
            print "\tThe tournament was a draw!"

        print "\n\n"
        print "Program is terminating."
        sys.exit()
예제 #46
0
 modB   = ZvezdaModule()
 modDrag = DragonCargoModule()
 modDrag.setup_simple_resupply()
        
 station = Station(modDock, 'NewbieStation', logger)
 station.berth_module(modDock,'CBM0',modA, None, True)
 station.berth_module(modDock,'CBM3',modB, None, True)    
 station.berth_module(modA,None,modDrag, None, True)
 
 '''rob = Robot('Robby')     
 rob.station = station
 station.actors[rob.id]=rob
 rob.location = modB.node('hall0')
 rob.xyz = modB.location'''
 
 ernie= Human('Bela Lugosi',station=station,logger=station.logger)
 station.actors[ernie.id] = ernie
 ernie.location = modA.node('hall0')
 ernie.xyz = modA.location
 
 ernie.needs['WasteCapacityLiquid'].amt=0.1
 ernie.needs['Food'].set_amt_to_severity('HIGH')
 ernie.nutrition = [0.5, 0.5, 0.5, 0.5, 0.5]
 #modB.equipment['Electrolyzer'][3].broken=True
 
   
 #modA.berth('CBM0', modB, 'CBM0')
 #for m in station.modules.values(): print m.short_id, m.location
 #for n in station.paths.edges(data=True): print n
 for i in range(1,10000):
     station.update(util.TIME_FACTOR/20.0)
예제 #47
0
    @age.setter
    def age(self, age):
        self._age = age

    # This allows the property to be deleted
    @age.deleter
    def age(self):
        del self._age


# When a Python interpreter reads a source file it executes all its code.
# This __name__ check makes sure this code block is only executed when this
# module is the main program.
if __name__ == '__main__':
    # Instantiate a class
    i = Human(name="Ian")
    i.say("hi")                     # "Ian: hi"
    j = Human("Joel")
    j.say("hello")                  # "Joel: hello"
    # i and j are instances of type Human, or in other words: they are Human objects

    # Call our class method
    i.say(i.get_species())          # "Ian: H. sapiens"
    # Change the shared attribute
    Human.species = "H. neanderthalensis"
    i.say(i.get_species())          # => "Ian: H. neanderthalensis"
    j.say(j.get_species())          # => "Joel: H. neanderthalensis"

    # Call the static method
    print(Human.grunt())            # => "*grunt*"
    
예제 #48
0
from bear import Bear, GrizzlyBear, DiscerningBear
from human import Human

dave = Human("Dave")
bob = Human("Bob")
dave.climb_tree()
bob.climb_tree()

fussy = DiscerningBear("Fussy")
fussy.chase(bob)
fussy.chase(dave)
#>>> Bleech! I'm not eating Dave!
예제 #49
0
    def test_human_stuck(self):
        s = Station(1)
        h = Human(1, s)

        with self.assertRaises(StuckException):
            h.action()