Ejemplo n.º 1
0
 def update_image(self, world):
     xvel = Game.cutoff(self.vel[0], 0.01)
     yvel = Game.cutoff(self.vel[1], 0.01)
     
     if xvel != 0 or yvel != 0:
         self.update_anim_timer(True, world)
         
         if xvel < 0:
             self.transition_to_anim_dir(0, world)
         elif xvel > 0:
             self.transition_to_anim_dir(2, world)
         elif yvel < 0:
             self.transition_to_anim_dir(1, world)
         elif yvel > 0:
             self.transition_to_anim_dir(3, world)
     
     else:
         if self.facing == Game.LEFT:
             anim_dir = 0
         else:
             anim_dir = 1
         self.transition_to_anim(0, anim_dir, world)
         if self.anim_state != 0:
             self.update_anim_timer(False, world)
     
     self.img = self.body_images[self.anim_state][self.anim_dir]
     self.hair_img = self.hair_images[self.anim_state][self.anim_dir]
     self.tail_img = self.tail_images[self.anim_state][self.anim_dir]
Ejemplo n.º 2
0
Archivo: main.py Proyecto: Neopibox/MDD
def run():
        n = 0
        gameState = "run"
        global game, menu, refresh
        
        while True:
                interact()
                if Menu.gameWindow(menu):
                        gameState = Game.run(game, dt)
                        if gameState == "run":
                                if(n % 10):
                                        #effacer la console 
                                        #sys.stdout.write("\033[2J")
                                        Menu.show(menu)
                                        Game.show(game)
                        elif gameState == "lose":
                                Menu.setCurrentWindow(menu, "lose")
                                Menu.show(menu)
                                gameState = "run"
                        elif gameState == "win":
                                Menu.setCurrentWindow(menu, "win")
                                Menu.show(menu)
                                gameState = "run"
                else:
                        if refresh==True:
                                Menu.show(menu)
                time.sleep(dt)
                n += 1
Ejemplo n.º 3
0
    def __init__(self, infile=None, void_color=VOID_COLOR):

        if not infile is None:
            board = []
            for line in infile:
                board.append(list(line.strip()))
            self.board = np.array(board).transpose()
            self.shape = self.board.shape
        else:
            board = real_world.split()
            for i, line in enumerate(board):
                board[i] = list(line.strip())
            self.board = np.array(board).transpose()
            self.shape = self.board.shape

        self.void_color = void_color
        self.game = None

        self.sprites = {
            'g': pygame.image.load(
                Game.resource_path(Game.Game.SPRITES_LOCATION, 'grass.png')
            ).convert(),
            'w': pygame.image.load(
                Game.resource_path(Game.Game.SPRITES_LOCATION, 'water.png')
            ).convert(),
            't': pygame.image.load(
                Game.resource_path(Game.Game.SPRITES_LOCATION, 'tree.png')
            ).convert(),
        }
Ejemplo n.º 4
0
    def dungeonTest(self):
        ''' Set up dungeon test '''
        from EriuMapTileClass import Forest
        mt = Forest(3, 5)
        d = A.MultiLevelArea(name = u"The Dungeons of Dread")

        mt.setConnectedArea(d)

        d.buildStartingLevel()
        d.buildDungeon(4)

        d1 = d.getLevels()[0]

        self.player = P.Player()
        d1.placeCreatureAtEntrance(self.player)

#         orc1 = Cr.Orc()
#         d1.placeCreatureAtRandom(orc1)
#
#         orc2 = Cr.Orc()
#         d1.placeCreatureAtRandom(orc2)

        self.openShelf()

        G.ui.setPlayer(self.player)
        G.setCurrentLevel(d1)

        self.play()
Ejemplo n.º 5
0
 def AddPlayer(self, player):
     print "Adding player "
     game = self.getAvailableGames()
     uuid = player.uuid
     self.players[uuid] = player
     player.Send({"action": "getUUID", "message": str(uuid)})
     if not game is None:
         player.inGame = True
         self.games[game].addPlayer(player)
         player.game = game
         opponents = game.getOpponents(player)
         if game.minPlayersConnected() == True:
             player.inGame = True
             # player.Send({"action": "inGameStart", "message": str(opponents[0].uuid)})
             # self.other.Send({"action":"inGameStart", "message": str(uuid)})
             for p in opponents:
                 p.Send({"action": "inGameStart", "message": str(uuid)})
                 self.players[p.uuid].inGame = True
     else:
         game = Game()
         game.addPlayer(player)
         self.games[game] = game
         player.game = game
         player.Send({"action": "isHost", "message": True})
         self.other = player
Ejemplo n.º 6
0
def main():
    
    #global donePlaying 
    #global titleScreen
    #global howToPlay
    #global mainGame
    #global gameOver
    #global creditScreen
    #global startMenu
    #global menu
    #global clearSprites
    
    while Globals.donePlaying != True:
        print Globals.donePlaying
        if Globals.titleScreen == True:
            Title.title()
        elif Globals.howToPlay == True:
            Instructions.instructions()
        elif Globals.mainGame == True:
            Game.game()
        elif Globals.pauseMenu == True:
            PauseMenu.pausemenu()
        elif Globals.gameOver == True:
            GameOver.gameover()
        elif Globals.creditScreen == True:
            Credits.credits()
        elif Globals.winScreen == True:
            Win.win()
Ejemplo n.º 7
0
 def evaluate(self, trials, games, xoro, testNet = False, goodNet = 0):
     """Tests the network and returns the results"""
     if testNet:         ###If there is another network to test with
         answers = Game.run(1,trials, games, self, xoro, True, goodNet)
     else:               ###If running against a random guesser
         answers = Game.run(1,trials,games,self, xoro)
     return answers
    def start_match(self):
        # Reset player history
        self.player_1.forget()
        self.player_2.forget()

        for iteration_count in range(self.iterations):
            move_1 = self.player_1.get_move()
            move_2 = self.player_2.get_move()

            if Game.is_communication_failed():
                move_1 = Game.opposite_move_from(move_1)
            if Game.is_communication_failed():
                move_2 = Game.opposite_move_from(move_2)

            self.moves.append([move_1, move_2])

            points_1, points_2 = Game.get_points(move_1, move_2)

            self.move_points.append([points_1, points_2])

            self.points[0] += points_1
            self.points[1] += points_2

            self.player_1.remember(opponent_move=move_2, my_move=move_1, opponent_points=points_2, my_points=points_1)
            self.player_2.remember(opponent_move=move_1, my_move=move_2, opponent_points=points_1, my_points=points_2)
