Пример #1
0
def find_moves(grid, chain, foundation, next_brick, first_move = 0):
    safety = list()
    p = player(grid)
    p1 = player(grid)
    for iterations in range(1000):
        p.new_grid(grid)
        mymoves = list()
        if first_move != 0:
            p.turn(first_move[0], first_move[1])
            mymoves.append(first_move[1])
            
        for i in foundation:
            move = grid_moves[random.randint(0, 9)]
            score = p.turn(i, move)
            if score > 0 or score < 0:
                break

            mymoves.append(move)

        if len(mymoves) < len(foundation):
            continue

        for move in possible_moves:
            p1.new_grid(p.grid)
            score = p1.turn(next_brick, move)
            if score >= 3:
                return mymoves+[move]
            elif p1.currentscore > 70*6:
                safety = mymoves+[move]
    return safety
Пример #2
0
 def __init__(self, player1, player2):
     self.player1 = player.player(player1)
     self.player2 = player.player(player2)
     self.deck = []
     self.winner = 0
     self.turno = None
     self.isthereawinner = 0
Пример #3
0
	def selectPlayers(self,dealerObj):
		print("******************************************")
		print(" Welcome to the Texas Hold'em Poker Game")
		print("******************************************")
		print("What Game would you like :")
		print("1. Human PLayer vs  Human Player")
		print("2. AI Agent     vs  Human Player")
		print("3. AI Agent     vs  AI Agent")
		selected= 0
		while(selected == 0):
			choice=int(input("Enter Your Choice : "))
			if (choice ==1):
				self.players.append(player(1, dealerObj))
				self.players.append(player(2, dealerObj))
				selected= 1
				return self.players
			elif (choice==2):
				level=int(input("Enter Agent Level (1-3) :"))
				level1=self.checkLevel(level)
				self.players.append(agent(1, dealerObj,level1))
				self.players.append(player(2, dealerObj))
				selected= 1
				return self.players
			elif(choice==3):
				level=int(input("Enter Agent 1 Level (1-3) :"))
				level1=self.checkLevel(level)
				self.players.append(agent(1, dealerObj,level1))
				level=int(input("Enter Agent 2 Level (1-3) :"))
				level2=self.checkLevel(level)
				self.players.append(agent(2, dealerObj,level2))
				selected= 1
				return self.players
			else:
				print("You Entered the Wrong choice")
Пример #4
0
 def __init__(self):
     self.player1 = player("player1")
     self.player2 = player("player2")
     self.turn = 0
     self.player1turn = True
     self.horizontalMove = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7}
     self.verticalMove = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7}
Пример #5
0
    def play_video(self):
        # Get current list item details...
        title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
        thumbnail = xbmc.getInfoImage("ListItem.Thumb")
        plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
        genre = unicode(xbmc.getInfoLabel("ListItem.Genre"), "utf-8")
        total_time = unicode(xbmc.getInfoLabel("ListItem.EndTime"), "utf-8")
        # Show wait dialog while parsing data...
        dialog_wait = xbmcgui.DialogProgress()
        dialog_wait.create(control.lang(30504), title)

        if self.video_url is None:
            # Close wait dialog...
            dialog_wait.close()
            del dialog_wait

            # Message...
            xbmcgui.Dialog().ok(control.lang(30000), control.lang(30505))
            return

        # Close wait dialog...
        dialog_wait.close()
        del dialog_wait

        player().run({
            "url": self.video_url,
            "thumb": thumbnail,
            "plot": plot,
            "genre": genre,
            "title": title,
            "endTime": total_time,
            "repeat": "Repeat One"
        })
        return
Пример #6
0
def main():
    """Main executable for a gameserver

    This program establishes an open recieving socket at the indicated host 
    initialized at 0.0.0.0:6969 here. It then enters an infinite loop. 
    This loop checks for readable sockets every loop, and removes connections
    that it finds to be closed or otherwise disconnected. Otherwise, hands
    down the recieved message to the players' current game lobby object, 
    in the dictionary at the record accorind to their player.state string,
    or if the player doesn't have a state, it passes on to cmdInterpreter.
    Also outputs everything here to stdout, and flushes every loop to allow
    for live log output.
    """

    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_addr = ('0.0.0.0', 6969)
    server_sock.bind(server_addr)
    server_sock.listen()
    print("Listening on", server_addr)

    player_list.append(player.player(server_sock, server_addr))

    while True:

        for p in player_list:  # Loop through sockets, selecting individually

            read = select.select([p.sock], [], [], 0)[0]

            #print(p.name, len(read))        # Some nice diagnostics to look at
            #time.sleep(3)

            for r in read:  # Searching one socket at a time, we know the owner

                if r == server_sock:  # Accept incoming connections
                    s, a = server_sock.accept()
                    p = player.player(s, a)
                    print('Connection from', a)
                    player_list.append(p)
                    p.sendUpdate('\n    Welcome!\n' + cmdlist)

                else:  # Otherwise, recieve client message

                    try:
                        dat = r.recv(8192).decode()
                        if dat == "":  # Check if connection closed
                            print(p.name, "connection closed")
                            purge(p)
                        else:  # Otherwise, handle normally
                            if p.state is None:
                                cmdInterpereter(p, dat)
                            else:
                                game_list[p.state].updateGame(p, dat)

                    except:  # Connection died, kill
                        print(p.name, "connection died")
                        purge(p)
                        continue

        sys.stdout.flush()  # Flushing every loop, so we can live view the log
Пример #7
0
 def __init__(self):
     self.Player1 = player(playerType.robot, 1,'r',0)
     self.Player2 = player(playerType.robot, 2,'b',0)
     self.Player1.opponent = self.Player2
     self.Player2.opponent = self.Player1
     self.gamePositions = 'A','B','C','D'
     self.currentGame = game(self.Player1, self.Player2)
     self.plc = S71200.S71200("151.141.148.26")
