Exemple #1
0
 def press_start_game(self, added_name, save_name):
     self.root.ids.game_box.clear_widgets()
     self.player = Player(added_name)
     self.player_backpack = BackPack("Basic Bag", 10)
     self.player_stash = StashBox("Chest", 20)
     self.player.save_game(save_name, self.player, self.player_backpack, self.player_stash)
     self.game_started = True
     self.press_cancel()
Exemple #2
0
def setup():
    global total_players, player_names, led_count, pixels, i, colors, p1, p2,\
                p3, p4, switch, neigh_in_use
    total_players = 0
    player_names = []
    neigh_in_use = []  # used in dices in order not to cause threading errors

    i = 0
    pname = ''
    while total_players < 2 or total_players > 4:
        total_players = int(input("Колко играча ще играете? - "))

    stlives = 0
    while stlives < 1:
        stlives = int(input('По колко живота ще има всеки? - '))

    stmoney = 0
    while stmoney < 100:
        stmoney = int(input('С каква начална сума ще започнете? - '))

    for _ in range(total_players):
        sleep(0.3)
        pixels.fill(colors['Game'])
        sleep(0.3)
        pixels.fill(colors['Wrong'])

    for _ in range(total_players):
        neigh_in_use.append(0)
        pname = str(input("Как се казвате :)"))
        while player_names.count(pname) >= 1:
            print("try again")
            pname = str(input("Опс, как се казвате :)"))
        else:
            player_names.append(pname)

    p0 = Player('Game', 10000000, 9999999999999, -1)
    p1 = Player(player_names[0], stlives, stmoney, 0)
    p2 = Player(player_names[1], stlives, stmoney, 1)
    switch = {'The game': p0, 0: p1, 1: p2}

    colors[switch[0].name] = (255, 250, 0)
    colors[switch[1].name] = (0, 0, 255)

    if total_players >= 3:
        p3 = Player(player_names[2], stlives, stmoney, 2)
        colors[player_names[2]] = (0, 255, 0)
        switch[2] = p3
    if total_players > 3:
        p4 = Player(player_names[3], stlives, stmoney, 3)
        colors[player_names[3]] = (255, 0, 0)
        switch[3] = p4
Exemple #3
0
 def __init__(self):
     super().__init__()
     # Load images
     self.image_display = pygame.image.load(IMAGE_PLAYER)
     self.screen = pygame.display.set_mode((SCREEN_SIDE, SCREEN_SIDE))
     # Set file
     file = 'Labyrinth'
     # Instatiation labyrinth
     self.level = Level.Level(file)
     # Create listes
     self.list_items = []
     self.list_ennemy = []
     self.list_items = []
     self.syringe = Object.Object(SYRINGE_OBJECT, 14*SPRITE_SIZE, 0)
     # Initiation pygame
     self.init_pygame()
     # set objects
     self.init_objects()
     # Create player
     self.player1 = Player.Player(IMAGE_PLAYER, IMAGE_PLAYER, IMAGE_PLAYER,
                                  IMAGE_PLAYER, self.level)
     # Create ennemy
     self.init_ennemy()
     # Display level and objects
     self.display_level()
     self.display_objects()
     # Display ennemy
     self.blit_image(self.list_ennemy[0].image, (self.list_ennemy[0].x,
                     self.list_ennemy[0].y))
Exemple #4
0
def register():
    print "What do you want your username to be?"
    option = raw_input(">>> ")
    name = option
    print "What is your email?"
    option = raw_input(">>> ")
    email = option
    while True:
        print "What do you want your password to be?"
        option = raw_input(">>> ")
        password = option
        print "Confirm password"
        option = raw_input(">>> ")
        if option != password:
            print "passwords do not match."
        elif len(option) < 6:
            print "password must be at least 6 characters long."
        else:
            password = hashlib.sha224(password).hexdigest()
            break
    PlayerIG = Player(name, ("Mage", Classes["Mage".title()]))
    command = """
    INSERT INTO users VALUES
        (%s, %s, %s, %s, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %s, %s, %s, %s, %s, %d %s, %s )
    """ % (PlayerIG.name, PlayerIG.cclass, PlayerIG.skilltree, PlayerIG.skills,
           PlayerIG.max_mana, PlayerIG.max_health, PlayerIG.max_stamina,
           PlayerIG.stamina, PlayerIG.health, PlayerIG.mana, PlayerIG.attack,
           PlayerIG.strength, PlayerIG.intelligence, PlayerIG.endurance,
           PlayerIG.base_speed, PlayerIG.boots, PlayerIG.weap, PlayerIG.armor,
           PlayerIG.helm, PlayerIG.misc, PlayerIG.arrows, email, password)
    conn = psycopg2.connect("dbname=rpg user=postgres password=password")
    cur = conn.cursor()
    cur.execute(command)
    print "user successfully created"