Ejemplo n.º 9
0
Archivo: main.py Proyecto: Neopibox/MDD
def interact(): 
        global direction, refresh, game, menu
       
        refresh = False
        #gestion des evenements clavier
        if isData():                                    #si une touche est appuyee
                refresh = True                
                key = sys.stdin.read(1)
                if Menu.gameWindow(menu):               # si on est sur le fenetre de jeu alors ...
                        Game.interact(game, settings, key)

                        if key == "p":
                                Menu.setCurrentWindow(menu, "pause")       # faire apparaitre le menu Pause
                else: 
                        if key == "z": 
                                Menu.changeSelectedButton(menu, "buttonUp")

                        elif key == "s":
                                Menu.changeSelectedButton(menu, "buttonDown")
                        
                        elif key == "d":
                                # Execute les commandes présentent dans la liste de commande à executer du bouton selectionne
                                buttonCmdList = Menu.getButtonList(menu, Menu.getIndexOfSelectedButton(menu, Menu.getButtonList(menu), Menu.getButtonSelected(menu,"name")),"cmd")
                                
                                for cmd in buttonCmdList:
                                        exec cmd
        
                if key == "\x1b": 
                        quit()                          # \x1b = touche echap / appel de la fonction qui permet de quitter le jeu
        
        while isData():
                sys.stdin.read(5)
Ejemplo n.º 10
0
def testMakeMove():
    new = Game(4)
    new.array = test_board
    new.makeMove(Game.CONST_UP)
    assert (new.array[0] == [4,4,16,4]) and
        (np.array(new.array).sum() <= 32) and
        (np.array(new.array).sum() >= 28)
Ejemplo n.º 11
0
 def render_block(self, x, y, screen, viewport, background):
     #don't render air
     if background:
         block = World.get_block_from_id(self.background_blocks[y][x])
     else:
         block = World.get_block_from_id(self.foreground_blocks[y][x])
     if block["name"] != "air":
         Game.get_world().render_block(block["id"], [Convert.chunk_to_world(x, self), y], block["connectedTexture"], screen, viewport, background, self)
Ejemplo n.º 12
0
def leaderboardMenu(display):
    bg = pygame.image.load("menu/wallpaper.jpg").convert_alpha()
    back = pygame.image.load("buttons/back.png").convert_alpha()
    font = pygame.font.Font(None, 30)
    loading = font.render("Loading...",0,(0,0,0))
    stringsToRender = []
    names = []
    scores = []

    bX = 10
    bY = 560
    rX = 200
    rY = 700
    while True :
        pos = pygame.mouse.get_pos()

        if collide(bX,bY,back,pos) :
            pygame.mouse.set_cursor(*cursor.HAND_CURSOR)
        else :
            pygame.mouse.set_cursor(*cursor.ARROW_CURSOR)

        for event in pygame.event.get():

            if event.type == MOUSEBUTTONDOWN and event.button == 1 :
                if collide(bX,bY,back,pos) :
                    Game.menu1(display)
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN :
                if event.key == K_ESCAPE :
                    pygame.quit()
                    sys.exit()
        display.blit(bg,(0,0))
        #draw scores

        for s in range(len(stringsToRender)):
            # newSurf = pygame.Surface((300,100))
            # newSurf.blit(stringsToRender[s],(0,0))
            # newSurf.set_alpha(255)
            # display.blit(newSurf, (200,50+(s*30)))
            display.blit(stringsToRender[s],(300,30+(s*30)))

        display.blit(back,(bX,bY))
        if len(names)<=0:display.blit(loading,(400,300))
        
        pygame.display.update()
        if len(names)<=0:
            
            scores = LeaderboardClient.getHighScores();
            names = scores[0]
            scores = scores[1]
            for i in range(len(names)):
                stringsToRender.append(font.render(str(i+1)+": "+str(names[i])+" - "+str(scores[i]),0,(0,0,0)))

        
            
    return
Ejemplo n.º 13
0
 def openGame(self):
     rows=int(self.Rows.currentText())
     columns=int(self.Columns.currentText())
     if(self.OptionPlayerPc.isChecked()):
         self.Ventana = Game(rows,columns,1)
     else:
         self.Ventana = Game(rows,columns,2)
     self.close()
     self.Ventana.show()
Ejemplo n.º 14
0
    def test_player_turn_after_one_mark(self):
        players = {"andy": "X", "nick": "O"}
        board = Board(3)
        game = Game(board, players)

        if not game.board.is_marked(0, 0):
            game.mark(0, 0)

        self.assertEquals(game.player_in_turn, players.keys()[1], "wrong player in turn")
Ejemplo n.º 15
0
def test_str_to_move():
    print("testing string to move conversion")

    print("\tnormal move")
    move = Game.str_to_move("a1a2")
    assert move == ((0, 0), (1, 0))
    print("\tpromotion")
    move = Game.str_to_move("c7c8q")
    assert move == ((6, 2), (7, 2), "q")
Ejemplo n.º 16
0
    def test_if_game_has_finnished_by_board_completion(self):
        b = Board(3)
        p = {"andy": "X", "nick": "O"}
        g = Game(b, p)

        for i in range(3):
            for j in range(3):
                b.fill_position(i, j, choice(ascii_uppercase))

        self.assertTrue(g.is_game_finnished(), "game is not finnished")
Ejemplo n.º 17
0
 def update(self, world):
     corner_empty = True
     for piece in self.pieces:
         if piece.pos == [self.pos[0] + 1, self.pos[1] + 1]:
             corner_empty = False
     solved = corner_empty and self.count_inversions() == 0
     if solved:
         Game.play_sound("sfx/puzzle/complete.ogg")
         for piece in self.pieces:
             piece.locked = True