Пример #8
0
 def __init__(self, numHands, numFingers):
     self.numHands = numHands
     self.numFingers = numFingers
     self.root = state(player(numHands, numFingers),
                       player(numHands, numFingers), 0)
     self.root.score = 0
     self.allStates = set()
     self.allStates.add(self.root)
Пример #9
0
    def createInitPlayers(self,dsn):
        app.store = StoreP(app.config['dsn'])

        newPlayer = player('Hasan', 'Male', 'Turkish', '1994', 1)
        app.store.addPlayer(newPlayer, dsn)
        newPlayer2 = player('Rose', 'Female', 'English', '1995', 2)
        app.store.addPlayer(newPlayer2, dsn)
        newPlayer3 = player('Dimitrov', 'Male', 'Russian', '1993', 4)
        app.store.addPlayer(newPlayer3, dsn)
Пример #10
0
 def game_reset(self):
     self.player1 = player.player((0, 100), 5, (0, 255, 0), "Player 1")
     self.player2 = player.player(
         (self.screen_size[0] - self.player1.width, 100), -5, (0, 0, 255),
         "Player 2")
     self.level = 1
     self.spike_arr = []
     self.static_spike_arr = []
     self.gen_static_spike()
Пример #11
0
 def __init__(self, screen, path1, path2, start_poses, tile_size):
     self.Player1 = player(screen, path1, start_poses[0], tile_size)
     self.Player2 = player(screen, path2, start_poses[1], tile_size)
     self.is_exec = True
     self.num = 2
     self.cur_num = 0
     self.map = 0
     self.map_size = 0
     self.a = 0
     self.b = 0
Пример #12
0
 def __init__(self):
     self.p = []
     self.p0 = player()  #dummy for simplicity in list operations
     self.p1 = player()
     self.p2 = player()
     self.p.append(self.p0)
     self.p.append(self.p1)
     self.p.append(self.p2)
     self.mainstart = 1
     self.start = 1
Пример #13
0
	def create(self,name,points_scored,points_lost,result):
		obj = player(name,points_scored,points_lost,1,0) if result==1 else player(name,points_scored,points_lost,0,1)
		self.playersDict[name]=obj
		if self.firstNode == None:	#this is the first node to be inserted in the rankingsDict
			self.firstNode = obj
			self.lastNode = obj
		else:
			if result == 1:			#win/lost
				self.adjustnode(obj,self.lastNode,int(points_scored),int(points_lost),1,0)
			else:
				self.adjustnode(obj,self.lastNode,int(points_scored),int(points_lost),0,1)
Пример #14
0
def eventCustom(x, y):
    if not data.makeCustomScreen:
        if 200 < x < 500 and 300 < y < 350:
            data.startScreen = False
            data.animatefirst = True
            p2Pieces = {"pawn": [(6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), \
        (6, 6), (6, 7)], "bishop": [(7, 2), (7, 5)], "rook": [(7, 0), (7, 7)], \
        "queen": [(7, 4)], "king": [(7, 3)], "knight": [(7, 1), (7, 6)]}
            p1Pieces = {"pawn": [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), \
        (1, 6), (1, 7)], "bishop": [(0, 2), (0, 5)], "rook": [(0, 0), (0, 7)], \
        "queen": [(0, 4)], "king": [(0, 3)], "knight": [(0, 1), (0, 6)]}
            data.playerOne = player.player(data.player1turn, p1Pieces, [], [],
                                           "p1")
            data.playerTwo = player.player(data.player2turn, p2Pieces, [], [],
                                           "p2")
            s.initializePieces(data.playerOne)
            s.initializePieces(data.playerTwo)
            data.addScreen = True
            s.getKings()
            data.rows = 8
            data.cols = 8
        elif 200 < x < 500 and 400 < y < 450:
            #print("no2")
            data.player2turn = True
            data.player1turn = False
            data.startScreen = False
            data.animatefirst = True
            data.addScreen = True
            p2Pieces = {"pawn": [(6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), \
        (6, 6), (6, 7)], "bishop": [(7, 2), (7, 5)], "rook": [(7, 0), (7, 7)], \
        "queen": [(7, 4)], "king": [(7, 3)], "knight": [(7, 1), (7, 6)]}
            p1Pieces = {"pawn": [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), \
        (1, 6), (1, 7)], "bishop": [(0, 2), (0, 5)], "rook": [(0, 0), (0, 7)], \
        "queen": [(0, 4)], "king": [(0, 3)], "knight": [(0, 1), (0, 6)]}
            data.playerOne = player.player(data.player1turn, p1Pieces, [], [],
                                           "p1")
            data.playerTwo = player.player(data.player2turn, p2Pieces, [], [],
                                           "p2")
            s.initializePieces(data.playerOne)
            s.initializePieces(data.playerTwo)
            s.getKings()
            data.rows = 8
            data.cols = 8
            data.cpu = True
        elif 200 < x < 500 and 500 < y < 550 and not data.custom:
            data.help = True
        elif 200 < x < 500 and 600 < y < 650 and not data.help:
            data.custom = True
            data.makeCustomScreen = True
            data.customAnim = True
        elif 200 < x < 500 and 660 < y < 680:
            data.startField = True
        else:
            data.startField = False