def generate_level(level):
    new_player, x, y = None, None, None
    spr_2_long = 1

    for y in range(len(level)):
        for x in range(len(level[y])):
            if spr_2_long != 1:
                spr_2_long -= 1
                continue
            if level[y][x] == '#':
                if x != len(level[y]) - 1:
                    if level[y][x + 1] == '#':
                        spr_2_long += 1
                        for z in range(x + 2, len(level[y])):
                            if level[y][z] == '#':
                                spr_2_long += 1
                                if spr_2_long == 7:
                                    break
                            else:
                                break
                Tile('long', x, y, spr_2_long)

            elif level[y][x] == '@':
                new_player = Player(x, y - 1)

            elif level[y][x] == 's':
                Skelet(x, y)

    return new_player, x, y
Exemple #6
0
def main():
	#init
	win = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
	pygame.display.set_caption("First Game")
	game = Game(win)
	game.add_player(Player(300,410,64,64))
	game.add_enemy(Enemy(100,410,64,64,450))
	game.start()
	pygame.quit()
Exemple #7
0
 def __init__(self, player=Player(), player_backpack=BackPack(), player_stash=StashBox(), **kwargs):
     """
     Construct the game app class
     """
     super().__init__(**kwargs)
     self.player = player
     self.player_backpack = player_backpack
     self.player_stash = player_stash
     self.game_started = False
Exemple #8
0
 def event(self, event):
     self.buttons_form.event(event)
     self.connect_form.event(event)
     self.login_form.event(event)
     if event.type == WS_YOU_ID:
         self.current_id = event.id
         self.current_player = Player(self.players_position.pop(0), self.current_id)
         # self.current_player.name = event.name
     if event.type == WS_MESSAGE:
         if event.data.get('type') == 'hit' and event.data.get('id') == self.current_id:
             card = event.data.get('card')
             print('Вы получили карту:', card)
             self.current_player.add_cards(card[0], card[1])
         if event.data.get('type') == 'other_players':
             player = self.add_player(self.players_position.pop(0), event.data.get('id'))
             for card in event.data.get('hand'):
                 player.add_cards(card[1], card[0])
         if event.data.get('type') == 'new_client':
             self.add_player(self.players_position.pop(0), event.data.get('message'))
         if event.data.get('type') == 'hit' and event.data.get('id') == 'Dealer':
             card = event.data.get('card')
             self.dealer.add_cards(card[0], card[1])
         if event.data.get('id') != self.current_id:
             for player in self.other_players:
                 if player.id == event.data.get('id'):
                     player.points = str(event.data.get('points'))
         if self.current_player:
             if event.data.get('id') == self.current_id:
                 self.current_player.points = str(event.data.get('points'))
                 print("У вас " + self.current_player.points + " очков")
         if event.data.get('type') == 'bust':
             self.buttons_form.visible = False
             print("У вас перебор, ход закончен.")
         if event.data.get('type') == 'winner' and event.data.get('id') == self.current_id:
             print('Вы выиграли.')
         if event.data.get('type') == 'winner' and event.data.get('id') != self.current_id:
             print('Вы проиграли.')
         if event.data.get('type') == 'restart':
             self.current_player.restart()
             self.dealer.restart()
             for player in self.other_players:
                 player.restart()
             self.buttons_form.visible = True
         # if self.current_player:
         #     if event.data.get('id') == self.current_id:
         #         name = event.data.get('username')
         #         self.current_player.name = name
         if event.data.get('id') != self.current_id:
             for player in self.other_players:
                 if player.id == event.data.get('id'):
                     name = event.data.get('username')
                     player.name = name
         for player in self.other_players:
             if event.data.get('type') == 'hit' and player.id == event.data.get('id'):
                 card = event.data.get('card')
                 player.add_cards(card[0], card[1])
Exemple #9
0
    def __init__(self):
        self.clock = pygame.time.Clock()
        self.frameCounter = 0

        self.player = Player()  # Igrač
        self.playerImage = pygame.transform.scale(
            pygame.image.load('Assets/player.png'), (60, 60))

        self.explosionCount = 6  # Counter za iteraciju po listi slika eksplozije
        self.explosionCoords = (
            0, 0)  # Koordinate na kojima se rpikazuje eksplozija

        self.enemies = []  # Lista neprijatelja
        self.maxEnemyNumber = 5  # Početni broj maksimalnog mogućeg broja neprijatelja koji se mogu instacirati i prikazati u prozoru

        self.run = True  # Glavni uvjet za izvršavanje while petlje u main metodi
        self.isGameOver = False  # Kada je True igra završava
        self.isPlaying = False  # Boolean je li igra u tijeku ili ne

        self.backgroundImageIndex = 0
Exemple #10
0
def TableSetup():
    players = []
    Table = tbl.Table
    for n in va.PlayerNames:
        players.append(pl.Player(n, va.StartingPurse))

    Table.Players = players
    Table.Min = va.TableMin
    Table.Max = va.TableMax
    Table.Multiple = va.TableMultiple
    return Table
Exemple #11
0
 def __init__(self, wsize):
     pygame.init()
     self.surface = pygame.display.set_mode(wsize)
     self.map = Map.Map()
     self.player = Player.Player()
     self.info = Info.Info(self.player.lifes, 0)
     self.clock = pygame.time.Clock()
     self.background = pygame.image.load(
         "Assets/main_menu_bg.png").convert()
     self.level = self.map.load_level()
     self.handle = True
     self.next_s = 1
     self.creatures = [Fly.Fly([1120, 288]), Snake.Snake([1408, 352])]