Ejemplo n.º 18
0
    def test_if_game_has_finnished_by_user_winning(self):
        b = Board(3)
        p = {"andy": "X", "nick": "O"}
        g = Game(b, p)

        for i in range(3):
            for j in range(3):
                b.fill_position(i, j, "X")

        self.assertTrue(g.is_game_finnished(), "game is not finnished")
Ejemplo n.º 19
0
Archivo: tests.py Proyecto: clu8/2048
    def test_board_creation(self):
        g = Game()
        assert len(g.get_open_squares()) == 4 * 4
        assert len(g.board) == 4
        assert len(g.board[0]) == 4

        g2 = Game(5, 6)
        assert len(g2.get_open_squares()) == 5 * 6
        assert len(g2.board) == 5
        assert len(g2.board[0]) == 6
Ejemplo n.º 20
0
def main():
	pygame.init()

	size = [SC_WIDTH, SC_HEIGHT]
	screen = pygame.display.set_mode(size)
	font = pygame.font.Font(None, 25)
	pygame.display.set_caption('Donkey Kong')

	game = Game()
	game.gameLoop(screen, font)
Ejemplo n.º 21
0
def main():
	"""..."""
	evManager = EventManager()
	keyboardMouseGameContController = KeyboardMouseGameContController(evManager)
	controlMapper = ControlMapper(evManager)
	spinner = CPUSpinnerController(evManager)
	pygameView = PygameView(evManager)
	game = Game(evManager)
	game.start()
	spinner.run()
class WerewolfTagClient:
    
    game = None
    window = None
    display = pygame.display
    event = pygame.event
    mixer = pygame.mixer #for sound
    frameRate = 60
    screenWidth = 640
    screenHeight = 480
    fullScreen = False
    currentState = GameState.GAME
    
    def __init__(self):
        pygame.init()
        self.window=self.display.set_mode([self.screenWidth, self.screenHeight], pygame.FULLSCREEN if self.fullScreen else pygame.RESIZABLE)
        pygame.mouse.set_visible(False)
        self.mixer.init()
        self.game = Game(self)
        self.game.init()
        
    def run(self):
        isDone = False
        while isDone == False: 
            self.window.fill((0, 0, 0))
            key = pygame.key.get_pressed()
            for event in pygame.event.get():
                if event.type==pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    isDone = True
                    
           
            if self.currentState == GameState.GAME:
                self.game.update(key)
    
            elif self.currentState == GameState.EXIT:
                isDone = True
        
         
            if self.currentState == GameState.GAME:
                self.game.draw()
            
            self.display.flip()
            
    def setState(self, state):
        #end current state
        if self.currentState == GameState.GAME:
            self.game.end()
            
        #initialize next state
        if state == GameState.GAME:
            state = self.game.init()
        
        #update current state
        self.currentState = state
    
    def end(self):   
        self.mixer.quit()
        self.display.quit()
        pygame.quit()
Ejemplo n.º 23
0
 def render_block(self, block, pos, screen, viewport):
     """#fast render water
     if block["name"] == "water":
         screen.blit(World.block_images[block["id"]],
                     Convert.world_to_viewport([Convert.chunk_to_world(pos[0], self), pos[1]], viewport))"""
     #don't render air
     if block["name"] != "air":
         #print(block["name"] + " " + str(block["id"]))
         Game.get_world().render_block(block["id"], [Convert.chunk_to_world(pos[0], self), pos[1]], block["connectedTexture"], screen, viewport)
     if Game.DEBUG:
         #draw bounding box
         pygame.draw.rect(screen, Game.BLACK, pygame.Rect(Convert.chunk_to_viewport(pos, self, viewport), (Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE)), 1)
Ejemplo n.º 24
0
    def __init__(self, **kwargs):
        self.questStatus = QuestStatus.NOT_STARTED
        self.questName = None
        self.startConversation = None
        self.progressConversation = None
        self.completedConversation = None

        self.questGivingNPC = None
        self.questReturnNPC = None
        self.questRequirements = set()
        
        Game.addQuest(self)
Ejemplo n.º 25
0
 def startGame(self,playerID,playerLetter):
     if (self.gameThreads[playerID]) is None:
         return "0290 PLAYER NOT FOUND"
     game = Game(False)
     thread = GameThread(game)
     #lock
     self.gameThreads[playerID] = thread
     #release
     thread.start()
     if game.start(playerLetter):
         return "0210 GAME IS STARTED"
     return "0999 UNKOWN ERROR"