Пример #15
0
def main():
    print('Welcome to Rock, Paper, Scissors, Lizard, Spock')
    player1 = player('Player 1')
    player2 = player('Player 2')
    game1 = game('Game 1', player1, player2)
    game2 = game('Game 2', player1, player2)
    game3 = game('Game 3', player1, player2)
    games = (game1, game2, game3)
    getPlayer2(player2)
    for gameInstance in games:
        game.getrResult(gameInstance)
    playAgain()
    def run(self):
        tracking_home = self.input()['tracking_home'].load()  # Row of tracking data
        tracking_away = self.input()['tracking_away'].load()  # Row of tracking data
        ball_start_pos = self.input()['ball_start_pos'].load()
        team_in_possession = self.input()['team_in_possession'].load()
        params = self.input()['params'].load()  # Model parameters

        attacking_players = []
        defending_players = []

        # get player  ids
        player_ids = np.unique([c.split('_')[1] for c in tracking_home.keys() if c[:4] == 'Home'])
        for p in player_ids:
            # create a player object for player_id 'p'
            team_player = pl.player(p, tracking_home, 'Home', params)
            if team_player.inframe:
                if team_in_possession == 'Home':
                    attacking_players.append(team_player)
                else:
                    defending_players.append(team_player)

        # get player  ids
        player_ids = np.unique([c.split('_')[1] for c in tracking_away.keys() if c[:4] == 'Away'])
        for p in player_ids:
            # create a player object for player_id 'p'
            team_player = pl.player(p, tracking_away, 'Away', params)
            if team_player.inframe:
                if team_in_possession == 'Away':
                    attacking_players.append(team_player)
                else:
                    defending_players.append(team_player)

        if self.remove_offsides_players:
            offsides_players = []

            # find the second-last defender
            x_defending_players = []
            for player in defending_players:
                x_defending_players.append(player.position[0])

            x_defending_players = np.sort(x_defending_players)
            second_last_defender_x = x_defending_players[-2]

            for player in attacking_players:
                position = player.position
                # if player is nearer to the opponent's goal than the ball
                if position[0] > ball_start_pos[0] and position[0] > second_last_defender_x:
                    offsides_players.append(player)

            for op in offsides_players:
                attacking_players.remove(op)

        self.save({'attacking_players': attacking_players, 'defending_players': defending_players})
Пример #17
0
def players():

    dsn = app.config['dsn']

    app.store = StoreP(dsn)

    app.storeT = StoreTeam(dsn)
    allTeams = app.storeT.getAllTeams(dsn)

    if request.method == 'GET':
        allPlayers = app.store.getAllPlayers(dsn)

    elif 'delete' in request.form:
        ids = request.form.getlist('players')
        for id in ids:
            app.store.deletePlayer(id, dsn)
        allPlayers = app.store.getAllPlayers(dsn)


    elif 'add' in request.form:
        name = request.form['nameToAdd']
        gender = request.form['genderToAdd']
        nation = request.form['nationToAdd']
        birthDate = request.form['birthDateToAdd']
        team = request.form['teamToAdd']
        newPlayer = player(name, gender, nation, birthDate, team)
        app.store.addPlayer(newPlayer, dsn)
        allPlayers = app.store.getAllPlayers(dsn)

    elif 'update' in request.form:
        ids = request.form.getlist('players')
        id = ids[0]
        name = request.form['nameToUpdate']
        gender = request.form['genderToUpdate']
        nation = request.form['nationToUpdate']
        birthDate = request.form['birthDateToUpdate']
        team = request.form['teamToUpdate']
        updatedPlayer = player(name, gender, nation, birthDate, team)
        app.store.updatePlayer(updatedPlayer, id, dsn)
        allPlayers = app.store.getAllPlayers(dsn)

    elif 'find' in request.form:
        name = request.form['nameToFind']
        gender = request.form['genderToFind']
        nation = request.form['nationToFind']
        birthDate = request.form['birthDateToFind']
        team = request.form['teamToFind']
        findPlayer = player(name, gender, nation, birthDate, team)
        allPlayers = app.store.selectPlayers(findPlayer, dsn)


    return render_template('players.html', players = allPlayers, teams = allTeams )
Пример #18
0
	def __init__(self, login, password, action):
		#~ if the game is launched with login/password,
		#~ the player is directly fetched
		if login is not None and password is not None:
			self._player = player(login, password)
		elif action == []:
			#else an empty player is created
			self._player = player(None, None)
			self._doInteractiveAuth()

		self._action = action

		self._player.connect()
Пример #19
0
    def __init__(self):
        self.title = "PyCard - A simple game of 21 ( Blackjack )"
        self.running = True
        self.dealer = player("Dealer Bot#{}".format(randint(0, 100000)))
        self.player = player("Player Bot#{}".format(randint(0, 100000)))
        self.card_deck = deck()

        # Deal out the initial two cards to the dealer and player
        self.dealer.addCard(self.card_deck.deal())
        self.dealer.addCard(self.card_deck.deal())

        self.player.addCard(self.card_deck.deal())
        self.player.addCard(self.card_deck.deal())
Пример #20
0
    def copyState(self):
        newPlayer1 = player(self.players[0].numHands,
                            self.players[0].numFingers)
        newPlayer2 = player(self.players[1].numHands,
                            self.players[1].numFingers)
        newPlayer1.hands = self.players[0].hands[:]
        newPlayer2.hands = self.players[1].hands[:]

        newState = state(newPlayer1, newPlayer2, self.turn, self.parent)
        newState.visits = 0

        newState.uct = newState.calcUct()
        return newState
Пример #21
0
    def __init__(self,name,new):
        """
        Constructor

        Uses algorithm to turn string data from txt file into a player object.
        ...
        
        Parameters
        ----------
        :param name: Name of user
        :type name: str
        :param new: if the game is a new or must be loaded
        :type new: Bool
        """
        if new == True:
            self.user = player(level=1, name = name, EXP=0, gold= 150, items ={})
        else:
            x = name.lower() + ".txt" # create string with name matching one used to create savegames
            with open(x, 'r') as f: # open file in read mode and parse through lines in same order as data was stored
                name = f.readline().rstrip('\n') # strip of \n
                level = int(f.readline()) # turn strings into int
                gold = int(f.readline())
                items_keys = f.readline()
                item_am = f.readline()
                cl_map = f.readline().rstrip('\n')
                cl_row = int(f.readline())
                cl_col = int(f.readline())
                exp = int(f.readline())
                exp_n = int(f.readline())
                st = int(f.readline())
            curr_map = None # emptry var to be assigned current map
            for i in all_maps:
                if i.key == cl_map:
                    curr_map = i

            non_pot_items = []        # items that are not pots
            try:
                bag = self.get_items(items_keys,item_am) # bag containing all items
                for i in bag:
                    if i.key != "hpo" and i.key != "mpo" and i.key != "upo":# if itst not a pot then remove from bag and add via add_item method to ensure stats are updated
                        non_pot_items.append(i)
                for i in non_pot_items:
                    del bag[i]
            except:
                bag = {}
            user1 = player(location(curr_map,cl_row,cl_col),location(curr_map,cl_row,cl_col), level,name,exp,exp_n,gold, bag,st)
            for i in non_pot_items:
                user1.add_item(i)

            self.user = user1
Пример #22
0
 def __init__(self, data={}):
     if len(data) == 0:
         player1 = player('kuba', 'p1', 'nan')
         player2 = player('marks', 'p2', 'nan')
         a = prov_creator('A', 'A', 'p1', 5, 3, 3, ['B'])
         b = prov_creator('B', 'B', 'p2', 5, 3, 3, ['A'])
         ind_prov_creator('X', 'X', 3)
         ind_prov_creator('Y', 'Y', 3)
         ind_prov_creator('Z', 'Z', 3)
         self.nilfgaard = nilfgaard(5, 8)
         for i in pl_list:
             self.pl_sitting_order.append(i)
         random.shuffle(self.pl_sitting_order)
         self.turn_order = self.pl_sitting_order
    def play_video(self):
        # Get current list item details...
        title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
        thumbnail = xbmc.getInfoImage("ListItem.Thumb")
        studio = unicode(xbmc.getInfoLabel("ListItem.Studio"), "utf-8")
        plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
        genre = unicode(xbmc.getInfoLabel("ListItem.Genre"), "utf-8")
        total_time = unicode(xbmc.getInfoLabel("ListItem.EndTime"), "utf-8")
        dbid = unicode(xbmc.getInfoLabel("ListItem.DBID"), "utf-8")

        # Show wait dialog while parsing data...
        dialog_wait = xbmcgui.DialogProgress()
        dialog_wait.create(control.lang(30504), title)

        if self.video_url is None:
            # Close wait dialog...
            dialog_wait.close()
            del dialog_wait

            # Message...
            xbmcgui.Dialog().ok(control.lang(30000), control.lang(30505))
            return

        # Play video...
        # playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        # playlist.clear()

        # list_item = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        # list_item.setInfo("video", {"Title": title, "Studio": studio, "Plot": plot, "Genre": genre})
        # playlist.add(self.video_url, list_item)

        # Close wait dialog...
        dialog_wait.close()
        del dialog_wait

        # Play video...
        # xbmc_player = xbmc.Player()

        player().run({
            "url": self.video_url,
            "thumb": thumbnail,
            "plot": plot,
            "genre": genre,
            "title": title,
            "endTime": total_time,
            "dbid": dbid
        })
        # xbmc_player.play(playlist)
        return
Пример #24
0
def main():
    currentRoom = room.startRoom()

    print "Welcome to Pygame.\n"
    char = player.player()

    #while player is alive
    while char.chp > 0:
        #check to see if a monster is in the room, if so set it to monster
        monster = currentRoom.enter(char)
        #if there is a monster in the room, begin combat
        while currentRoom.monCount > 0 and monster != None:
            combat.combat(char, monster)
            currentRoom.monCount -= 1
            if char.chp < 1:
                char.death()
        #check for chance event
        currentRoom.rollChance(char)
        #display next room options
        currentRoom.nextRooms(currentRoom.exits)
        #(re)initialize results to None
        result = None
        #display game prompt. If the user selects a new room, restart the loop
        while not result:
            result = prompt(char, currentRoom)
            if isinstance(result, room.maps):
                currentRoom = result



    if char.chp < 1:
        char.death()
Пример #25
0
def run_bot(r, comments_replied_to):
    print "Obtaining 25 most recent comments..."
    
    for comment in r.subreddit('mytestzone').comments(limit=25):
        if "!New_Character" == comment.body and comment.id not in comments_replied_to and not comment.author == r.user.me():
            #Check if user already has a character
            username = str(comment.author)
            if search_player_list(username) == True:
                comment.reply("You already have a character. " +
                              "\n\nAre you sure you want to restart?")
            else:
                newplayer=player(username)
                #comment.reply("You've created a new character, " +
                 #             newplayer.username + "!")
                with open ("player_list.txt", "a") as text_file:
                    text_file.write(newplayer.username + "\n")
                print newplayer.username + " created a new character!"
            print "Replied to comment " + comment.id
            comments_replied_to.append(comment.id)
            with open ("comments_replied_to.txt", "a") as f:
                f.write(comment.id + "\n")

    print "Sleeping for 3 seconds"
    #Sleep for 3 seconds
    time.sleep(3)
Пример #26
0
def reset_all():
    global pontuacao_total
    global i

    if i == 3:
        pontuacao_total = []
        i = 1
    else:
        i += 1

    print(i)
    global king
    king = pl.player(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2, 32, 32, win,
                     WINDOW_WIDTH, WINDOW_HEIGHT)
    global zombies
    zombies = []
    global items
    items = []
    global mapa
    mapa = mp.mapa(0, 0, win, 'mapa' + str(i))
    global collected_itens
    collected_itens = {
        'coin': 0,
        'boots': 0,
        'coffee': 0,
        'multi_shot': 0,
        'fast_shot': 0,
        'clock': 0
    }