def create_player_Sim(X):
    loading_screens = ("Chlorinating Car Pools", "Partitioning Social Network",
                       "Prelaminating Drywall Inventory",
                       "Blurring Reality Lines",
                       "Reticulating 3-Dimensional Splines",
                       "Preparing Captive Simulators",
                       "Capacitating Genetic Modifiers",
                       "Destabilizing Orbital Payloads",
                       "Sequencing Cinematic Specifiers",
                       "Branching Family Trees", "Manipulating Modal Memory")
    help_reader()
    player_info = None
    while True:
        if X == "yes" or X == "y":
            player_info = get_player_info()
            player = Player(player_info[0], player_info[1], player_info[2],
                            player_info[3], player_info[4], player_info[5],
                            player_info[6])
            Zzz = os.system('cls' if os.name == 'nt' else 'clear')
            print("Hello, {}".format(player_info[0]))
            return player
        else:
            player_info = load_player_sql()
            if player_info != None:
                Zzz = os.system('cls' if os.name == 'nt' else 'clear')
                print("\n" * 25 + random.choice(loading_screens) + "...")
                player = Player(player_info[0], player_info[1], player_info[2],
                                player_info[3], player_info[4], player_info[5],
                                player_info[6])
                time.sleep(1.25)
                Zzz = os.system('cls' if os.name == 'nt' else 'clear')
                return player
            else:
                print("Sorry, that name doesn't exist.  Create?")
                X = input()
                continue
Exemple #13
0
def findStats(rawData):
    _outLeaderboard = []

    rawData = BeautifulSoup(rawData, features='lxml')
    statTables = [
        table for table in rawData.find_all('div', class_='data_grid_box')
    ]
    for table in statTables:
        statName = table.find('caption').text
        playerList = Leaderboard(statName)
        for stat in table.find_all('tr'):
            values = ';'.join([col.text for col in stat.find_all('td')])
            splicedVals = formatTableRow(values)
            _rank = splicedVals[0]
            if _rank == '':
                splicedVals[0] = playerList[-1].rank

            selPlayer = Player(*splicedVals)
            playerList.addPlayer(selPlayer)
        _outLeaderboard.append(playerList)
    return _outLeaderboard
Exemple #14
0
class TestShareCards(unittest.TestCase):
    def setUp(self):
        self.player1 = Player("player1", 111)
        self.Discarded = Discarded()
        self.TableCards = TableCards()
        self.deck = Deck()

    def test_give_card(self):
        self.assertEqual(self.player1.number_of_cards, 0)
        self.deck >> self.player1
        self.deck >> self.TableCards
        self.deck >> self.Discarded
        self.deck >> self.Discarded
        self.assertEqual(self.deck.number_of_cards, 48)
        self.assertEqual(self.player1.number_of_cards, 1)
        self.assertEqual(self.TableCards.number_of_cards, 1)
        self.assertEqual(self.Discarded.number_of_cards, 2)
        self.deck >> self.player1
        self.assertEqual(self.Discarded.show_card(), 2)
        self.assertEqual(self.TableCards.show_card(), [Card(1, 'D')])
        self.assertEqual(self.player1.show_card(),
                         [Card(1, 'C'), Card(2, 'C')])
class TestPlayer(unittest.TestCase):

    def setUp(self):
        self.player = Player("Max")
        self.player2 = Player("Leo")

    def tearDown(self):
        del self.player
        del self.player2

    def test_init(self):
        self.assertEqual(self.player.name, "Max")
        self.assertTrue(self.player.is_player)
        self.assertFalse(self.player.is_winner)

    def test_str(self):
        self.assertEqual(self.player.__str__(), "Max")

    def test_check_winner(self):
        self.assertGreaterEqual(self.player.card.calc_sum(), 0)
        self.assertFalse(self.player.is_winner)

    def test_eq(self):
        self.assertEqual(self.player, self.player2)
Exemple #16
0
test_card_1 = Cards('Diamonds', 1)
test_card_2 = Cards('Clubs', 11)
test_card_3 = Cards('Spades', 12)
test_card_4 = Cards('Hearts', 13)
question_card = Cards('?', 0)
player_no = 1

print("--------------------------------------------")
print("            Welcome to In-Between!          ")
print(card_graphics(test_card_1, test_card_2, test_card_3, test_card_4))
print("                 by kupori                 ")
print("--------------------------------------------")

no_player = check_int("Enter Number of Players ---> ")
pot_size = check_int("Enter Total Pot Amount ---> $")
House = Player("House", pot_size, 0, 0, 0)
min_bet_amount = check_int("Enter Minimum Bet/Fold Amount ---> $")
while min_bet_amount > House.score:
    min_bet_amount = check_int("Minimum Amount cannot exceed Pot! ---> $")

p_list = [Player("", 0, 0, 0, 0) for i in range(no_player)]

for x in p_list:
    x.name = input("Enter Player {0}'s Name ---> ".format(player_no))
    player_no += 1

stats = statistics_deck()
deck = shuffle_deck()
bet = []
rounds = 1
t_rounds = 18
Exemple #17
0
from Classes import HandMatch, Player
from random import random


n_players = 6

player_list = [Player("", random()*100//1) for _ in range(n_players//2)]
Hand_match = HandMatch(n_players)

for player in player_list:
    Hand_match << player

[table.deck >> table.players[p] for p in table.players if table.players[p]]
[table.deck >> table.players[p] for p in table.players if table.players[p]]




# d1 = Dealer()
#
#
# deck >> None
# deck >> player
# deck >> table
# player.show_hand()
# table
Exemple #18
0
 def init_ennemy(self):
     ennemy = Player.Player(IMAGE_FINISH, IMAGE_FINISH, IMAGE_FINISH,
                            IMAGE_FINISH, self.level)
     self.list_ennemy.append(ennemy)
Exemple #19
0
 def display_player(self):
     player1 = Player.Player(IMAGE_PLAYER, IMAGE_PLAYER, IMAGE_PLAYER,
                             IMAGE_PLAYER, self.level)
Exemple #20
0
elif sex == "male":
    player_full_name = "Brave Sir Knight " + name
    print("Welcome, " + player_full_name + ".")

sleep(1.5)

###############################################################################

# Instructions (Talvez mais tarde um minitut)
# print("Here are the instructions for playing, " + player_full_name)

###############################################################################

# Stat attribution! + Player() creation
p = Player(name=player_full_name, sex=sex)
StatAssigner(player_full_name, first=True, tokens=15, player=p).cmdloop()
###############################################################################
# Intro skip? I'm tired. Help, brave sir knight!

print("Do you wish to skip the intro?")
skipdecision = input(">> ").strip().lower()
if not (skipdecision.startswith("y")):
    clear()
    sleep(1)
    print("You wake up to see yourself surrounded by nothing but cave walls.")
    sleep()
    print("You do not recall the events of the past couple of days.")
    sleep()
    print("You arrived on this land two nights ago, by boat,")
    sleep()
Exemple #21
0
        if mode == 2:
            if teaminpt.handle_event(event, False, 20):
                #when clicking enter or ok on the team input
                #write the team in teams and make a new team file
                teamnametxt = subfont.render(teaminpt.text, True, black)
                teamname, teamfile, mode = openteams()
                players = []
                if mode == 2: overlap = True
        elif mode == 3:
            if backbtn.handle_event(event): mode = 1
        elif mode == 4:
            if nameinpt.handle_event(event, False, 20):
                #when inputing player names, make them into objects
                players.append(
                    str(len(players) + 1 + playerdel) + ' ' + nameinpt.text)
                playerclass.append(Player(len(players), nameinpt.text))
                playerclass[-1].save(teamfile)
                if len(players) > 10: scroll += 1
                #make a menu for players and delete and a scroll bar that is
                #linked to the menu
                playermn, deletemn1 = makemenu(players)
                nameinpt.text = ''
                nameinpt.txt_surface = nameinpt.font.render(
                    '', True, nameinpt.color)
                playerscroll.newBar(players)
            elif playerscroll.handle_event(event):
                mousedown = True
            elif startbtn.handle_event(event):

                printmatch, printscore = [], []
                scroll = 0
Exemple #22
0
 def setUp(self):
     self.player1 = Player("player1", 111)
     self.player2 = Player("player2", 222)
     self.card = Card('A', 'C')
Exemple #23
0
def runGame():
    '''Set up the game and creating objects'''

    #Set print break
    def pb():
        print("")
        print("")

    #Creating level of difficulty array
    difficultyLevelArray = [1, 2]

    #Setting the 8 ways to win
    across1 = [7, 8, 9]
    across2 = [4, 5, 6]
    across3 = [1, 2, 3]
    down1 = [7, 4, 1]
    down2 = [8, 5, 2]
    down3 = [9, 6, 3]
    highLow = [7, 5, 3]
    lowHigh = [1, 5, 9]

    #Creating GameSetting object
    setting = GameSetting()

    #Creating Player object
    player = Player()

    #Creating Computer object
    computer = Computer()

    #Creating Grid object
    gridDisplay = Grid()

    #Creating a waysToWin object
    w2w = WaysToWin()

    #Adding the 8 ways to win into w2w' wtwArray
    w2w.setWtwArray(across1)
    w2w.setWtwArray(across2)
    w2w.setWtwArray(across3)
    w2w.setWtwArray(down1)
    w2w.setWtwArray(down2)
    w2w.setWtwArray(down3)
    w2w.setWtwArray(highLow)
    w2w.setWtwArray(lowHigh)
    '''Run Game'''

    print(
        "xxx-----------------------------------------------------------------------xxx"
    )
    print("")
    print("                                        Tic Tac Toe")
    print("")
    print(
        "xxx-----------------------------------------------------------------------xxx"
    )

    pb()
    #Adding player name
    pName = input("Enter your name...")
    player.setName(pName)

    #Choosing a level of difficulty
    level = int(
        input("Choose the level of difficulty: 1 for Easy. 2 for Hard..."))

    while level not in difficultyLevelArray:
        level = int(input("That is not a level, please choose another one..."))

    setting.setLevel(level)

    #Choosing who goes 1st and 2nd
    position = int(
        input(
            "Would you like to go first or second?: Enter 1 for first or 2 for second..."
        ))

    setting.setPosition(position, player, computer)

    #Setting the symbol for each player
    firstPlayer = setting.getFirstPlayer()
    firstPlayer.setSymbol("O")
    secondPlayer = setting.getSecondPlayer()
    secondPlayer.setSymbol("X")

    pb()
    print("************************START ************************")
    pb()
    #Display Grid at starting point
    gridDisplay.displayGrid()

    #Start game loop

    #Setting which player is playersTurn
    for item in range(0, 9):
        if item % 2 == 0:
            playersTurn = setting.getFirstPlayer()
        else:
            playersTurn = setting.getSecondPlayer()

        #Perform actions for computer
        if playersTurn.getName() == "Computer":
            level = setting.getLevel()
            symbol = computer.getSymbol()
            playerSymbol = player.getSymbol()
            grid = setting.getGridArray()
            selection = computer.compSelection(level, symbol, playerSymbol,
                                               grid)

            #Update computer's eyes with selection
            computer.updateEyes(selection, symbol)

            #Deleting selection from grid
            grid.remove(selection)

            #Adding selection to playersTurn's array
            computer.addToArray(selection)

            #Adding selection to Grid array
            gridDisplay.addSelectionToGridArray(selection, symbol)

            #display grid
            print("The Computer is thinking...")
            pb()
            pb()
            pb()
            pb()
            pb()
            pb()
            pb()
            time.sleep(4)
            print("-------------The Computer has placed", "'", symbol, "'",
                  "on number", selection, "-------------")
            pb()
            gridDisplay.displayGrid()
            pb()
            pb()
            pb()
            pb()
            pb()
            pb()
            pb()

        #Perform actions for player
        else:

            grid = setting.getGridArray()

            print(
                playersTurn.getName(),
                ",using the number pad, choose a number from the remaining spaces"
            )
            selection = int(input("Enter your selection and press Enter..."))

            #Checking selection is in gridArray
            while selection not in grid:
                selection = int(
                    input(
                        "That is not available, please choose another one..."))

            #Deleting selection from grid
            grid.remove(selection)

            #Adding selection to playersTurn's array
            playersTurn.addToArray(selection)

            #Update computer's eyes with player selection
            symbol = player.getSymbol()
            computer.updateEyes(selection, symbol)

            #Adding selection to Grid array
            gridDisplay.addSelectionToGridArray(selection, symbol)

            pb()
            print("------------------You placed", "'", symbol, "'",
                  "on number", selection, "------------------")
            pb()
            #display grid
            gridDisplay.displayGrid()

        #Check isMatch() if game loop is between 3 and 8
        if (item >= 4) and (item < 8):
            if (isMatch(playersTurn, w2w)):
                print(playersTurn.getName(), "WINS!")
                pb()
                print("End of Game")
                break

        else:

            #draw or win on last move
            if item == 8:
                if (isMatch(playersTurn, w2w)):
                    print(playersTurn.getName(), "WINS!")
                    pb()
                    print("End of Game")
                    break
                if (isMatch(playersTurn, w2w)) == False:
                    print("It's a DRAW!")
                    pb()
                    print("End of Game")
                    pb()
                    break

    #Play Again?
    answer = int(
        input("Would you like to play again? 1 for Yes or 2 for No..."))
    if answer == 1:
        runGame()
    elif answer == 2:
        print("End of game. Thank you for playing")
def player_instance(conns):
    list_of_players = []
    for name, conn in conns.items():
        list_of_players.append(Player(name, conn))
    return list_of_players
Exemple #25
0
class TestHandler(unittest.TestCase):
    def setUp(self):
        self.player1 = Player("player1", 111)
        self.player2 = Player("player2", 222)
        self.card = Card('A', 'C')

    def test_setUp(self):
        self.player1.set_chips(111)
        self.assertEqual(self.player1.name, "player1")
        self.assertEqual(self.player1.chips, 111)
        self.assertEqual(self.player1.cards, [])
        self.assertTrue(self.player1.active)
        self.assertEqual(self.player1.number_of_cards, 0)

    def test_add_chips(self):
        self.player1.set_chips(100)
        self.assertEqual(self.player1.chips, 100)
        self.player1.add_chips(111)
        self.assertEqual(self.player1.chips, 211)

    def test_subtract_chips(self):
        self.player1.set_chips(100)
        self.assertEqual(self.player1.subtract_chips(10), 10)
        self.assertEqual(self.player1.chips, 90)
        self.assertEqual(self.player1.subtract_chips(100), 90)
        self.assertEqual(self.player1.chips, 0)

    def test_transfer_chips(self):
        self.player1.set_chips(111)
        self.player2.set_chips(222)
        self.player1 >> (10, self.player1)
        self.assertEqual(self.player1.chips, 111)
        self.player1 >> (10, self.player2)
        self.assertEqual(self.player1.chips, 101)
        self.assertEqual(self.player2.chips, 232)
        self.player2 >> (300, self.player1)
        self.assertEqual(self.player1.chips, 333)
        self.assertEqual(self.player2.chips, 0)
        self.assertFalse(self.player2.active)

    def test_add_card(self):
        self.assertEqual(self.player1.number_of_cards, 0)
        self.assertEqual(self.player1.add_cards([self.card]), 1)
        self.assertEqual(self.player1.number_of_cards, 1)
Exemple #26
0
def generate_level(level, player_group, tiles_group, all_sprites, clone_tiles):
    new_player, x, y = None, None, None  # заводим переменные для игрока, а также для его координат
    maximum_height = 0  # максимальная высота уровня
    for y in range(len(level)):
        for x in range(len(level[y])):
            # пустой блок
            if level[y][x] == '.':
                Tile(tiles_group, all_sprites, 'empty-block', x, y)
            # простой блок, на котором можно спокойно постоять
            elif level[y][x] == '#':
                Tile(tiles_group, all_sprites, 'upper-block', x, y)
            # заводим персонажа
            elif level[y][x] == '@':
                Tile(tiles_group, all_sprites, 'empty-block', x, y)
                new_player = Player(player_group, all_sprites, x, y)
            # заводим опасные блоки
            elif level[y][x] == '!':
                DangerousTile(tiles_group, all_sprites,
                              'dangerous-triangular-block', x, y)
            # заводим блоки, через которые можно провалиться
            elif level[y][x] == 'S':
                ShadowTile(tiles_group, all_sprites, 'dangerous-shadow-block',
                           x, y)
            # заводим блоки, на которых можно подпрыгнуть высоко
            elif level[y][x] == 'J':
                Tile(tiles_group, all_sprites, 'jump-block', x, y)
            # заводим блоки, которые увеличивают скорость
            elif level[y][x] == '+':
                Tile(tiles_group, all_sprites, 'speed-up-block', x, y)
            # заводим блоки, которые уменьшают скорость
            elif level[y][x] == '-':
                Tile(tiles_group, all_sprites, 'speed-down-block', x, y)
            # клонирующие персонажа блока
            elif level[y][x] == 'C':
                CloneTile(clone_tiles, tiles_group, all_sprites, 'clone-block',
                          x, y)
            # финиширующий уровень блок
            elif level[y][x] == 'F':
                Tile(tiles_group, all_sprites, 'finish-block', x, y)
            # вычисляем максимальную высоту на каждой итерации
            if TILE_HEIGHT * y - ADD_HEIGHT > maximum_height:
                maximum_height = TILE_HEIGHT * y - ADD_HEIGHT
    # вернем игрока, а также размер поля в клетках
    new_player.set_maximum_height(maximum_height)

    # установим строго фрагментированные группы препятствий для игрока
    new_player.set_warning_group(tiles_group)
    new_player.set_dangerous_group(tiles_group)
    new_player.set_jump_group(tiles_group)
    new_player.set_speed_up_group(tiles_group)
    new_player.set_speed_down_group(tiles_group)
    new_player.set_finish_group(tiles_group)

    # возвращаем персонажа, его координаты, максимальную высоту
    return new_player, x, y, maximum_height
Exemple #27
0
# things to import
from Classes import Card, Deck,Hand, Player
from os import system,name
system("cls")
from time import sleep
from pip._vendor.colorama import init
init()
from pip._vendor.colorama import Back, Fore, Style

# list of variables
player_1 = None
player_2 = None
player_3 = None
player_4 = None
Dealer = Player('Dealer', ' ')
hand_1 = Hand()
hand_2 = Hand()
hand_3 = Hand()
hand_4 = Hand()
dealer = Hand()
dealer_hid_card = Card(' ',' ')
hid_card = []
new_deck = Deck()
player_list = [player_1,player_2,player_3,player_4]
hand_list = [hand_1,hand_2,hand_3,hand_4,dealer]
ply_option = {'H':'Hit', 'S':'Stand', 'D':'Double Down'}


# functions for the game

def table(player_list):
 def setUp(self):
     self.player = Player("Max")
     self.player2 = Player("Leo")
Exemple #29
0
class Game:
    def __init__(self, server):
        pygame.init()
        self.screen = pygame.display.set_mode((RESX, RESY), 0, 32)
        pygame.display.set_caption("BlackJack beta")
        self.myFont = pygame.font.SysFont("None", 16, bold=False, italic=False)
        self.run = True
        self.deck_image = load_image(path=os.path.join("images", "cards"), name="back.png")
        self.deck_pos = (600, 50)
        self.server = server

        # buttons form
        self.buttons_form = ButtonsForm((300, 550), self.screen, self.server)

        # connect form
        self.connect_form = ConnectForm((0, 0), self.screen, self.server)

        # login form
        self.login_form = LoginForm((0, 0), self.screen, self.server)

        # Игроки, Диллер
        self.players_position = [(275, 400), (25, 400), (525, 400)]
        self.dealer_position = (250, 75)
        self.current_player = None
        self.dealer = Dealer(self.dealer_position)
        self.other_players = []
        self.server = Server()
        self.current_id = None

    def add_player(self, pos, id):
        player = Player(pos, id)
        self.other_players.append(player)
        return player

    def render(self, screen):
        self.connect_form.render(screen)
        self.buttons_form.render(screen)
        self.login_form.render(screen)
        self.dealer.render(screen)
        if self.current_player:
            self.current_player.render(screen)
            # current_player_font = self.myFont.render(str(self.current_player.name) + '  ' +
            #                                          str(self.current_player.points) + '/21', 0, (0, 0, 0))
            # screen.blit(current_player_font, (290, 380))
        for player in self.other_players:
            player.render(screen)
            # player_font = self.myFont.render(str(player.name) + '  ' + str(player.points) + '/21', 0, (0, 0, 0))
            # screen.blit(player_font, (player.pos[0] + 15, player.pos[1] - 20))
        screen.blit(self.deck_image, self.deck_pos)

    def event(self, event):
        self.buttons_form.event(event)
        self.connect_form.event(event)
        self.login_form.event(event)
        if event.type == WS_YOU_ID:
            self.current_id = event.id
            self.current_player = Player(self.players_position.pop(0), self.current_id)
            # self.current_player.name = event.name
        if event.type == WS_MESSAGE:
            if event.data.get('type') == 'hit' and event.data.get('id') == self.current_id:
                card = event.data.get('card')
                print('Вы получили карту:', card)
                self.current_player.add_cards(card[0], card[1])
            if event.data.get('type') == 'other_players':
                player = self.add_player(self.players_position.pop(0), event.data.get('id'))
                for card in event.data.get('hand'):
                    player.add_cards(card[1], card[0])
            if event.data.get('type') == 'new_client':
                self.add_player(self.players_position.pop(0), event.data.get('message'))
            if event.data.get('type') == 'hit' and event.data.get('id') == 'Dealer':
                card = event.data.get('card')
                self.dealer.add_cards(card[0], card[1])
            if event.data.get('id') != self.current_id:
                for player in self.other_players:
                    if player.id == event.data.get('id'):
                        player.points = str(event.data.get('points'))
            if self.current_player:
                if event.data.get('id') == self.current_id:
                    self.current_player.points = str(event.data.get('points'))
                    print("У вас " + self.current_player.points + " очков")
            if event.data.get('type') == 'bust':
                self.buttons_form.visible = False
                print("У вас перебор, ход закончен.")
            if event.data.get('type') == 'winner' and event.data.get('id') == self.current_id:
                print('Вы выиграли.')
            if event.data.get('type') == 'winner' and event.data.get('id') != self.current_id:
                print('Вы проиграли.')
            if event.data.get('type') == 'restart':
                self.current_player.restart()
                self.dealer.restart()
                for player in self.other_players:
                    player.restart()
                self.buttons_form.visible = True
            # if self.current_player:
            #     if event.data.get('id') == self.current_id:
            #         name = event.data.get('username')
            #         self.current_player.name = name
            if event.data.get('id') != self.current_id:
                for player in self.other_players:
                    if player.id == event.data.get('id'):
                        name = event.data.get('username')
                        player.name = name
            for player in self.other_players:
                if event.data.get('type') == 'hit' and player.id == event.data.get('id'):
                    card = event.data.get('card')
                    player.add_cards(card[0], card[1])

    def mainloop(self):
        while self.run:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE or event.type == pygame.QUIT:
                    sys.exit()
                self.event(event)
            self.screen.fill((0, 100, 0))
            self.render(self.screen)
            pygame.display.flip()
Exemple #30
0
 def setUp(self):
     self.player1 = Player("player1", 111)
     self.Discarded = Discarded()
     self.TableCards = TableCards()
     self.deck = Deck()
Exemple #31
0
print('Welcome to blackjack!')
y = input('Are you ready(y or n): ')

while y.upper() != 'Y':
    y = input('Are you ready(y or n): ')
money = 0
while money <= 0:
    try:
        money = int(input('How much do you want your balance to be? '))
    except ValueError:
        print('Enter valid amount')
        continue
    if money <= 0:
        print('Enter valid amount')
player1 = Player(money)

while y.upper() == 'Y':
    bet_money = player1.balance + 1
    count = 0
    while bet_money > player1.balance or bet_money <= 0:
        count += 1
        try:
            bet_money = int(
                input(
                    f'How much do you want to bet? (your current balance is {player1.balance}) '
                ))
        except ValueError:
            print('Enter integer')
        else:
            if count > 1:
Exemple #32
0
class Game():
    def __init__(self):
        self.clock = pygame.time.Clock()
        self.frameCounter = 0

        self.player = Player()  # Igrač
        self.playerImage = pygame.transform.scale(
            pygame.image.load('Assets/player.png'), (60, 60))

        self.explosionCount = 6  # Counter za iteraciju po listi slika eksplozije
        self.explosionCoords = (
            0, 0)  # Koordinate na kojima se rpikazuje eksplozija

        self.enemies = []  # Lista neprijatelja
        self.maxEnemyNumber = 5  # Početni broj maksimalnog mogućeg broja neprijatelja koji se mogu instacirati i prikazati u prozoru

        self.run = True  # Glavni uvjet za izvršavanje while petlje u main metodi
        self.isGameOver = False  # Kada je True igra završava
        self.isPlaying = False  # Boolean je li igra u tijeku ili ne

        self.backgroundImageIndex = 0

    # Prikazuje neprijatelje u prozoru i provjerava je li igrač pogođen
    def enemyCheck(self):
        if self.explosionCount < 6:
            window.blit(
                explosion[self.explosionCount],
                self.explosionCoords)  # Prikazuje određeni frame eksplozije
            self.explosionCount += 1

        # Prolazi kroz listu neprijatelja
        for enemy in self.enemies:
            # Briše neprijatelje koji su izašli iz vidljivog djela prozora
            if (enemy.x1 + enemy.width < 0
                    or enemy.x1 - enemy.width > windowWidth) or (
                        enemy.y1 + enemy.height < 0
                        or enemy.y1 - enemy.height > windowHeight):
                self.enemies.pop(self.enemies.index(enemy))

            # Provjerava je li igrač pogođen te ovisno o tome briše neprijatelja i povećava njegov hitCount
            if self.player.isHit(enemy):
                self.isGameOver = self.player.health <= 0
                playerHitSoundEffect.play(0)
                self.explosionCount = 0
                # Postavlja koordinate eksplozije na mjesto gdje se preklapaju hitbox od igrača i hitbox od neprijatelja
                self.explosionCoords = (
                    self.player.hitbox.clip(enemy.hitbox).topleft[0] - 32,
                    self.player.hitbox.clip(enemy.hitbox).topleft[1] - 32)
                self.enemies.pop(self.enemies.index(enemy))
            else:
                self.player.score += 0.01

            enemy.draw(window)  # Prikazuje neprijatelja
            enemy.move()  # Pomiče neprijatelja

    # Prikazuje health bar i score igrača u prozoru
    def drawGameStatusInfo(self):
        damageBar = pygame.Rect(int(windowWidth // 2 - 300), 30, 600, 25)
        healthBar = pygame.Rect(
            int(windowWidth // 2 - 300), 30,
            int(600 * self.player.health / self.player.maxHealth), 25)
        pygame.draw.rect(window, red, damageBar)
        pygame.draw.rect(window, (0, 180, 0), healthBar)
        window.blit(self.playerImage,
                    (healthBar.midright[0] - self.playerImage.get_width() // 2,
                     healthBar.centery - self.playerImage.get_height() // 2))
        healthText = fontGameStatusBar.render(
            str(round(self.player.health / 5, 1)) + "%", 100, white)
        window.blit(healthText,
                    (damageBar.centerx - healthText.get_width() // 2,
                     damageBar.centery - healthText.get_height() // 2))

        text = font.render("Score: " + str(round(self.player.score, 0)), 100,
                           white)
        window.blit(text, (windowWidth - text.get_width() - 50, 30))

    # Prikazuje pygame prozor i objekte u njemu
    def redrawWindow(self):
        window.blit(backgroundImages[int(self.backgroundImageIndex // 1)],
                    (0, 0))  # Postavlja pozadinu prozora
        self.backgroundImageIndex = (self.backgroundImageIndex + 0.5) % 202

        self.player.draw(window)  # Prikazuje igrača u prozoru
        self.enemyCheck()
        self.drawGameStatusInfo()
        pygame.display.update(
        )  # Ažurira prozor kako bi se vidjele napravljene promjene

    # Završava igru i prikazuje završni izbornik
    def gameOver(self):
        pygame.mixer.music.stop()
        gameOverSoundEffect.play(0)
        k = 10
        delay = int(gameOverSoundEffect.get_length() * 1000 // k) - 75
        for i in range(0, k + 1):
            pygame.time.delay(delay)
            rect = pygame.Rect(0, 0, windowWidth, (i + 1) * windowHeight // k)
            pygame.draw.rect(window, black, rect)
            pygame.display.update()

        pygame.display.quit()
        pygame.quit()
        score = round(self.player.score, 0)
        ender = Ender(Tk(), score)
        ender.mainloop()

    # ------------------------ MAIN PETLJA ------------------------ #
    def main(self):
        pygame.time.delay(200)
        pygame.mixer.music.play(-1)
        while self.run:
            self.clock.tick(framerate)  # Postavlja framerate igre
            self.frameCounter += 1

            # Petlja koja prolazi kroz evente koje generira korisnik
            for event in pygame.event.get():
                if event.type == pygame.QUIT:  # Provjerava je li korisnik klikuo na X za izlaz iz igre
                    self.run = False

            # Poziva određene funkcije ovisno o pritisnutoj tipki
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                self.player.moveLeft()
            if keys[pygame.K_RIGHT]:
                self.player.moveRight()
            if keys[pygame.K_UP]:
                self.player.moveUp()
            if keys[pygame.K_DOWN]:
                self.player.moveDown()
            if keys[pygame.K_ESCAPE]:
                self.run = False

            # Animacija ulaska igrača u prozor - pomiče igrača od dna do sredine prozora
            if self.player.y > windowHeight / 2 and not (self.isPlaying):
                self.player.moveUp()
            else:
                self.isPlaying = True  # Igrač započinje s igranjem

                # Stvara nove neprijatelje kada stari nestanu iz vidljivog područja prozora
                if len(self.enemies) < self.maxEnemyNumber:
                    enemy = Enemy()
                    self.enemies.append(enemy)
                # Povećava maksimalan broj neprijatelja do 20 svake sekunde (svakih 60 frameova)
                if self.maxEnemyNumber < 20 and not (self.frameCounter % 60):
                    self.maxEnemyNumber += 0.5

            self.redrawWindow()

            if self.isGameOver:
                self.gameOver()
                break