Ejemplo n.º 26
0
 def draw_tooltip(self, screen, name, description = []):
     font = Game.get_font(False)
     big_font = Game.get_font(True)
     mouse_pos = pygame.mouse.get_pos()
     
     name_image = GUI.render_string_array([name], big_font, 0, Game.WHITE)
     desc_image = GUI.render_string_array(description, font, 0, Game.WHITE)
     name_width = name_image.get_width()
     name_height = name_image.get_height()
     desc_width = desc_image.get_width()
     desc_height = desc_image.get_height()
     width = max(name_width, desc_width)
     height = name_height
     if desc_height > 0:
         height += TOOLTIP_GAP + desc_height
     corner = 4 * Game.SCALE
     edge = 2 * corner
     
     pos = (mouse_pos[0] + corner, mouse_pos[1])
     
     #if too long, flip it to the other side of the mouse
     if pos[0] + width + 2 * corner > Game.SCREEN_WIDTH:
         pos = (max(pos[0] - width - 4 * corner, 0), pos[1]) #gap for mouse
     if pos[1] + height + 2 * corner > Game.SCREEN_HEIGHT:
         pos = (pos[0], pos[1] - height - 2 * corner)
     
     #top border
     screen.blit(Images.tooltip_pieces[0][0], pos)
     for x in range(0, width, edge):
         screen.blit(Images.tooltip_pieces[0][1], (pos[0] + corner + x, pos[1]))
     screen.blit(Images.tooltip_pieces[0][2], (pos[0] + 3 * corner + x, pos[1]))
     
     #middle
     slices = math.ceil(height / edge)
     for s in range(slices):
         y = height * s // slices
         screen.blit(Images.tooltip_pieces[1][0], (pos[0], pos[1] + corner + y))
         for x in range(0, width, edge):
             screen.blit(Images.tooltip_centers[((x + y) // edge) % 4], (pos[0] + corner + x, pos[1] + corner + y))
         screen.blit(Images.tooltip_pieces[1][2], (pos[0] + 3 * corner + x, pos[1] + corner + y))
     
     #bottom border
     y = corner + height
     screen.blit(Images.tooltip_pieces[2][0], (pos[0], pos[1] + y))
     for x in range(0, width, edge):
         screen.blit(Images.tooltip_pieces[2][1], (pos[0] + corner + x, pos[1] + y))
     screen.blit(Images.tooltip_pieces[2][2], (pos[0] + 3 * corner + x, pos[1] + y))
     
     #text
     screen.blit(name_image, (pos[0] + corner, pos[1] + corner))
     screen.blit(desc_image, (pos[0] + corner, pos[1] + corner + name_height + TOOLTIP_GAP))
Ejemplo n.º 27
0
    def worldMapTest(self):
        ''' Set up world map test '''
        self.worldMap = W.EriuWorldMap(width = C.WORLD_MAP_WIDTH, height = C.WORLD_MAP_HEIGHT, num_regions = C.NUM_REGIONS)
        self.worldMap.buildMap()

        self.player = P.Player()
        self.worldMap.placePlayer(self.player)

        self.openShelf()

        G.ui.setPlayer(self.player)
        G.setCurrentLevel(self.worldMap)

        self.play()
Ejemplo n.º 28
0
 def update(self, world):
     if self.hurt_time > -1:
         if self.hurt_time == 0:
             self.hurt = False
         self.hurt_time -= 1
     self.knockback[0] = Game.cutoff(self.knockback[0], ent.DamageSource.KNOCKBACK_FALLOFF)
     self.knockback[1] = Game.cutoff(self.knockback[1], ent.DamageSource.KNOCKBACK_FALLOFF)
     if self.knockback[0] != 0:
         self.vel[0] += self.knockback[0]
         self.knockback[0] += math.copysign(ent.DamageSource.KNOCKBACK_FALLOFF, -self.knockback[0])
     if self.knockback[1] != 0:
         self.vel[1] += self.knockback[1]
         self.knockback[1] += math.copysign(ent.DamageSource.KNOCKBACK_FALLOFF, -self.knockback[1])
     super().update(world)
Ejemplo n.º 29
0
    def townTest(self):
        name = getPlaceName()
        d = EriuTownLevel(tilesWide = 3, tilesHigh = 3, area = None, name = name, depth = 0)
        d.buildLevel()

        self.player = P.Player()
        d.placeCreatureAtRandom(self.player, False)

        self.openShelf()

        G.ui.setPlayer(self.player)
        G.setCurrentLevel(d)

        self.play()
Ejemplo n.º 30
0
def main():
    print('Marco Bros Starting')

    pygame.init()
    pygame.font.init()
    win = pygame.display.set_mode((1280, 720))
    pygame.display.set_caption('Marco Bros')

    clock = pygame.time.Clock()

    game = Game(win, clock)
    game.gameloop()

    print('exited game')
Ejemplo n.º 31
0
 def reset(self):
     del self.pygame
     self.pygame = Game.Pygame2D()
     obs = self.pygame.observe()
     return obs
Ejemplo n.º 32
0
def main():

    game = Game()
    game.run()
Ejemplo n.º 33
0
 def __init__(self):
     cmd.Cmd.__init__(self)
     self.prompt = "Enter your command: \n"
     self.game = Game()
Ejemplo n.º 34
0
    def setupdb(self):
        # If you set this to 1, it will print out all data as it populates the datbase.
        debugging = 0

        # make a database connection to the game database
        if debugging:
            print('connecting to database')
        conn = connect('./db/game.db')

        # create our cursor
        if debugging:
            print('creating cursor')
        cur = conn.cursor()

        # create our armor table in the database
        if debugging:
            print('creating table for armor')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS armor (level INTEGER, class TEXT, name TEXT, type TEXT, basedef INTEGER, durability INTEGER)'''
        )

        # insert our armor table in the database
        if debugging:
            print('inserting armor into database')
        with open('./csv/armor.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO armor VALUES (?,?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM armor')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our enemy table in the database
        if debugging:
            print('creating table for enemies')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS enemies(level INT, firstname TEXT, middlename TEXT, lastname TEXT, attack INTEGER, xp INTEGER, gold INTEGER, hp INTEGER, def INTEGER, status TEXT)'''
        )

        # insert our enemy table in the database
        if debugging:
            print('inserting enemies into database')
        with open('./csv/enemies.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute(
                    'INSERT INTO enemies VALUES (?,?,?,?,?,?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM enemies')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our items table in the database
        if debugging:
            print('creating table for items')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS items(level INT, grade INT,name TEXT,effect INT,value INT)'''
        )

        # insert our items table in the database
        if debugging:
            print('inserting items into database')
        with open('./csv/items.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO items VALUES (?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM items')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our levelnotes table in the database
        if debugging:
            print('creating table for levelnotes')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS levelnotes(Level INT,HP INT,ATK INT,DEF INT,xptonextlevel INT, dodge INT )'''
        )

        # insert our levelnotes table in the database
        if debugging:
            print('inserting levelnotes into database')
        with open('./csv/levelnotes.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO levelnotes VALUES (?,?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM levelnotes')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our shields table in the database
        if debugging:
            print('creating table for shields')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS shields (level INT,class TEXT,name TEXT,type TEXT,basedef INT,durability INT)'''
        )

        # insert our shields table in the database
        if debugging:
            print('inserting shields into database')
        with open('./csv/shields.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO shields VALUES (?,?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM shields')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our weapons table in the database
        if debugging:
            print('creating table for weapons')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS weapons ( level INTEGER ,class TEXT ,name TEXT ,type TEXT,baseattack INTEGER ,durability INTEGER ,power TEXT)'''
        )

        # insert our weapons table in the database
        if debugging:
            print('inserting weapons into database')
        with open('./csv/weapons.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO weapons VALUES (?,?,?,?,?,?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM weapons')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))

        # create our riddles table in the database
        if debugging:
            print('creating table for riddles')
        cur.execute(
            '''CREATE TABLE IF NOT EXISTS riddles (question TEXT ,answer TEXT)'''
        )

        # insert our riddles table in the database
        if debugging:
            print('inserting riddles into database')
        with open('./csv/riddles.csv', 'r') as fin:
            dr = csv.reader(fin)
            for i in dr:
                if debugging:
                    print('inserting ' + str(i))
                cur.execute('INSERT INTO riddles VALUES (?,?);', i)
            if debugging:
                cur.execute('SELECT * FROM riddles')
                rows = cur.fetchall()
                for row in rows:
                    print('QUERY ALL: ' + str(row))
        # commit the changes
        conn.commit()
        # close the database connection to let other operations use it
        conn.close()
        Game.centerprint('...Have fun')