Пример #27
0
    def multiplayer(self):
        """Setup to represent the game with 2 human players

        variables:
        instances - Player1 and Player2 - Instances of player class who store name, Symbol and are used to determine whos turn it is 

        attributes:
        current_player - Points to the Instance of the player whos turn it is"""
        self.Player1 = player("X")
        self.Player1.turn = True
        self.Player2 = player("O")
        self.current_player = self.Player1
        self.Turn_count = 0
        # Setup Board
        if self.board_init_true == False:
            self.init_Board()
Пример #28
0
def run_game():
    #breakpoint()

    screen = pygame.display.set_mode((1024, 512))
    player_image = pygame.image.load('blue.png').convert()
    background_image = pygame.image.load('back.jpg').convert()
    print(player_image.get_rect().width)
    print(player_image.get_rect().height)
    p = player(player_image, {'width': player_image.get_rect().width, 'height': player_image.get_rect().height}, {'x': 0, 'y': 0})

    while True:

        # handle input
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                sys.exit()
            # elif event.type == pygame.KEYDOWN:
            #     if event.key == pygame.K_RIGHT:
            #         p.change_speed((10,0))
            #     elif event.key == pygame.K_LEFT:
            #         p.change_speed((-10,0))
        
        active_keys = pygame.key.get_pressed()
        if active_keys[pygame.K_RIGHT]:
            p.change_speed((1,0))
        elif active_keys[pygame.K_LEFT]:
            p.change_speed((-1,0))

        p.move((640, 480))
        screen.blit(background_image, (0, 0))
        screen.blit(p.image, p.pos)
        pygame.display.update()
        pygame.time.delay(100)
Пример #29
0
def main():
    currentRoom = room.startRoom()

    print "Welcome to Pygame.\n"
    char = player.player()

    #while player is alive
    while char.chp > 0:
        #check to see if a monster is in the room, if so set it to monster
        monster = currentRoom.enter(char)
        #if there is a monster in the room, begin combat
        while currentRoom.monCount > 0 and monster != None:
            combat.combat(char, monster)
            currentRoom.monCount -= 1
            if char.chp < 1:
                char.death()
        #check for chance event
        currentRoom.rollChance(char)
        #display next room options
        currentRoom.nextRooms(currentRoom.exits)
        #(re)initialize results to None
        result = None
        #display game prompt. If the user selects a new room, restart the loop
        while not result:
            result = prompt(char, currentRoom)
            if isinstance(result, room.maps):
                currentRoom = result

    if char.chp < 1:
        char.death()
Пример #30
0
def main():
    dices = []
    for i in range(6):
        dice1 = dice()
        dices.append(dice1)
    player1 = player('Mona')
    player2 = player('Andreas')
    while player1.score < 10000 and player2.score < 10000:
        turn(player1, dices)
        time.sleep(5)
        turn(player2, dices)
    if player1.score < 10000:
        print('Reaced 10000 or more! Score: ' + str(player1.score))
    elif player2.score < 10000:
        print('Reaced 10000 or more! Score: ' + str(player2.score))
    time.sleep(60)
Пример #31
0
 def setup_player(self):
     try:
         self.my_player = player.player()
         if self.my_player.get_db_status():
             messagebox.showinfo("success!", "connected successfuly to db")
         else:
             raise Exception("sorry u cannot save or load favourites!!!")
     except Exception as ex:
         messagebox.showerror("db error!", ex)
         self.Button9.config(state="disabled")
         self.Button10.config(state="disabled")
         self.Button11.config(state="disabled")
     self.vol_scale.configure(from_=0, to=100, command=self.change_volume)
     self.vol_scale.set(50)
     self.addSongsToPlayListButton.configure(command=self.add_song)
     self.deleteSongsFromPlaylistButton.configure(command=self.remove_song)
     self.playButton.configure(command=self.play_song)
     self.stopButton.configure(command=self.stop_song)
     self.top.title("Mouzikka-Dance to the rhythm of your heart")
     self.top.protocol("WM_DELETE_WINDOW", self.close_window)
     self.isPaused = False
     self.isPlaying = False
     self.pauseButton.configure(command=self.pause_song)
     self.previousButton.configure(command=self.load_previous_song)
     self.Button9.configure(command=self.add_song_to_favourites)
     self.Button10.configure(command=self.remove_song_from_favourites)
     self.Button11.configure(command=self.load_songs_from_favourites)
     self.playList.configure(font="vivaldi 12")
     self.playList.bind("<Double-1>", self.list_double_click)
     img = tk.PhotoImage(file="./icons/broken-heart.png")
     self.top.iconphoto(self.top, img)
     #self.i=0
     self.isThreadRunning = False
Пример #32
0
 async def getPlayer(self, name):
     hdr = {
         'User-Agent':
         'Mozilla/5.0',
         'Accept':
         'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
     }
     async with aiohttp.get(
             "http://www.blissscape.net/highscores/index.php",
             params={"player": name},
             headers=hdr) as r:
         if r.status == 200:
             print(name.strip() + ": " + str(r.status))
             soup = BeautifulSoup(await r.text(), "lxml")
             table = soup.findAll('table')
             if table:
                 rows = table[0].findAll('tr')
                 del rows[0]
                 total = []
                 for i in rows:
                     cells = i.findAll('td')
                     total.append([
                         int(cells[3].getText().replace(',', '')),
                         int(cells[2].getText().replace(',', ''))
                     ])
                 return player(name, total)
             else:
                 return None
Пример #33
0
def main():
    village = card("village", 'a', 3, 2, 0, 1, 0, 0)
    my_dom = dominion([village] * 10)
    copper = card("copper", "t", 0, treasure=1)
    estate = card("estate", "v", 2, victory=1)
    my_player = player([copper] * 7 + [estate] * 3)
    my_dom.turn(None, my_player)
