Exemple #1
0
def scrapeNumFD():
    """
    Retrieves player projection data from NumberFire for FanDuel contests. 
    Returns 2-D array contains player objects with relevant attributes filled.
    """
    
    url = 'https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    prices = soup.findAll('td', attrs={'class':'cost'})
    names = soup.findAll('a', attrs={'class':'full'})
    teams = soup.findAll('span', attrs={'class':'team-player__team active'})
    proj = soup.findAll('td', attrs={'class':'fp active'})
    positions = soup.findAll('span', attrs={'class':'player-info--position'})
    # gtd = soup.findAll('span', attrs={'class':'team-player__injury player-gtd'})
    data = [[],[],[],[],[]]

    for i in range(0,len(prices)):
        price = int(int(re.sub('[^0-9]','', prices[i].text))/100)
        value = float(proj[i].text.strip())

        if("PG" in positions[i].text):
            data[0].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))
        elif("SG" in positions[i].text):
            data[1].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))
        elif("SF" in positions[i].text):
            data[2].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))
        elif("PF" in positions[i].text):
            data[3].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))
        elif("C" in positions[i].text):
            data[4].append(player(value,price,i,names[i].text.strip(),teams[i].text.strip()))

    return data
Exemple #2
0
def scrapeGrindFD():
    """
    Retrieves player projection data from RotoGrinders for FanDuel contests. 
    Returns 2-D array contains player objects with relevant attributes filled.
    """
    #auto change by day
    url = 'https://rotogrinders.com/lineups/nba?date=' + CUR_DATE + '&site=fanduel'
    teamDict = scrapeTeams()
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    pts = soup.find_all('span',attrs={'class':'fpts'})
    names = soup.find_all('a',attrs={'class':'player-popup'})
    salary = soup.find_all('span',attrs={'class':'salary'})
    positions = soup.find_all('span',attrs={'class':'position'})

    data = [[],[],[],[],[]]

    for i in range(0,len(salary)):
        price = int(float(salary[i].text.replace('$','').replace('K',''))*10)
        value = float(pts[i].text.strip())
        team = 'placeholder' #teamDict[names[i].text.strip()]
        if("PG" in positions[i].text):
            data[0].append(player(value,price,i,names[i].text.strip(),team))
        elif("SG" in positions[i].text):
            data[1].append(player(value,price,i,names[i].text.strip(),team))
        elif("SF" in positions[i].text):
            data[2].append(player(value,price,i,names[i].text.strip(),team))
        elif("PF" in positions[i].text):
            data[3].append(player(value,price,i,names[i].text.strip(),team))
        elif("C" in positions[i].text):
            data[4].append(player(value,price,i,names[i].text.strip(),team))

    return data
Exemple #3
0
def main():
    list_Deck = deck()
    list_Comps_Name = ["Noob1", "Noob2", "Noob3", "Noob4"]
    list_Players = []

    # START GAME
    game_Flag = True
    game_input = input(
        "Valdaz Digital Bomb | Press Enter to Cont... / Q to Quit! ")

    if game_input.lower() == 'q':
        game_Flag = False

    name = input("Enter Player Name: ")
    noob = player(name)

    while game_Flag:
        numPlayers = int(input("Number of Players: "))

        print("Lets Play!!!")

        list_Deck.shuffle()

        print("Shuffling. . .")
        time.sleep(2)

        for i in range(numPlayers):
            temp = player(list_Comps_Name[i])
            list_Comps.append(temp)

        for temp in list_Comps:
            print(temp.hand)

        game_Flag = False
Exemple #4
0
def optimize(players, budget):
    """
    Generates the optimal lineup for DraftKings based on player projections.

    Inputs:
        players: 2-D array containing player objects for each player by position
        num_players: total number of players
        budget: amount of money to spend on players
    """
    
    num_pos = len(players)
    
    V = np.zeros((num_pos, budget+1))   # array to track max vorp
    Who = np.zeros((num_pos, budget+1), dtype=object) # array to recreate hires

    for x in range(budget+1):
        V[num_pos-1][x] = 0
        Who[num_pos-1][x] = player()
        
        for p in players[num_pos-1]:
            # retrieve relevant players
            if p.cost <= x and p.value > V[num_pos-1][x]:
                V[num_pos-1][x] = p.value
                Who[num_pos-1][x] = p
    
    for pos in range(num_pos-2,-1,-1):
        for x in range(budget+1):
            null_player = player()
            # V[pos][x] = V[pos+1][x]     # not taking a player. we will try initializing to -inf
            V[pos][x] = 0
            Who[pos][x] = null_player

    # If it traces back the current lineup correctly the first time it should do it after that

            for p in players[pos]:
                currentTeams = {}
                currentLineup = []
                amount = x - p.cost
                for i in range(pos+1,num_pos):
                    k = Who[i][amount]
                    if type(k) != int:
                        if k.id != None:
                            if k.team in currentTeams:
                                currentTeams[k.team] += 1
                            else:
                                currentTeams[k.team] = 1
                            currentLineup.append(k.name)
                            amount = amount - k.cost
                
                if p.cost <= x and (V[pos+1][x-p.cost] + p.value >= V[pos][x]) and (p.name not in currentLineup):  # and currentTeams[p.team] < 4
                    if pos != 0:
                        if x - p.cost < 10:
                            continue
                    V[pos][x] = V[pos+1][x-p.cost] + p.value
                    Who[pos][x] = p

    return Who