Ejemplo n.º 35
0
server = ""
port = 5555

server_ip = socket.gethostbyname(server)

try:
    s.bind((server, port))

except socket.error as e:
    print(str(e))

s.listen(2)
print("Waiting for a connection")

game = Game()
connected = set()
games = {}
idCount = 0


def threaded_client(conn, p, gameId):
    global idCount
    # conn.send(str.encode(str(p)))
    # print(conn)

    while True:
        try:
            data = conn.recv(2048)
            if gameId in games:
                game = games[gameId]
Ejemplo n.º 36
0
skittles_agent2 = Agent(skittles_move)
skittles_agent2.S = LoadTable("TTT Skittles 2.json")
skittles_agent2.post = skittles_after

# ### Running the Game - Random vs Skittles 2

# In[14]:

W = []
L = []
T = []

n = []
total_games = 0
for i in range(100):
    g = Game(number_of_games=1000)
    g.display = False
    result = g.run(random_agent, skittles_agent2)

    SaveTable(skittles_agent1.S, "TTT Skittles 1.json")
    SaveTable(skittles_agent2.S, "TTT Skittles 2.json")

    percent_wins = sum([_ == 1 for _ in result]) / len(result) * 100
    percent_losses = sum([_ == 2 for _ in result]) / len(result) * 100
    percent_ties = sum([_ == 0 for _ in result]) / len(result) * 100

    total_games += g.number_of_games
    n.append(total_games)
    W.append(percent_wins)
    L.append(percent_losses)
    T.append(percent_ties)
Ejemplo n.º 37
0
            Game.clear()
            print("INVALID OPTION!\nPlease type a number.")
            input("PRESS ENTER TO CONTINUE...")
        # Otherwise, process the user's selection
        else:
            # If 1, play the game
            if choice == 1:
                game()
            # If 2, add custom words to CustomWords.txt
            elif choice == 2:
                add_words(custom_words)
                break
            # If 3, open Nick Lueth's LinkedIn page
            elif choice == 3:
                open_linkedin()
                break
            # If 4, quit the game
            elif choice == 4:
                exit(0)
            # Otherwise, prompt the user again
            else:
                print("That value is not a valid option...")
                sleep(1.5)


easy_words = Game.get_easy_words()
medium_words = Game.get_medium_words()
hard_words = Game.get_hard_words()
custom_words = Game.get_custom_words()
main_menu()
Ejemplo n.º 38
0
 def test_game_isinstance_of_game_class(self):
     game = Game_library.Game()
     message = "Object is not instance of Game class"
     self.assertIsInstance(game, Game_library.Game, message)
Ejemplo n.º 39
0
#!/usr/bin/python

import random
import sys
import os
import queue
import Game
from queue import Queue
import PerfectBot

os.environ["SDL_VIDEODRIVER"] = "dummy"


# Main game loop

Harta = [[0 for x in range(0, 3 + 1)] for y in range(0 + 3 + 1)]
newGame = Game.Game()
newGame.printMap()
newGame.play()









def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("State of the Art-ificial Intelligence")

    # <insert large block of code at bottom if shit goes south>

    # Loop until the user clicks the close button.
    games = []
    finishedGames = []
    # game1 = Game(screen, 0)
    # game2 = Game(screen, 1)

    numGames = 1

    for game in range(numGames):
        tempGame = Game(screen, game)
        games.append(tempGame)

    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for game in games:
            if game.isOver:
                finishedGames.append(game)
                games.remove(game)

        # update players --> in update() tell players to think()
        #in the think(), they should run the neural net once
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            """
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    user_player.direction = "left"
                    user_player.executeAction(0) 
                if event.key == pygame.K_RIGHT:
                    user_player.direction = "right"
                    user_player.executeAction(1)
                if event.key == pygame.K_UP:
                    user_player.executeAction(2)
                if event.key == pygame.K_SPACE:
                    user_player.executeAction(4)
 
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    user_player.executeAction(3)
                if event.key == pygame.K_RIGHT:
                    user_player.executeAction(3)
            """

            if event.type == pygame.USEREVENT:
                for game in games:
                    for player in game.entities:
                        if player.playerID == event.id:
                            eventPlayer = player
                if event.action == "attack":
                    eventPlayer.executeAction(4)
                elif event.action == "moveLeft":
                    eventPlayer.executeAction(0)
                    eventPlayer.direction = "left"
                elif event.action == "moveRight":
                    eventPlayer.executeAction(1)
                    eventPlayer.direction = "right"
                elif event.action == "jump":
                    eventPlayer.executeAction(2)
                elif event.action == "stop":
                    eventPlayer.executeAction(3)
                    eventPlayer.direction = "none"
                elif event.action == "damage":
                    eventPlayer.health -= 2
                else:
                    print("unkown event: ", event)

        # Update items in the level

        for game in games:
            game.level.update()
            # game.active_sprite_list.update()

        games[0].level.draw(screen)
        games[0].level.drawBG(screen)

        for game in games:
            # game.active_sprite_list.draw(screen)
            game.level.draw(screen)
            game.player.updateHealth()
            game.enemy.updateHealth()

        #time.sleep(.05)

        # mouse_pos = pygame.mouse.get_pos()

        # for player in players:
        #     # draw the lines between point
        #     player.distanceToPoint(player.enemyPos, True, BLUE)
        #     # player.distanceToPoint((800,500),True, RED, "X")
        #     player.updateHealth()
        # playerOne.updateHealth()
        # playerTwo.updateHealth()

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Ejemplo n.º 41
0
 def check_drunkeness(self, move):
     if self.current_round >= self.START_BREATH_TEST and self.lawyer_is_drunk(
     ):
         return Game.opposite_move(move)
     return move
Ejemplo n.º 42
0
from Game import *

Game = Game(5,5,"machine")
Ejemplo n.º 43
0
            GameX = GameX.humanPlayerInput()

            while not GameX:
                GameX = PrevGameX.humanPlayerInput()

        steps += 1

    GameX.printGameState()
    if GameX.utility == float('-inf'):
        print(screeOutput_youWin)
    elif GameX.utility == float('inf'):
        print('Computer Wins')
        print(screeOutput_youLose)
    else:
        print(screeOutput_tie)

    input('press enter')


if __name__ == '__main__':
    player = input('Do you want to start first ? \n[0-No ; 1-Yes]')

    TicTacToGame = None

    if player == '0' or player == '1':
        TicTacToGame = Game.TicTacTo(
            [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']], int(player))
        play(TicTacToGame, 4)
    else:
        player = input('Invalid Input \n Press Enter to exit')
Ejemplo n.º 44
0
import Game as game

game.Game()
Ejemplo n.º 45
0
 def test_game_default_initializes_instance_game_deck_object_correct(self):
     game = Game_library.Game()
     message = "Game - Deck Object is not instance of Deck class"
     self.assertIsInstance(game.game_deck, Deck_library.Deck, message)
Ejemplo n.º 46
0
# # player1 = Game.Computer.Player.Player(10,"Mike")
# player1 = Game.Computer.Computer(10,1)
# player2 = Game.Computer.Computer(10,2)
# player3 = Game.Computer.Computer(10,3)
# player4 = Game.Computer.Computer(10,4)
rock = 0
paper = 0
n = 100
for i in range(n):
    players = []

    nPlayers = 100
    for i in range(nPlayers):
        players.append(Game.Computer.Computer(1000,i+1))

    game = Game.Game(players)

    playersLeft = True

    rnd = 1
    while playersLeft:
        cleanout = []
        for player in game.players:
            if player.health <= 0 :
                cleanout.append(player)
        for item in cleanout:
            second = item
            game.players.remove(item)
        if len(game.players) <= 1:
            print(game.players[0].getLimits())
            rock += game.players[0].getLimits()[0]
Ejemplo n.º 47
0
Archivo: main.py Proyecto: Vodak/SINS
"""
Fichier main qui lance le programme
"""

from Game import *

game = Game()
game.play()
Ejemplo n.º 48
0
def main():
    game = Game()
    game.start()
Ejemplo n.º 49
0
Archivo: parta.py Proyecto: orensul/AI1
    def main():

        file_name = os.path.abspath(sys.argv[1])
        Game.Game(file_name)
Ejemplo n.º 50
0
import Game

if __name__ == "__main__":
    game = Game.Game()
    game.on_execute()
Ejemplo n.º 51
0
def async_Q(max_time_steps: int, reward: int, penalty: int,
            checkpointFrequency: int, checkpoint_dir,
            policyNetwork: List[NeuralNetwork], policySess,
            targetNetwork: List[NeuralNetwork], targetSess, lock: Lock,
            queue: Queue):
    """

    :param max_time_steps:
    :param reward:
    :param penalty:
    :param checkpointFrequency:
    :param checkpoint_dir:
    :param policyNetwork:
    :param policySess:
    :param targetNetwork:
    :param targetSess:
    :param lock:
    :param queue:
    :return:
    """
    time_steps = 0
    # Create random epsilon list
    epsilon = []  # type: List[float]
    for idx in range(Constants.numberOfSnakes):
        while True:
            e = np.random.normal(0.8, 0.1)
            if e < 1:
                epsilon.append(e)
                break

    while True:
        g = Game.Game()  # creates game object
        #Start a Game
        snake_list = g.snakes  # contains list of Snake objects
        episodeRunning = True  # True if game is running, false if not
        pastStateAlive = [True for i in range(Constants.numberOfSnakes)
                          ]  # keeps track if Snakes were alive
        actions_taken = [0 for j in range(Constants.numberOfSnakes)
                         ]  # holds the actions last taken for each snake
        initial_state = [0] * Constants.numberOfSnakes

        # initialize lists
        state = [[] for _ in range(Constants.numberOfSnakes)]
        action = [[] for _ in range(Constants.numberOfSnakes)]
        reward = [[] for _ in range(Constants.numberOfSnakes)]
        next_state_Q = [[] for _ in range(Constants.numberOfSnakes)]

        while episodeRunning:  #Meaning in an episode
            for idx in range(Constants.numberOfSnakes):  # for each snake
                # contains all snakes except the currently indexed one
                pruned_snake_list = [
                    snake for snake in snake_list if snake != snake_list[idx]
                ]
                if g.snakes[idx].alive:
                    # Get state of snake
                    initial_state[idx] = Agent.getState(g.snakes[idx],
                                                        pruned_snake_list,
                                                        g.food,
                                                        normalize=True)
                    # Choose action to take using epsilon greedy action
                    actions_taken[idx] = epsilon_greedy_action(
                        g.snakes[idx], policySess[idx], policyNetwork[idx],
                        initial_state[idx], epsilon[idx])
                    state[idx].append(
                        initial_state[idx]
                    )  # keep track of state by appending it to list
                    action[idx].append([
                        actions_taken[idx]
                    ])  # keep track of action by appending it to list
                    pastStateAlive[idx] = True
                else:
                    actions_taken[idx] = None
                    pastStateAlive[idx] = False

            # Try to move all snakes according to their computed actions
            try:
                # List[int]       ,  bool
                single_step_reward, episodeRunning = g.move(
                    actions_taken)  # rewards for snake actions, game end state
            except AssertionError:
                print("Error making moves {} in game :\n{}".format(
                    actions_taken, g))

            #Now we transition to the next state
            time_steps += 1
            lock.acquire()
            T = queue.get()
            T += 1
            queue.put(T)
            lock.release()

            # Every 500 time steps...
            if T % checkpointFrequency == 0:
                # for each snake...
                for idx in range(Constants.numberOfSnakes):
                    # Save policy and target network checkpoints
                    policyNetwork[idx].save_model(
                        policySess[idx],
                        "{}/policy_{}_{}.ckpt".format(checkpoint_dir, T, idx))
                    targetNetwork[idx].save_model(
                        targetSess[idx],
                        "{}/target_{}_{}.ckpt".format(checkpoint_dir, T, idx))

            # for each snake...
            for idx in range(Constants.numberOfSnakes):
                # if snake is alive, append its reward to its reward list. (Keeps track of rewards for each snake)
                if (pastStateAlive[idx]
                    ):  # To check if snake was already dead or just died
                    reward[idx].append([single_step_reward[idx]])
                    # contains all snakes except the currently indexed one
                    pruned_snake_list = [
                        snake for snake in snake_list
                        if snake != snake_list[idx]
                    ]
                    # if the game is over or snake is dead...
                    if not episodeRunning or not g.snakes[
                            idx].alive:  # train on terminal
                        next_state_Q[idx].append([0])
                        # thread waits here until thread lock is available
                        lock.acquire()
                        # Update agent policy
                        policyNetwork[idx].train(policySess[idx], state[idx],
                                                 action[idx], reward[idx],
                                                 next_state_Q[idx])
                        lock.release()
                        # clear lists
                        state[idx], action[idx], reward[idx], next_state_Q[
                            idx] = [], [], [], []
                    else:
                        # get snake state and get next best action to take
                        final_state = Agent.getState(g.snakes[idx],
                                                     pruned_snake_list,
                                                     g.food,
                                                     normalize=True)
                        next_state_best_Q = best_q(g.snakes[idx],
                                                   targetSess[idx],
                                                   targetNetwork[idx],
                                                   [final_state])
                        next_state_Q[idx].append([next_state_best_Q])

            # Update agent policy
            if time_steps % Constants.AQ_asyncUpdateFrequency == 0:
                # for each snake
                for idx in range(Constants.numberOfSnakes):
                    if pastStateAlive[idx] and g.snakes[
                            idx].alive and episodeRunning:  # train only if non-terminal, since terminal case is handled above
                        lock.acquire()
                        # update agent policy
                        policyNetwork[idx].train(policySess[idx], state[idx],
                                                 action[idx], reward[idx],
                                                 next_state_Q[idx])
                        lock.release()
                    state[idx], action[idx], reward[idx], next_state_Q[
                        idx] = [], [], [], []

            T = queue.get()
            queue.put(T)
            if T % Constants.AQ_globalUpdateFrequency == 0:
                for idx in range(Constants.numberOfSnakes):
                    checkpoint_path = "{}/transfer_{}.ckpt".format(
                        checkpoint_dir, idx)
                    lock.acquire()
                    policyNetwork[idx].save_model(policySess[idx],
                                                  checkpoint_path)
                    targetNetwork[idx].restore_model(targetSess[idx],
                                                     checkpoint_path)
                    lock.release()

            T = queue.get()
            queue.put(T)
            if T >= max_time_steps:
                break

        print("Episode done on thread {}. T = {}.".format(get_ident(), T))
        T = queue.get()
        queue.put(T)
        #  break out of loop when all time steps done
        if T >= max_time_steps:
            break
    print("Thread {} complete.".format(get_ident()))
    # save policy and target models
    for idx in range(Constants.numberOfSnakes):
        lock.acquire()
        policyNetwork[idx].save_model(
            policySess[idx],
            "{}/policy_{}_{}.ckpt".format(checkpoint_dir, T + 1, idx))
        targetNetwork[idx].save_model(
            targetSess[idx],
            "{}/target_{}_{}.ckpt".format(checkpoint_dir, T + 1, idx))
        lock.release()
Ejemplo n.º 52
0
def graphical_inference(size_of_hidden_layer: int = 20,
                        load_dir="checkpoints",
                        load_time_step: int = 500,
                        play: bool = False,
                        scalingFactor: int = 9):
    """
    To render graphics of the trained agents
    :param size_of_hidden_layer:
    :param load_dir:
    :param load_time_step:
    :param play:
    :param scalingFactor:
    :return:
    """
    import pygame
    import GraphicsEnv

    numSnakes = Constants.numberOfSnakes  # type: int
    if play:
        numSnakes += 1
    colors = np.random.randint(0, 256, size=[numSnakes, 3])
    if play:  # user interacts with the agents
        colors[0] = (0, 0, 0)  # player's snake is always black
    # Create Game Window
    win = pygame.display.set_mode((scalingFactor * Constants.gridSize,
                                   scalingFactor * Constants.gridSize))
    screen = pygame.Surface(
        (Constants.gridSize + 1, Constants.gridSize + 1))  # Grid Screen
    pygame.display.set_caption("Snake Game")
    crashed = False

    targetNetwork = []  # type: List[NueralNetwork]
    targetSess = []  # type: List[tf.Session]
    if play:
        targetNetwork.append(None)
        targetSess.append(None)
    length = Agent.getStateLength()
    for idx in range(int(play), numSnakes):
        targetNetwork.append(
            FunctionApproximator.NeuralNetwork(
                length, size_of_hidden_layer=size_of_hidden_layer))
        targetSess.append(tf.Session(graph=targetNetwork[idx].graph))
        targetNetwork[idx].init(targetSess[idx])
        targetNetwork[idx].restore_model(
            targetSess[idx],
            "{}/target_{}_{}.ckpt".format(load_dir, load_time_step,
                                          idx - int(play)))

    g = Game.Game(numSnakes)
    episodeRunning = True

    while episodeRunning and not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True

        actionList = []
        if play:
            actionList.append(GraphicsEnv.manual_action(g.snakes[0], event))
        for i in range(int(play), numSnakes):
            snake = g.snakes[i]
            if not snake.alive:
                actionList.append(None)
                continue
            opponentSnakes = [
                opponent for opponent in g.snakes if opponent != snake
            ]
            state = Agent.getState(snake,
                                   opponentSnakes,
                                   g.food,
                                   normalize=True)
            action, _ = targetNetwork[i].max_permissible_Q(
                targetSess[i], [state], snake.permissible_actions())
            actionList.append(action)

        singleStepRewards, episodeRunning = g.move(actionList)
        GraphicsEnv.displayGame(g, win, screen, colors)
Ejemplo n.º 53
0
import Game
Game.play()
Ejemplo n.º 54
0
from Game import *

MinimaxAI_win = 0
AlphaBetaAI_win = 0

for _ in range(1):
    winner = Game().play('4', '5')
    if winner == BLACK:
        MinimaxAI_win += 1
    elif winner == WHITE:
        AlphaBetaAI_win += 1
    winner = Game().play('5', '4')
    if winner == BLACK:
        AlphaBetaAI_win += 1
    elif winner == WHITE:
        MinimaxAI_win += 1

print('勝利数\n'
      'MinimaxAI: %d \n'
      'AlphaBetaAI: %d' % (MinimaxAI_win, AlphaBetaAI_win))
Ejemplo n.º 55
0
class Controller(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "Enter your command: \n"
        self.game = Game()

    def start_game(self):
        self.game.display_game_status()

    def do_attack(self, line):
        if self.game.attack():
            print("\nYou killed the zombies")
            self.game.display_game_status()
        else:
            print("\nNo zombie to attack\n")

    def do_run(self, direction):
        if self.game.run(direction):
            print("\nYou ran away from the zombies. You lost 1 HP!")
            self.game.display_game_status()

    def do_cower(self, line):
        if self.game.cower():
            print("\nYou rested for a while")
            self.game.display_game_status()
        else:
            print("\nYou must kill the zombies first\n")

    def do_move(self, direction):
        if self.game.move(direction):
            print("\nYou are moving to " + direction)
            self.game.display_game_status()

    def do_get_totem(self, line):
        if self.game.get_totem():
            print("\nYou found the totem!")
            self.game.display_game_status()
        else:
            print("\nNo totem in this zoom.\n")

    def do_bury_totem(self, line):
        if self.game.bury_totem():
            print("\nTotem buried. You win the game!\n")
            sys.exit()
        else:
            print("\nYou can't do that!\n")

    def do_get_item(self, line):
        if self.game.get_item():
            self.game.display_game_status()
        else:
            print("\nNo item to get.\n")

    def do_save(self, line):
        if len(line) == 0:
            print("You must type a file name")
        else:
            file = open("saves/" + line + ".data", "wb")
            pickle.dump(self.game, file)
            file.close()
            print("File saved\n")

    def do_load(self, line):
        try:
            file = open("saves/" + line + ".data", "rb")
            self.game = pickle.load(file)
            file.close()
            print("File loaded\n")
            self.game.display_game_status()
        except (IOError, pickle.UnpicklingError):
            print('Error! no such file or invalid save file')

    def do_quit(self, line):
        print("\n----------")
        print("Game ended")
        print("----------")
        return 1

    def do_help(self, line):
        print("move <Direction>	- Move player <Direction> \
                run <Direction> 	- Escape zombies by running <Direction> \
                attack			    - Attack zombies in current room \
                cower			    - Hide in current room and not move this turn \
                get_item		    - Retrieve weapon from current room \
                get_totem		    - Retrieve totem (Only in Evil Temple) \
                bury_totem		    - Bury totem (Only in graveyard) \
                save			    - Save current game to <path> \
                load                - Load the saved game <path> \
                quit			    - Quit game \
                help			    - Display this help file")
Ejemplo n.º 56
0
 def reset(self):
     self.game = Game.Game()
Ejemplo n.º 57
0
from Piece import *
from Board import *
from Game import *

if __name__== "__main__":
    res = {}
    for d in range(1,3): # avoiding highest difficulty because it takes too long
        for h in range(0,3):
            res[(d,h)] = 0
            for k in range(20):
                g = Game(difficulty=d,heuristic=h,DEBUG=True)
                g.play()
                res[(d,h)] += g.winner
    print(res)
Ejemplo n.º 58
0
def game():
    """
    Initiates the game loop found in the Game.py file.
    """
    Game.main()
Ejemplo n.º 59
0
        ##        print("{} removed {} - {}".format(game.turn.ident, edge[0], edge[1]))
        point_awarded = game.remove_bar(game.turn, edge[0], edge[1])
        if not (game.extra_turn and point_awarded):
            game.change_turns()

    if game.player1.score > game.player2.score:
        return game.player1.ident
    elif game.player1.score < game.player2.score:
        return game.player2.ident
    else:
        return 0


player1_wins = 0
player2_wins = 0
ties = 0
for i in range(num_trials):
    game = Game(num_vertices, False)
    game.graph.make_clique_graph()
    winner = play_game(game)
    if winner == game.player1.ident:
        player1_wins += 1
    elif winner == game.player2.ident:
        player2_wins += 1
    else:
        ties += 1

print("Player 1 Wins: {}".format(player1_wins))
print("Player 2 Wins: {}".format(player2_wins))
print("Ties: {}".format(ties))
Ejemplo n.º 60
0
                for hcard in pbo.hand:
                    if hcard.title == picked.title:
                        pb.hand.append(hcard)
                        pbo.hand.remove(hcard)

    def clash_effect(self, game, pbidx):
        pb = game.playerboards[pbidx]
        card = pb.player.choosecardtodiscard(game, pbidx, ["hand", "recovery"])
        pb.discard(card, ["hand", "recovery"])

if __name__ == '__main__':
    import Game as G
    import SimpleHumanPlayer as SHP

    b = Bureaucrat()
    g = G.Game(3)
    for p in range(3):
        shp = SHP.SimpleHumanPlayer("SHP " + str(p+1))
        g.playerboards[p].player = shp
    c1 = C.Card("Not this one", 500)
    c2 = C.Card("Not this one either", 501)
    c3 = C.Card("Yes this one", 503)
    g.addtocardlist(c1)
    g.addtocardlist(c2)
    g.addtocardlist(c3)
    g.addtocardlist(b)
    g.sendcardlisttoboards()
    g.playerboards[0].readytoplay(b)
    print("When prompted, choose one of the cards.")
    # g.playallcards()
    g.playcards()