Пример #34
0
  def test_player_attack_pass_roll_prestige(self):
    """
    Tests player attack in a mock mob object
    """

    tp=player.player()
    tp.DEX=5
    tp.STR=1
    tp.totatk=1
    tp.lv=0
    tm=testmob()
    tm.exp=1
    tm.pres=1

    for i in range(1,101):
      tp.attack(tm)
      self.assertEqual(tm.HP, -i)
      self.assertEqual(tm.hit, 1)
      self.assertEqual(tp.prestige, i)
      self.assertEqual(tp.totalhits, i)
      self.assertEqual(tp.totalatks, i)
      self.assertEqual(tp.totaldmg, i)
      self.assertEqual(tp.maxdmg, 1)
      self.assertEqual(tp.kills, i)
      self.assertEqual(tp.exp, i)
Пример #35
0
    def on_reloadbutton_clicked(self,button):

        self.players=[]
        name=self.partychooser.get_active_text()
        if len(name)>0:
            name=name+".par"
            j=0
            with open("userdata/"+name, 'rb') as csvfile:
                reader = csv.reader(csvfile, delimiter=',', quotechar='|')
                for row in reader:
                    self.players.append(player(row))
                    j+=1
            self.globaldata.players=self.players
        name=self.enemychooser.get_active_text()
        if (len(name)>0):
            name=name+".enc"
            j=0
            with open("userdata/"+name, 'rb') as csvfile:
                self.globaldata.selected=[]
                reader = csv.reader(csvfile, delimiter=',', quotechar='|')
                for row in reader:
                    monst=Monster(row[0],row[1],row[2],row[3],row[4],row[5],row[6])
                    self.globaldata.selected.append(monst)

        self.create_rows()
        self.remove_old_info()
        self.get_monster_info()
Пример #36
0
    def __init__(self, mpv_path, streamer_fifo_path, mpv_cmds_fifo_path, server_ip, mpd_port, http_port):

        self.streamer_fifo_path = streamer_fifo_path
        self.mpv_cmds_fifo_path = mpv_cmds_fifo_path

        # the command that Popen will call in a new process (the media player, 
        # controlled by writing commands to mpv_cmds_fifo_path, a handy feature
        # of mpv) 
        self.playercmd = [mpv_path, "--input-file=" + mpv_cmds_fifo_path, streamer_fifo_path]

        # create mpd client, connect it to the server
        self.remote = mpd_client.mpd_client(server_ip, mpd_port, REMOTE_DEBUGLEVEL)
        self.remote.connect_to_server()
        # get the status of the server 
        self.remote.retrieve_status()

        # create player
        self.player = player.player(self.playercmd, mpv_cmds_fifo_path, PLAYER_DEBUGLEVEL)

        # create http client
        self.streamer = http_client.http_client(server_ip, http_port, streamer_fifo_path, STREAMER_BUFFER_SIZE, STREAMER_DEBUGLEVEL)

        # if the mpd server is playing, initialize the http client's connetion 
        state = self.remote.status.state
        if state == "play":
            self.player.play()
            self.streamer.play()
            # check if the streamer successfully connected
            if not self.streamer.connected:
                self.print_debug("Error: could not connect to HTTP server!", 1) 
                self.quit()

        self.message = None
Пример #37
0
def main():
    global dror
    pygame.init()
    dror = player.player(X_screen / 2 - player_width, Y_screen - player_height,
                         player_width, player_height)
    #BACKGROUND = pygame.image.SSload("background.jpg") - load background later
    run = True
    CLOCK = pygame.time.Clock()
    if not stats.game_active:
        play_button.draw_button()
    while game_active:
        CLOCK.tick(60)

        updategame(WIN)
        #movement-------------------------------------------------------
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            dror.x -= dror.velocity
        if keys[pygame.K_RIGHT]:
            dror.x += dror.velocity
        if not (dror.isJump):
            if keys[pygame.K_SPACE]:
                dror.isJump = True
        else:
            if dror.jumpCount >= -10:
                dror.y -= (dror.jumpCount * abs(dror.jumpCount)) * 0.5
                dror.jumpCount -= 1
            else:
                dror.jumpCount = 10
                dror.isJump = False

        #---------------------------------------------------------------
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
Пример #38
0
	def __init__(self): 
		# initial board state stuff 
		self.hints = 8
		self.bombs = 3
		self.played = [0] * len(COLORS)
		self.played_features = np.zeros([NUM_COLORS, NUM_VALUES])

		# set up deck
		self.deck = deck()

		# set up discard pile
		self.discarded = []
		self.discarded_features = np.zeros([NUM_COLORS, NUM_VALUES])

		# set up each of the players' hands
		self.hands = []
		for i in range(NUM_PLAYERS): 
			self.hands.append(self.deck.deal())

		# set up player states
		self.players = []
		for i in range(NUM_PLAYERS): 
			# cards you see in others' hands
			known = self.total_known_cards(self.get_known_in_hand(i), self.played_features, self.discarded_features) 
			# create player with unfucked beliefs 
			self.players.append(player(known, self.get_others_hands(i), self.hints, self.bombs, self.played))

		# weight array used for both players 
		self.weights = np.empty([ACTION_NUM, NUM_COLORS * NUM_VALUES * NUM_HAND * NUM_PLAYERS + 7])
		self.weights.fill(0.1)
Пример #39
0
    def startup(self):
        #method for starting Game state stuff
        print('Starting Up Game State...')

        #set the next state, defaults to the transition state
        self.next = self.previousState.targetState

        #initialize the player
        self.player1 = player.player(self.window.windowSize)
        self.playerProjectiles = []

        #initialize the camera
        #self.camera1 = camera('basicCamera', self.levelWidth, self.levelHeight)

        #initialize enemies
        self.enemies = []
        numberEnemies = 5
        for i in range(0, numberEnemies):
            self.enemies.append(
                enemy.enemy(self.window.windowSize[0],
                            self.window.windowSize[1]))
        pass

        #initialize entities object list
        self.entities = []