Exemple #5
0
 def __init__(self):
     pygame.init()
     pygame.font.init()
     self.settings = settings()
     self.player = player()
     self.draw = draw()
     self.keys = keys()
     self.screen = pygame.display.set_mode(
         (self.settings.WIDTH, self.settings.HEIGHT))
     pygame.display.set_caption(self.settings.CAPTION)
     self.clock = pygame.time.Clock()
     self.time_font = pygame.font.Font('freesansbold.ttf', 60)
     self.text_font = pygame.font.Font('freesansbold.ttf', 20)
     self.end_font = pygame.font.Font('freesansbold.ttf', 30)
     self.start_font = pygame.font.Font('freesansbold.ttf', 100)
     with open("texts/text.txt") as f:
         contents = f.readlines()
     for n, line in enumerate(contents):
         if line.startswith("line"):
             contents[n] = "\n" + line.rstrip()
         else:
             contents[n] = line.rstrip()
     self.contents = ' '.join(contents)
     self.text_width, self.text_height = self.time_font.size(self.contents)
     self.lines = int(math.ceil(self.text_width / self.settings.WIDTH / 2))
     self.groups = int(len(self.contents) / self.lines)
     self.line_contents = textwrap.wrap(self.contents, self.groups)
     for n, line in enumerate(self.line_contents):
         if n < len(self.line_contents):
             self.line_contents[n] = self.line_contents[n] + " "
Exemple #6
0
 def __init__(self,name):
     '''
     Constructor for a game of rock paper scissors
     Initializes Player and computer to None
     Initializes rounds to 0
     @param name: The user-given name for the Player
     '''
     self.player = player(name)
     self.computer = computer()
     self.rounds = 0
Exemple #7
0
def scrapeBaseFD():
    """
    Retrieves player projection data from NumberFire for FanDuel contests. 
    Returns 2-D array contains player objects with relevant attributes filled.
    """
    urlp = 'https://www.numberfire.com/mlb/daily-fantasy/daily-baseball-projections/pitchers'
    urlh = 'https://www.numberfire.com/mlb/daily-fantasy/daily-baseball-projections/batters'
    response = requests.get(urlh)
    soup = BeautifulSoup(response.text, "html.parser")
    prices = soup.findAll('td', attrs={'class':'cost'})
    names = soup.findAll('a', attrs={'class':'full'})
    proj = soup.findAll('td', attrs={'class':'fp active'})
    positions = soup.findAll('span', attrs={'class':'player-info--position'})
    # gtd = soup.findAll('span', attrs={'class':'team-player__injury player-gtd'})


    data = [[],[],[],[],[],[],[],[],[]]

    for i in range(0,len(prices)):
        price = int(int(re.sub('[^0-9]','', prices[i].text))/100)
        value = float(proj[i].text.strip())
        # print(names[i])

        if("C" in positions[i].text or "1B" in positions[i].text):
            data[0].append(player(value,price,i,names[i].text.strip()))
        elif("2B" in positions[i].text):
            data[1].append(player(value,price,i,names[i].text.strip()))
        elif("3B" in positions[i].text):
            data[2].append(player(value,price,i,names[i].text.strip()))
        elif("SS" in positions[i].text):
            data[3].append(player(value,price,i,names[i].text.strip()))
        elif("OF" in positions[i].text):
            data[4].append(player(value,price,i,names[i].text.strip()))
        data[5].append(player(value,price,i,names[i].text.strip()))

    # Pitchers
    response = requests.get(urlp)
    soup = BeautifulSoup(response.text, "html.parser")
    prices = soup.findAll('td', attrs={'class':'cost'})
    names = soup.findAll('a', attrs={'class':'full'})
    proj = soup.findAll('td', attrs={'class':'fp active'})
    positions = soup.findAll('span', attrs={'class':'player-info--position'})

    for i in range(0,len(prices)):
        price = int(int(re.sub('[^0-9]','', prices[i].text))/100)
        value = float(proj[i].text.strip())

        data[6].append(player(value,price,i,names[i].text.strip()))

    data2 = [data[0],data[1],data[2],data[3],data[4],data[4],data[4],data[5],data[6]]
    return data2
Exemple #8
0
    def __init__(self):

        pygame.init()
        self.window = pygame.display.set_mode((50 * 3, 300))

        self.czcionka = pygame.font.SysFont("comicsans", 20)
        self.player = player("./res/man.png")
        self.fishes.append(Fish("./res/blackfish.png"))
        self.fishes.append(Fish("./res/blackfish.png"))
        self.fishes.append(Fish("./res/blackfish.png"))

        self.fishes[0].rect.y = -350
        self.fishes[1].rect.y = -440
        self.fishes[2].rect.y = -525

        while True:
            self.window.fill(self.color)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit(0)
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    sys.exit(0)

            if (pygame.key.get_pressed()[pygame.K_SPACE]):
                a = Game()

            if (self.catched == True):
                self.text = "score" + str(self.score)
            self.text_render = self.czcionka.render(self.text, 1,
                                                    (250, 250, 250))
            self.window.blit(self.text_render, (10, self.texty))

            self.window.blit(player.getImage(self.player),
                             (self.player.rect.x, self.player.rect.y))
            self.window.blit(Fish.getImage(self.fishes[0]),
                             (self.fishes[0].rect.x, self.fishes[0].rect.y))
            self.window.blit(Fish.getImage(self.fishes[1]),
                             (self.fishes[1].rect.x, self.fishes[1].rect.y))
            self.window.blit(Fish.getImage(self.fishes[2]),
                             (self.fishes[2].rect.x, self.fishes[2].rect.y))

            self.Ticking()
            pygame.display.flip()
def startGame():
    '''starts a new round'''
    #global maincam
    #global p1
    #global mode
    #global score
    #global scoredrop
    #global scoredropper
    #global enemies
    #global stars
    #global projectiles
    #global items
    #global particles
    #global enemyspawndelay
    #global cowspawndelay

    GlobalVariables.enemies = list()
    GlobalVariables.stars = list()
    GlobalVariables.projectiles = list()
    GlobalVariables.items = list()
    GlobalVariables.particles = list()

    gotoMode(1)
    GlobalVariables.score = 0
    GlobalVariables.scoredrop = 500
    GlobalVariables.enemyspawndelay = 0
    GlobalVariables.cowspawndelay = 0
    GlobalVariables.scoredropper = None
    GlobalVariables.maincam = camera()
    GlobalVariables.p1 = player()

    # testpow = item((0, 40), 2)
    # items.append(testpow)
    # testbas = basher((100,100))
    # enemies.append(testbas)
    # testmtc = motherCow((100,100))
    # enemies.append(testmtc)

    # fills in the stars
    for i in range(200):
        GlobalVariables.stars.append(randPoint(500))