Пример #40
0
def newgame(quick=0):
  """
  This function displays the menu to create a new character.

  Receives an optionanl quick parameter. if 1, it generates a 40x40 dungeon and a random player.
  """

  cfg=config.config()

  #If quick is 1, generate everything randomly
  if quick:
    dung=dungeon.dungeon(50,50,1)
    hero=player.player()
    hero.enter(dung)

  #If not, go through the usual process
  elif not quick:
    while 1:
      #purge()
      try:
        common.version()
        print "New game [1/5] Dungeon size\n~40x40 recommended\n"
        xsize=int(raw_input("Horizontal size: "))
        ysize=int(raw_input("Vertical size: "))
        if xsize<40 or ysize<20: print "Minimum size 40x20"
        else:
          print "%ix%i dungeon created"%(xsize,ysize)
          common.getch()
          break
      except ValueError: pass
Пример #41
0
 def __init__(self,playerCount):
     print ("Starting Game...")
     self.deck = deck()
     
     #If the game has a bunch of people, we need more cards, so we creat a double deck
     if playerCount >= 4:
         deck2 = deck()
         self.deck.cards.extend(deck2.cards)
     
     #Once we have all the cards, we shuffle them
     self.deck.shuffle()
     print ("Starting Deck Length: "+str(self.getDeckLength()))
     
     #Time to create players
     self.players = []
     for x in range(0,playerCount):
         print ("Loading Player "+str(x)+"...")
         #Draw 5 cards for each player and insert them into our player list
         newPlayerHand = self.deck.drawCard(13)
         newPlayer = player(self,x,newPlayerHand)
         self.players.append(newPlayer)
     
     #We pick a starting card with onlyNumerical = true so we dont start with an action card
     self.currentCard = self.deck.drawCard(1,True)
     
     
     #index of current player (players list)
     self.currentPlayer = 0;
     
     #which direction the flow is going
     self.rotationManager = 1
Пример #42
0
def run():
    import player as _player_
    player = _player_.player()
    p = player_client(player)
    data = {}
    data["quit"] = 0
    while not data["quit"]:
        data = p.chat()
Пример #43
0
def testcharsh():
  """
  Test environment for the character sheet.
  """

  dung=dungeon.dungeon(0,0,0)
  test=player.player(dung,1)
  test.charsheet()
Пример #44
0
 def initBattle(self,roles):
     self.players = []
     self.warriors = []
     
     for r in roles:
         p = player(r,self)
         self.players.append(p)
         self.init_role(p)
Пример #45
0
def main():
	conn = xmmsclient.glib.GLibConnector(xmms)
	app = player(xmms)
	app.window.show()
	gtk.gdk.threads_init()
	gtk.gdk.threads_enter()
	gtk.main()
	gtk.gdk.threads_leave()	
Пример #46
0
  def test_pick_consumable_pass(self):
    """
    Tests if the player can pick a consumable
    """

    tp=player.player()
    ti=testhppotion
    ans=tp.pickconsumable(ti)
    self.assertEqual(ans, (1, "You picked hp."))
Пример #47
0
def testvend():
  """
  Test environment for vendors and sellers
  """

  dung=dungeon.dungeon(0,0,0)
  hero=player.player(dung,1)
  seller=npc.vendor()
  seller.commerce(hero)
Пример #48
0
def startGame():
    #Setup Objects
    try:
        level.levelSpawner = level.levelSpawner()
        level.background = level.background()
    except: pass
    objects.player = player.player(PLAYERSTART[0],PLAYERSTART[1])
    objects.energyBar = misc.energyBar()
    objects.healthBar = misc.healthBar()
Пример #49
0
 def __init__(self):
     """Main running function"""
     self.windowx = 680
     self.windowy = 800
     pygame.init()
     self.clock = pygame.time.Clock()
     self.set_up_screen()
     self.time_since_last_frame = 0.0
     self.enemy_text = open("enemies.txt").readlines()
     self.enemy_data = self.interp_enemies(self.enemy_text)
     self.text_text = open("text_disp.txt").readlines()
     self.text_data = self.interp_text(self.text_text)
     self.text_list = []
     self.debris_list = []
     self.rock_list = []
     self.sbear_list = []
     self.wbear_list = []
     self.particle_list = []
     self.boss = None
     self.boss_killed = False
     self.boss_spawned = False
     self.lady_spawned = False
     self.lady_koi = None
     self.lives = 6
     self.last_death = -2000
     self.immortal_time = 2000
     self.player = player(self.windowx, self)
     self.distance = 0
     self.worldspeed = 1 #distance per ms for river image movement
     self.riverimg = pygame.image.load("img/river1.png").convert()
     #self.landimgl = pygame.image.load("img/landproxy.png").convert()
     #self.landimgr = pygame.image.load("img/landproxy.png").convert()
     #self.landimgr = pygame.transform.rotate(self.landimgl, 180)
     self.landimgl = pygame.image.load("img/good_grass_left.png").convert_alpha()
     self.landimgr = pygame.image.load("img/good_grass_right.png").convert_alpha()
     self.sidebarimg = pygame.image.load("img/sidebar.png").convert()
     self.heartimg = pygame.image.load("img/heart.png").convert_alpha()
     self.key_bindings = key_bindings()
     self.screen_rect = pygame.Rect(0,0,self.windowx,self.windowy)
     self.player_killed = False
     self.killedforealz = False
     self.deaddraw = True
     self.deaddrawnum = 0 #a counter to make the player flicker when respawning
     #self.font32 = pygame.font.Font(None, 32) #Temp Font
     self.font32 = pygame.font.Font("fonts/SVBasicManual.ttf", 20)
     self.aqua32 = pygame.font.Font("fonts/Aquanaut.ttf", 40)
     #final boss stuff
     #self.bad_koi = evil_koi(self.windowx)
     self.bad_projectiles = []
     self.music = game_music()
     self.distance_bar = generic_bar(0, 200000, (0,0,0), (0,0,0), (255,255,255), 620, 100, 20, 300)
     self.energy_bar = generic_bar(0, 300, (255,0,0), (255,255,0), (255,255,255), 645, 100, 20, 300)
     self.dont_exit = True
     self.lady_time = 0
     self.fire_particle_image = pygame.image.load("img/fire_particle.png").convert_alpha()
     self.water_particle_image = pygame.image.load("img/water_particle.png").convert_alpha()
     self.rock_particle_image = pygame.image.load("img/rock_particle.png").convert_alpha()
Пример #50
0
  def test_pick_consumable_fail(self):
    """
    Tests if the consumable picking fails when inv is epmty
    """

    tp=player.player()
    tp.belt=[testhppotion for i in range(4)]
    ti=testhppotion
    ans=tp.pickconsumable(ti)
    self.assertEqual(ans, (0, "Your belt is full"))
Пример #51
0
  def test_player_fall_enter(self):
    """
    Tests if a player can correctly enter a dungeon falling
    """

    td=testdungeon
    tp=player.player()
    tp.enter(td, 1)
    self.assertEqual(tp.xpos, 1)
    self.assertEqual(tp.ypos, 2)
Пример #52
0
  def test_player_spec_enter(self):
    """
    Tests if a player can correctly enter a dungeon specifying normally
    """

    td=testdungeon
    tp=player.player()
    tp.enter(td, 0)
    self.assertEqual(tp.xpos, 1)
    self.assertEqual(tp.ypos, 1)
Пример #53
0
  def test_pick_itemp_pass(self):
    """
    Tests if the player can successfully pick an item
    """

    tp=player.player()
    ti=testitem
    ans=tp.pickobject(ti)
    self.assertEqual(ans, (0, "You picked test_item\n"))
    self.assertEqual(tp.itemspck, 1)
Пример #54
0
def run_curses():
    import curses_ as curses
    import player as _player_
    player = _player_.player()
    player = curses.player_curses()
    p = player_client(player)
    data = {}
    data["quit"] = 0
    while not data["quit"]:
        data = p.chat()
    def play_video(self):
        # Get current list item details...
        title = unicode(xbmc.getInfoLabel("ListItem.Title"), "utf-8")
        thumbnail = xbmc.getInfoImage("ListItem.Thumb")
        studio = unicode(xbmc.getInfoLabel("ListItem.Studio"), "utf-8")
        plot = unicode(xbmc.getInfoLabel("ListItem.Plot"), "utf-8")
        genre = unicode(xbmc.getInfoLabel("ListItem.Genre"), "utf-8")
        total_time = unicode(xbmc.getInfoLabel("ListItem.EndTime"), "utf-8")
        dbid = unicode(xbmc.getInfoLabel("ListItem.DBID"), "utf-8")

        # Show wait dialog while parsing data...
        dialog_wait = xbmcgui.DialogProgress()
        dialog_wait.create(control.lang(30504), title)

        if self.video_url is None:
            # Close wait dialog...
            dialog_wait.close()
            del dialog_wait

            # Message...
            xbmcgui.Dialog().ok(control.lang(30000), control.lang(30505))
            return

        # Play video...
        # playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        # playlist.clear()

        # list_item = xbmcgui.ListItem(title, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        # list_item.setInfo("video", {"Title": title, "Studio": studio, "Plot": plot, "Genre": genre})
        # playlist.add(self.video_url, list_item)

        # Close wait dialog...
        dialog_wait.close()
        del dialog_wait

        # Play video...
        # xbmc_player = xbmc.Player()

        player().run({"url": self.video_url, "thumb": thumbnail, "plot": plot, "genre": genre, "title": title,
                    "endTime": total_time, "dbid": dbid})
        # xbmc_player.play(playlist)
        return
Пример #56
0
  def test_levelup_multiple(self):
    """
    Same as test_levelup_once, except it sets the exp to 67
    With that exp the player should get to level 6 with a single call
    """

    tp=player.player()
    tp.exp=67
    self.assertEqual(tp.lv, 1)
    tp.levelup()
    self.assertEqual(tp.lv, 6)
Пример #57
0
def testchat():
  """
  Test environment for seller chat

  Starts a chat with a random vendor, giving extra information for testing purposes.
  """

  dung=dungeon.dungeon(0,0,0)
  hero=player.player(dung,1)
  seller=npc.vendor()
  parser.chat(seller.keeper,hero)
Пример #58
0
  def test_levelup_none(self):
    """
    Same as the other test_levelup functions, except it sets the exp to 4
    At level 1 with less than 5 exp, the player should not level up at all
    """

    tp=player.player()
    tp.exp=4
    self.assertEqual(tp.lv, 1)
    tp.levelup()
    self.assertEqual(tp.lv, 1)
Пример #59
0
 def __init__(self):
     """initializes the game"""
     pygame.init()
     self.screen = pygame.display.set_mode((680, 800))
     self.clock = pygame.time.Clock()
     self.player = player(680)
     self.FrameRate = 1
     self.SCREENRECT = pygame.Rect(0, 0, 680, 800)
     self.debris = False
     self.evil_koi = evil_koi(680)
     self.debris_list = []
Пример #60
0
  def test_levelup_once(self):
    """
    Tests player increasing levels
    Set the experience to 5 
    Expects the player to level up just once
    """

    tp=player.player()
    tp.exp=5
    self.assertEqual(tp.lv, 1)
    tp.levelup()
    self.assertEqual(tp.lv, 2)