Exemple #10
0
 def addPlayer(self):
     charRand = randint(0, 5)
     while charRand in self.usedCharacters:
         charRand = randint(0, 5)
     name = self.characterList[charRand]
     Player = player(character=name,
                     platforms=self.platformList,
                     elevator=self.elevatorList,
                     weakLayer=self.weakLayerGroup,
                     bulletList=self.bulletList,
                     sticks=self.stickList,
                     giantSpike=self.giantSpikeList)
     initialLocations = [(968, 400), (280, 400), (968, 250), (280, 250)]
     initialLocation = initialLocations[randint(0, 3)]
     Player.rect.x, Player.rect.y = initialLocation
     Player.weapon.rect.x, Player.weapon.rect.y = initialLocation
     if self.playerList is None:
         self.playerList = pygame.sprite.Group()
     self.playerList.add(Player)
     self.playerList.add(Player.weapon)
     return Player
Exemple #11
0
import pygame
from Player import player
from Terrain import terrain
from MainMenu import menu
from Leaderboard import leaderboard_read, leaderboard_write
from LoadImage import load_image
from Motion import motion
from Collision import collision
import time

# initialize game and call classes
pygame.init()
player_1 = player()
player_2 = player()
terrain = terrain()
menu = menu()
player_2.x = int(terrain.screen_size[0] * 0.8)
player_2.direction = 'Left'
# Name of game
pygame.display.set_caption('First Game')
'''
Game start menu
'''
run_game = False
while menu.run:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            menu.run = False
        # load_image(filename, pos_x, pos_y, width, height)
        load_image('menu\selection_screen.jpg', 0, 0, terrain.screen_size[0],
Exemple #12
0
def game():
    print("Le jeux va commencer!!")
    sleep(2)
    print("Personnage disponible : ")
    print("[ 1 ] L'ancien")
    print(
        "Faiblesse : Cette vielle personnes détestent quand on insulte sa famille et son physique de vieux."
    )
    sleep(2)
    print("[ 2 ] Le jeune")
    print(
        "Ce jeune ado prépubère déteste quand on insulte sa manière de s'habiller et son physique d'enfant."
    )
    sleep(2)
    print("[ 3 ] Le noble")
    print(
        "Ce personnage issue de la haute noblesse n'aime pas quand on se moque de sa hierarchie et qu'on l'insulte."
    )
    sleep(2)
    print("[ 4 ] L'intello")
    print("Cet homme aillant un QI plus élevé n'aime pas qu'on "
          "insulte sa famille et d'être comparé a certaine personnes.")
    sleep(2)
    print()

    choice = int(input("Joueur 1 choississez votre personnage : "))
    while choice < 1 or choice > 4:
        choice = int(input("Joueur 1 choississez votre personnage : "))
    player1 = player(choice)
    choice = int(input("Joueur 2 choississez votre personnage : "))
    while choice < 1 or choice > 4:
        choice = int(input("Joueur 2 choississez votre personnage : "))
    player2 = player(choice)
    print("Le jeux se lance!")
    sleep(2)

    while not (player1.vie <= 0 or player2.vie <= 0):
        while len(board.boardList) > 2:
            print("player1 :", player1.phrase)
            player1.chooseWord(board)
            print("player2 :", player2.phrase)
            player2.chooseWord(board)

        print("La phrase de player1 est : \"", player1.phrase, "\"")
        print("La phrase de player2 est : \"", player2.phrase, "\"")

        print("------------------")

        player1.vie -= player2.attackPhase()
        player2.vie -= player1.attackPhase()
        player1.bonusAtt = 0
        player2.bonusAtt = 0

        print("player1 :", player1.vie, "PV")
        print("player2 :", player2.vie, "PV")

        sleep(3)
        board.newBoard()
        player1.phrase = ""
        player2.phrase = ""

    if player1.vie <= 0:
        print("Vainqueur de la rencontre : Joueur 2 !")
    elif player2.vie <= 0:
        print("Vainqueur de la rencontre : Joueur 1 !")
    else:
        print("Egalité... Dommage !")
Exemple #13
0
#Importar Menus
from Menus import *

# Se inician modulos
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'

# Se inicia la pantalla
surface = pygame.display.set_mode((winWidth, winHeight))
pygame.display.set_caption('PP-Block')

# Se crea el reloj
clock = pygame.time.Clock()

########PRUEBA
player1 = player(surface, pong, flecha, avatarCisneros)
Mat = MatCas(surface, player1)
Mat.nextLevel()
pausa = Button(winWidth - 30, marUp / 2, pausaTex, surface)

#Contadores
a = 0
b = 0
c = 0

#estado click izquierdo Mouse
estdMouse = mouse.get_pressed()[0]

Menu(surface, clock, player1, Mat)

# Entra en bucle principal
Exemple #14
0
def game():
    global timer
    win = pygame.display.set_mode((1900, 1000))

    pygame.display.set_caption("First Game")
    # char = pygame.image.load('standing.png')

    clock = pygame.time.Clock()
    bg = pygame.image.load('Recursos/Backgroung/bg.png')
    board = pygame.image.load('Recursos/Board.png')
    label1 = pygame.font.SysFont('arial',28).render("Player1:", 1,(0,255,0))
    label2 = pygame.font.SysFont('arial',28).render("Player2:", 1,(0,255,0))
    label3 = pygame.font.SysFont('arial',28).render("Vidas:", 1,(0,255,0))
    label4 = pygame.font.SysFont('arial',28).render("Vidas:", 1,(0,255,0))
    label8 = pygame.font.SysFont('arial',28).render("Time: ",1,(0,255,0))
    labelwin = pygame.font.SysFont('arial',100).render("PLAYER 1 is the WINNER!",1,(0,0,0))
    labelwin1 = pygame.font.SysFont('arial',100).render("PLAYER 2 is the WINNER!",1,(0,0,0))


    counter = 120

    #Inicializar control
    joysticks = []
    for i in range(pygame.joystick.get_count()):
        joysticks.append(pygame.joystick.Joystick(i))
    for joystick in joysticks:
        joystick.init()
    with open(os.path.join("ps4_keys.json"),'r+') as file:
        button_keys = json.load(file)

    #analog keys
    analog_keys = {0:0, 1:0, 2:0, 3:0, 4:-1, 5: -1}

    # bulletSound = pygame.mixer.Sound('bullet.wav')
    # hitSound = pygame.mixer.Sound('hit.wav')

    # music = pygame.mixer.music.load('music.mp3')
    # pygame.mixer.music.play(-1)

    P1 = Spritesheet("platform")
    Platform1 = P1.get_spritte()

    P2 = Spritesheet("platform1")
    Platform2 = P2.get_spritte()

    TARGET_FPS = 60
    def redrawGameWindow():
        win.blit(bg, (0, 0))
        win.blit(board, (1500, 0))
        win.blit(label1,(1530,140))
        win.blit(label2,(1530,550))
        win.blit(label3,(1530,180))
        win.blit(label4,(1530,630))
        win.blit(label5,(1630,180))
        win.blit(label6,(1630,630))

        win.blit(label8,(1530,40))
        win.blit(label7,(1600,40))



        if player1.vidas == 0:
            win.blit(labelwin1, (300, 500))
        elif player2.vidas == 0:
            win.blit(labelwin, (300, 500))
        else:
            piso.draw(win)
            plataform1.draw(win)
            platform2.draw(win)
            pow1.draw(win)
            pow2.draw(win)
            pow3.draw(win)
            player2.draw(win)
            player1.draw(win)
            AVL.draw(win)

        pygame.display.update()


    # mainloop
    font = pygame.font.SysFont('comicsans', 30, True)
    player1 = player()
    player1.position.x = 500
    player1.position.y = 700
    player1.rect.y = player1.position.y
    player2 = player()
    player2.position.x = 600
    player2.position.y = 700


    pow1 = powers(random.choice(["shield"]), random.randint(100, 1500), 40)
    pow2 = powers(random.choice(["jump"]), random.randint(100, 1500), 40)
    pow3 = powers(random.choice(["punch"]), random.randint(100, 1500), 40)

    AVL = tree("AVL",random.randint(100,1500),40)


    piso = platform(Platform1[0],250,860)
    plataform1 = platform(Platform2[0],1200,650)
    platform2 = platform(Platform2[1],100,650)

    run = True
    while run:
        dt = clock.tick(60) * .001 * TARGET_FPS

        for event in pygame.event.get():
            if event.type == pygame.USEREVENT:
                counter  -= 1
                timer = str(counter).rjust(3) if counter > 0 else quit()
            else:
                clock.tick(60)
            if event.type == pygame.QUIT:
                run = False
            label5 = pygame.font.SysFont('arial', 28).render(str(player1.vidas), 1, (0, 255, 0))
            label6 = pygame.font.SysFont('arial', 28).render(str(player2.vidas), 1, (0, 255, 0))
            label7 = pygame.font.SysFont('arial', 28).render(str(timer), 1, (0, 255, 0))
            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == button_keys['left_arrow']:
                    player1.LEFT_KEY = True
                    player1.left = True
                    player1.right = False
                    player1.standing = False
                    player1.punch = False
                if event.button == button_keys['right_arrow']:
                    player1.RIGHT_KEY = True
                    player1.left = False
                    player1.right = True
                    player1.standing = False
                    player1.punch = False
                if event.button == button_keys['up_arrow']:
                    player1.jump()
                if event.button ==  button_keys['square']:
                    if player1.pow:
                        if player1.powpunch:
                            player1.punchCount = 0
                            player1.punch = True
                            player1.standing = False
                            player1.pow = False
                        elif player1.jumpow:
                            player1.usejump = True
                            player1.jump()
                            player1.pow = False
                        elif player1.shield:
                            player1.useshield = True
                            player1.pow = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:#or event.button == button_keys['x']
                    player1.LEFT_KEY = True
                    player1.left = True
                    player1.right = False
                    player1.standing = False
                    player1.punch = False
                elif event.key == pygame.K_d:
                    player1.RIGHT_KEY = True
                    player1.left = False
                    player1.right = True
                    player1.standing = False
                    player1.punch = False
                elif event.key == pygame.K_w:
                    player1.jump()
                elif event.key == pygame.K_j:
                    player2.LEFT_KEY = True
                    player2.left = True
                    player2.right = False
                    player2.standing = False
                    player2.punch = False
                elif event.key == pygame.K_l:
                    player2.RIGHT_KEY = True
                    player2.left = False
                    player2.right = True
                    player2.standing = False
                    player2.punch = False
                elif event.key == pygame.K_i:
                    player2.jump()
                elif event.key == pygame.K_s:
                    if player1.pow:
                        if player1.powpunch:
                            player1.punchCount = 0
                            player1.punch = True
                            player1.standing = False
                            player1.pow = False
                        elif player1.jumpow:
                            player1.usejump = True
                            player1.jump()
                            player1.pow = False
                        elif player1.shield:
                            player1.useshield = True
                            player1.pow = False
                elif event.key == pygame.K_k:
                    if player2.pow:
                        if player2.powpunch:
                            player2.punchCount = 0
                            player2.punch = True
                            player2.standing = False
                            player2.pow = False
                        elif player2.jumpow:
                            player2.usejump = True
                            player2.jump()
                            player2.pow = False
                        elif player2.shield:
                            player2.useshield = True
                            player2.pow = False
            ############################################
            if event.type == pygame.JOYBUTTONUP:
                if event.button == button_keys['left_arrow']:
                    player1.LEFT_KEY = False
                    player1.right = False
                    player1.standing = True
                if event.button == button_keys['right_arrow']:
                    player1.RIGHT_KEY = False
                    player1.LEFT_KEY = False
                    player1.left = False
                    player1.standing = True
                if event.button == button_keys['up_arrow']:
                    if player1.isJump:
                        player1.vel.y *= .25
                        player1.isJump = False
                if event.button ==  button_keys['square']:
                    if player1.catch != None:
                        player1.catch.drop = False
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    player1.LEFT_KEY = False
                    player1.right = False
                    player1.standing = True
                elif event.key == pygame.K_d:
                    player1.RIGHT_KEY = False
                    player1.LEFT_KEY = False
                    player1.left = False
                    player1.standing = True
                elif event.key == pygame.K_w:
                    if player1.isJump:
                        player1.vel.y *= .25
                        player1.isJump = False
                if event.key == pygame.K_j:
                    player2.LEFT_KEY = False
                    player2.right = False
                    player2.standing = True
                elif event.key == pygame.K_l:
                    player2.RIGHT_KEY = False
                    player2.left = False
                    player2.standing = True
                elif event.key == pygame.K_i:
                    if player2.isJump:
                        player2.vel.y *= .25
                        player2.isJump = False
                elif event.key == pygame.K_s:
                    if player1.catch != None:
                        player1.catch.drop = False
                elif event.key == pygame.K_k:
                    if player2.catch !=None:
                        player2.catch.drop = False
        AVL.update(dt,[piso,platform2,plataform1])
        pow1.update(dt,[piso,platform2,plataform1])
        pow2.update(dt, [piso, platform2, plataform1])
        pow3.update(dt, [piso, platform2, plataform1])
        player2.update(dt,[player1],[piso,platform2,plataform1],[pow1,pow2,pow3],[[AVL],"AVL"])
        player1.update(dt,[player2],[piso,platform2,plataform1],[pow1,pow2,pow3],[[AVL],"AVL"])
        redrawGameWindow()
Exemple #15
0
	def main(stdscr):
		setCurses(stdscr)
		h, w = stdscr.getmaxyx()
		p1 = player('raf', 10)
		b = board(1)

		if len(sys.argv) > 1:
			seed = int(sys.argv[1])
		else: seed = ''

		random.seed()
		roomSizeIdx = random.randrange(0, len(roomSizes))

		random.seed()
		numRooms = random.randrange(1, 6)
		for i in range(0,  numRooms):
			random.seed()
			roomSizeIdx = random.randrange(0, len(roomSizes))

			originX = random.randrange(0, w - 20)
			originY = random.randrange(0, h - 15)
			origin = (originX, originY)
			b.addRoom(room(roomSizes[roomSizeIdx], stdscr, origin))

		running = True
		while running:

			stdscr.addstr(h-1, int(w/2), '           ') 
			stdscr.addstr(h-1, int(w/2), '(%i, %i)' % (p1.getX(), p1.getY())) 
			stdscr.addstr(h-1, 1, '        ') 
			stdscr.addstr(h-1, 1, 'Health: %i' % (p1.getHealth()))
			stdscr.addstr(h-1, w-10, '        ') 
			stdscr.addstr(h-1, w-10, 'Rooms: %i' % (b.getNumRooms()))
			
			b.printBoard()

			stdscr.move(p1.y, p1.x)
			key = stdscr.getch()

			if key == curses.KEY_UP:
				if p1.y == 0:
					p1.y = 0
				else:
					p1.y -= 1

			elif key == curses.KEY_DOWN:
				if p1.y == h-2:
					p1.y = p1.y
				else:
					p1.y += 1

			elif key == curses.KEY_LEFT:
				if p1.x == 0:
					p1.x = 0
				else:
					p1.x -= 1

			elif key == curses.KEY_RIGHT:
				if p1.x == w-1:
					p1.x = p1.x
				else:
					p1.x += 1

			elif key == ord('q') or key == ord('Q'):
				exit()


			b.updateRooms(p1)
			stdscr.refresh()
Exemple #16
0
clock = pygame.time.Clock()

score = 0

def redrawGameWindow():
    win.blit(bg, (0,0))
    text = font.render('Score: ' + str(score), 1, (0,0,0))
    win.blit(text, (390, 10))
    man.draw(win, walkRight, walkLeft, char)
    goblin.draw(win)
    for bullet in bullets:
        bullet.draw(win)
    pygame.display.update()

man = player(300, 410, 64, 64)
goblin = enemy(100, 410, 64, 64, 450)
shootLoop = 0
#Game loop
font = pygame.font.SysFont('comicsans', 30, True)
running = True
bullets = []
while running:
    clock.tick(27)

    if shootLoop > 0:
        shootLoop += 1
    if shootLoop > 3:
        shootLoop = 0

    pygame.time.delay(50)
Exemple #17
0
#Redraw Function
def redrawGameWindow():
    win.blit(bg, (0, 0))
    ui.draw(win)
    ai.draw(win)
    player.draw(win)

    for bullet in bullets:
        bullet.draw(win)

    pygame.display.update()


#Game Loop
player = player(100, 100, 32, 32)
ui = ui(0, screenHeight - 100, 0)
ai = enemy(250, 250, 32, 32, 100, 50)
shootLoop = 0
ammo = 0
options = 0
reload = False
bullets = []
run = True
while run:
    clock.tick(15)

    if ammo == 5:
        reload = True

    if shootLoop > 0:
Exemple #18
0
def startGame():

    print('Welcome to BlakJac')

    print('')

    # setup deck

    gamedeck = deck()

    gamedeck.shuffe()

    # Setup player and dealer

    player1name = input('Please enter your name: ')

    player1 = player(player1name)

    dealer1 = dealer()

    gametable = table(player1, dealer1)

    while True:
        try:
            deposit = int(input('How much would you like to deposit?:'))
            break
        except:
            print('Oops! deposit needs to be a number. Please try again')

    player1.setBalance(deposit)

    print(
        f'Welcome {player1.getName()} your balance is now {player1.getBalance()}'
    )

    while True:
        startgame = str(input('Are you ready to play?[y/n]'))
        if startgame.lower() == 'y': break
        elif startgame.lower() == 'n':
            print('Ok we will wait!')
        else:
            print('Oops! You need to enter y or n')

    print('Get Ready...')
    sleep(3)
    print('3')
    sleep(1)
    print('2')
    sleep(1)
    print('1')
    sleep(1)
    print('GO!!')
    sleep(1)

    gametable.clearScreen()

    # main game logic

    while True:
        gametable.displayBoard()

        player1.placeBet()

        print('')
        print('')

        gametable.clearScreen()
        gametable.displayBoard()

        print('Dealing cards')

        sleep(2)

        player1.hit(gamedeck)

        gametable.clearScreen()
        gametable.displayBoard()
        print('Dealing cards')

        sleep(2)

        player1.hit(gamedeck)

        gametable.clearScreen()
        gametable.displayBoard()
        print('Dealing cards')

        sleep(2)

        dealer1.hit(gamedeck)

        gametable.clearScreen()
        gametable.displayBoard()
        print('Dealing cards')

        sleep(2)

        dealer1.hit(gamedeck)

        gametable.clearScreen()
        gametable.displayBoard()
        print('Dealing cards')

        sleep(2)

        # choose hit or stick logic

        while True:

            #need to check if player already has black jack

            gametable.clearScreen()
            gametable.displayBoard()

            if player1.hand.isblackjack:
                print(f'{player1.getName()} has blackJack!')
                break

            hit = input(f'{player1.getName()} hit or stick? [enter h or s]:')
            if hit.lower() == 'h':
                #hit
                player1.hit(gamedeck)

                gametable.clearScreen()
                gametable.displayBoard()

                sleep(2)

                # check for black jack
                if player1.hand.isblackjack:
                    print(f'{player1.getName()} has blackJack!')
                    break
                #check for bust
                elif player1.hand.isBust:
                    print(f'{player1.getName()} is Bust!')
                    break
                # ask for hit or stick again
                else:
                    continue

            elif hit.lower() == 's':
                #stick
                print('Stick')
                break
            else:
                #incorrect input
                print("Incorrect option, please use h or s for hit or stick")

        # dealer1 turn logic

        sleep(3)

        dealer1.setIsTurn(True)

        while True:

            # show dealers hidden card

            gametable.clearScreen()
            gametable.displayBoard()

            # check to see if dealer has black jack

            if dealer1.hand.isblackjack:
                print(f'{dealer1.getName()} has blackJack')
                sleep(3)
                break

            if dealer1.hand.isBust:
                print(f'{dealer1.getName()} is Bust!')
                sleep(3)
                break

            print('Dealers Turn')
            sleep(3)
            # check if dealer has less then 17, or 17 but with an ace, they hit

            if (dealer1.hand.getvalue() < 17) or (dealer1.hand.getvalue() == 17
                                                  and
                                                  dealer1.hand.containsAce):
                print(f'{dealer1.getName()} takes a HIT!')

                sleep(3)

                dealer1.hit(gamedeck)

                gametable.clearScreen()
                gametable.displayBoard()

                sleep(3)

                continue
            else:
                print(f'{dealer1.getName()} STICKS!')
                break

        # bet win/ loss logic

        # if player bust, check to see if dealer bust = draw
        # else, if deal hans't bust = loose bet

        if player1.hand.isBust:

            if dealer1.hand.isBust:
                #both player and dealer are bust

                print(f'{player1.getName()} and {dealer1.getName()} are bust!')
                print(f'Game is a a draw, returning bet')

                sleep(3)

                player1.setBalance(player1.getBalance() + player1.getBet())

                print('')
                print(f'Player: {player1.getName()}')
                print(f'Current Balance: {player1.getBalance()}')

                sleep(3)

            else:
                #deal is not bust, player must have lost

                print(f'{player1.getName()} lost!')
                #no futher processing as replay logic is clear bet and preserve player balancee.

                sleep(3)

        else:  #player hand is not bust

            if dealer1.hand.isBust:
                # player is not bust, dealer is bust, player wins!
                # double bet and add to balance
                print(f'{player1.getName()} is a winner!')

                sleep(3)

                player1.setBalance(player1.getBalance() +
                                   (player1.getBet() * 2))

                print('')
                print(f'Player: {player1.getName()}')
                print(f'Current Balance: {player1.getBalance()}')

                sleep(3)

            else:
                #player is not bust and dealer is not bust
                #print('neither player or dealer is bust!')

                # add logic to handle winning hand

                if player1.hand.getvalue() > dealer1.hand.getvalue():
                    #player wins
                    print(f'{player1.getName()} is the winner')
                    player1.setBalance(player1.getBalance() +
                                       (player1.getBet() * 2))

                    print('')
                    print(f'Player: {player1.getName()}')
                    print(f'Current Balance: {player1.getBalance()}')

                    sleep(3)
                elif player1.hand.getvalue() < dealer1.hand.getvalue():
                    #dealer wins
                    print(f'{dealer1.getName()} is the winner')
                else:
                    #must be a draw
                    print(f'Game is a a draw, returning bet')

                    sleep(3)

                    player1.setBalance(player1.getBalance() + player1.getBet())

                    print('')
                    print(f'Player: {player1.getName()}')
                    print(f'Current Balance: {player1.getBalance()}')

                    sleep(3)

        #game over

        if player1.getBalance() <= 0:
            print(f'{player1.getName()} has no more chips. Game over')
            break

        # replay logic

        while True:

            playagain = input('Play again?[y or n]').lower()

            if (playagain == 'y'):
                isGameOn = True
                break
            elif (playagain == 'n'):
                isGameOn = False
                break
            else:
                print('Opps! please enter y or n')
                continue

        if isGameOn:
            # need to clear board, and reset player hanad and reset dealer hand
            player1.clearBet()
            player1.hand.clearHand()

            dealer1.hand.clearHand()
            dealer1.setIsTurn(False)

            gametable.clearScreen()

            #add condition to test if deck is 75% empty (len <= 13), start a new deck and shuffle

            if len(gamedeck.cards) <= 13:
                print(
                    f'Number of cards is runnng low. Only {len(gamedeck.cards)} card left.'
                )
                print('Starting new deck')
                gamedeck = deck()
                gamedeck.shuffe()

                sleep(3)

            continue
        else:
            print('GoodBye!')
            break
#***************#

#TODO Need to make a game loop to handle flow of startup, rounds, and turns

## Game Initialize
game_main = engine()
game_main.game_start()
game_main.player_roster = []

## Create the Game Deck and shuffle it.
game_deck = cards()
game_deck.shuff()

## Create and add Players to roster
Player1 = player()
game_main.player_roster.append(Player1)
npc_1 = player("NPC")
game_main.player_roster.append(npc_1)
npc_2 = player("NPC")
game_main.player_roster.append(npc_2)

#***************#

## Main Game Start - Need to make this into a loop.n
# TODO write tests in place of print to terminal
# Set Dealer
game_main.set_dealer()

## Deal Cards -
game_main.deal_players()
Exemple #20
0
        break

    elif mode == '2':
        break
    else:
        print('잘못된 입력입니다.')
        continue

if mode == '1':
    while True:
        print('순서를 선택하세요.')
        print('1 : Player 선 / 2. AI 선')
        temp = input('입력하시오 : ')

        if temp == '1':
            pl = player(row, col, black)
            ai = ai_6(row, col, white, False)
            break
        elif temp == '2':
            pl = player(row, col, white)
            ai = ai_6(row, col, black, False)
            break
        else:
            print('잘못된 입력입니다.')
            continue
else:
    pl = ai_5(row, col, black, False)
    ai = ai_6(row, col, white, False)

# 1 = white(second) / -1 = black(first)
Exemple #21
0
def optimizeMultiple(players,budget,entries):
    """
    Returns multiple optimized lineups for either fanduel or draftkings. This function
    is provided arguments for player data, budget, and the number of entries desired.
    This function can handle up to 20 entries pretty well. It can be easily run through
    its wrapper function multipleOptimizer()
    """

    num_pos = len(players)
    lineups = []
    flineups = []
    for g in range(0,entries):
        # shuffle(players)
        V = np.zeros((num_pos, budget+1))   # array to track max vorp
        Who = np.zeros((num_pos, budget+1), dtype=object) # array to recreate hires
        for x in range(budget+1):
            V[num_pos-1][x] = 0
            Who[num_pos-1][x] = player()
            
            for p in players[num_pos-1]:
                # retrieve relevant players
                if p.cost <= x and p.value > V[num_pos-1][x]:
                    V[num_pos-1][x] = p.value
                    Who[num_pos-1][x] = p
        
        for pos in range(num_pos-2,-1,-1):
            for x in range(budget+1):
                null_player = player()
                # V[pos][x] = V[pos+1][x]     # not taking a player. we will try initializing to -inf
                V[pos][x] = 0
                Who[pos][x] = null_player

        # If it traces back the current lineup correctly the first time it should do it after that

                for p in players[pos]:
                    currentLineup = []
                    amount = x - p.cost
                    for i in range(pos+1,num_pos):
                        k = Who[i][amount]
                        if type(k) != int:
                            if k.id != None:
                                currentLineup.append(k.name)
                                amount = amount - k.cost
                    
                    if p.cost <= x and (V[pos+1][x-p.cost] + p.value >= V[pos][x]) and (p.name not in currentLineup):
                        tempCur = [p.name] + currentLineup
                        masterCopy = 0
                        fmasterCopy = 0
                        if pos != 0:
                            if x - p.cost < 10:
                                continue
                        if g > 0:
                            if pos == 5:
                                for s in lineups:
                                    diff = False
                                    for k in tempCur:
                                        if k not in s:
                                            diff = True
                                    if diff:
                                        masterCopy+=1
                                if masterCopy == len(lineups):

                                    V[pos][x] = V[pos+1][x-p.cost] + p.value
                                    Who[pos][x] = p
                            elif pos == 0:
                                for s in flineups:
                                    diff = False
                                    for k in tempCur:
                                        if k not in s:
                                            diff = True
                                    if diff:
                                        fmasterCopy+=1
                                if fmasterCopy == len(flineups):
                                    V[pos][x] = V[pos+1][x-p.cost] + p.value
                                    Who[pos][x] = p

                            else:
                                V[pos][x] = V[pos+1][x-p.cost] + p.value
                                Who[pos][x] = p
                        else:
                            V[pos][x] = V[pos+1][x-p.cost] + p.value
                            Who[pos][x] = p
                        
        names = set()
        fnames=set()
        print('-----------')
        newLineup = getLineup(Who,[],output=True)
        for p in range(4,len(newLineup)):
            names.add(newLineup[p].name)

        lineups.append(names)
        for p in range(0,len(newLineup)):
            fnames.add(newLineup[p].name)
        flineups.append(fnames)
Exemple #22
0
				for p in self.players:
					playedCard = p.takeTurn()
					if (playedCard.compareSuit(cardLead) and playedCard.compareRank(cardLead) > 0):
						cardLead = playedCard
						winningPlayer = p
				print(winningPlayer.getName())
				winningPlayer.regTrick()
				
			for p in self.players:
				p.regWin(p.getTricks())
			
			self.players.append(self.lead)
			self.deck.resetDeck()
		
		winner = self.players.pop(0)
		for p in self.players:
			if(winner.getPoints() < p.getPoints()):
				winner = p
				
		print("WINNER: " + winner.getName())
		winner.regV()
			
##################################################MAIN##################################################

g = game()
g.addPlayer(player("sally", 0))
# g.addPlayer(player("jimmy", 1))
# g.addPlayer(player("katy", 2))
# g.addPlayer(player("Johny", 3))
# g.addPlayer(player("Susie", 4))
g.mainLoop()
import pprint
from collections import OrderedDict
from Player import player
from Weapon import weapon
import sys
        
print "Welcome To Fallen Warriors Alpha!\n"

try:
    if sys.argv[1] == '-godmode':
        main_player = player('')
        main_player.name = 'GODMODE'
        main_player.strength = 100
        main_player.speed = 100
        main_player.magic = 100
        main_player.agility = 100
        main_player.ranged = 100
        main_player.block = 100
        main_player.sword = 100
        main_player.blunt = 100
        
        main_player.xp = 0
        main_player.level = 801
    
    else:
        name = ''
        while name== '':
            name = raw_input("Enter thy name?: ")
    
            print '\n'
Exemple #24
0
OFFSET = 0

FPS = 40
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
fpsClock = pygame.time.Clock()

gravity = 1
tv = 10
jumpspeed = -12
runspeed = 7

timeclock = 0
worldstatus = 0

play = player(320,400)
goal = goal(100,500)
hitgoal = True
restart = False
died = False

leftflag = 0
rightflag = 0
upflag = 0

floors = []
enemies = []

timer = -1
cycleperiod = 60
save_manager.set_default_object({'hi-score': 0, 'credit': 0})
save_manager.load()

global highscore
highscore = 0
global score
score = 0
global ship_score_threshold
ship_score_threshold = random.randint(100, 500)
global lives
lives = 3
global coins
coins = 0
mystery_ship = None

player = player("player", "PLAYER")
player.set_image(sheet.sprites['PLAYER'])
player.set_position((WIDTH // 2 - player.width // 2, HEIGHT - 32))
player.tint((0, 255, 0))

bullets = []
aliens = []
particles = []

start_game()
global alien_direction
alien_direction = 1
shelters = spawn_shelters(4)
clock = pygame.time.Clock()
os.environ[
    'SDL_VIDEO_CENTERED'] = '1'  # Centering the window on the screen (SDL flag ?)
Exemple #26
0
        print(f'| {playerHandValueStr:29}| {dealerHandValuestr:28}|')
        #        print('|{:^60}'.format('')+'|')
        print('|{:^30}'.format('') + '|' + '{:^29}'.format('') + '|')
        print('|{:-^60}|'.format(''))


#         print('Bet')
#         print(f'{self.player.getBet()}')

    def clearScreen(self):

        system('cls')

if __name__ == '__main__':

    testplayer = player('sunny')
    testdealer = dealer()
    testtable = table(testplayer, testdealer)

    testtable.displayBoard()

    print('clear screen in...3')

    sleep(1)

    print('2')

    sleep(1)

    print('1')
Exemple #27
0
if __name__ == '__main__':
# i will probably put some of this code in an "Environment" class someday
    #this is for very simple testing
    #collsision detction can be ralised with the vector classes also.

    #create a simpüle test environment
    #points
    shades = ["░", "▒", "▓", "█"]

    a = vec2(0, 0)
    b = vec2(2, 0)
    c = vec2(2, 2)
    d = vec2(0, 2)
    env = [line(a,b,shades[2]), line(b,c,shades[2]), line(c,d,shades[3]), line(d,a,shades[3])]

    ply = player(vec2(1, 1),0)



    for i in range(0,360,10):
        ply.ang = i
        render()
        m.output()
        print("--")
        time.sleep(0.1)
        



# Python text RPG
#RISHIK

import cmd
import textwrap
import sys
import os
import time
import random
from Player Class import player
screenWidth = 100

#### PLAYER SETUP #####
Player_name = input("Enter your name: ")
Player_name = player(Player_name, 100, 0, "none", "Outside district 5")

#### Title Screen ####
def title_screen_selections():
    option= input("> ")
    if option.lower() == ("play"):
        start_game() #placeholder until written
    elif option.lower() == ("help"):
        help_menu()
    elif option.lower() == ("quit"):
        sys.exit()
    while option.lower()not in ['play', 'help', 'quit']:
        print("please enter a valid command.")
        option = input("> ")
        if option.lower() == ("play"):
            start_game()  # placeholder until written
        elif option.lower() == ("help"):
Exemple #29
0
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DGRAY = (200, 200, 200)
GRAY = (100, 100, 100)
colors = [RED, GREEN, BLUE, BLACK, DGRAY, GRAY]
c = 0

pygame.init()
w = pygame.display.set_mode((width, height))
pygame.display.set_caption("Hack from home")

font = pygame.font.Font('AnyFont.ttf', 32)
fontB = pygame.font.Font('Black Hold.ttf', 32)
littleFont = pygame.font.Font('Black Hold.ttf', 16)
Me = player(w, BLUE, (width, height), groundHeight)
MyEnemies = []


def DrawScore(score, font):
    score = font.render("Score: " + str(score), True, BLACK)
    w.blit(score, (width // 2 - 50, 0))


while instructions:
    w.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            instructions = False
        elif event.type == pygame.KEYDOWN:
Exemple #30
0
 def __init__(self, root):
     self.root = root
     self.player = player(self.root, self)
Exemple #31
0
Music_1 = pygame.mixer.Sound('Audio/Soundtrack_TrainerMusic.wav')
Music_1.set_volume(0.5)
Music_1.play(-1)

throw = pygame.mixer.Sound('Audio/Ball_throw.wav')  #load sound
catch = pygame.mixer.Sound('Audio/Item.wav')  #load sound
player_collide = pygame.mixer.Sound('Audio/Player_collision.wav')  #load sound
ball_collide = pygame.mixer.Sound('Audio/Ball_collision.wav')  #load sound
player_death = pygame.mixer.Sound('Audio/pikachu_sound.wav')  #load sound
ball_shake = pygame.mixer.Sound('Audio/Ball_shake.wav')  #load sound
ball_shake.set_volume(1.0)
ball_open = pygame.mixer.Sound('Audio/Ball_open.wav')  #load sound
ball_open.set_volume(0.3)

#Initialize Objects
player = player()

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Gameloop~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#

lPress = False
rPress = False
uPress = False
dPress = False

running = True
while running:

    if lives <= 0:
        Music_1.stop()
        pygame.draw.rect(window, (0, 0, 0), (0, 0, 480, 640))
from Player import player

server = "192.168.100.8"  #"192.168.100.23"192.168.100.10
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((server, port))
except socket.error as e:
    str(e)

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

players = [player((10, 10), (244, 238, 238)), player((11, 11), (58, 55, 47))]

# def displayScoreAndResetPlayer(p):
#
#     Score = len(p.playerBody)
#     # print('Score: ', len(p.playerBody))
#
#     notificationBox('You Lost!', 'Your Score was ' + str(Score) + '. Play again?')
#     p.resetPlayer((10, 10))


def threaded_client(conn, player):
    #conn.send(str.encode("Connected"))
    conn.send(pickle.dumps(players[player]))
    reply = ""
    while True: