示例#1
0
        def __init__(self, surface):
            self.surface = surface

            self.BackGround = Background()
            self.DieText = Text(text="DIE! Press R to restart!", name="Die", w=WIN_WIDTH, h=WIN_HEIGHT, color=(30, 30, 30, 1), fontSize=90)
            # self.DieImage = pygame.image.load(PICTURE_AFTER_DIE)
            self.level_name = Menus.currentLevel

            self.on_level_collect = 0

            self.map = []
            self.player = Player()

            self.blocks = pygame.sprite.Group()
            self.wallList = pygame.sprite.Group()
            self.prefabs = []
            self.reload = False

            self.sound = pygame.mixer.Sound(SOUNDS_GAME["W1_Music"])
            self.sound.set_volume(SavesManager.AUDIO_VOLUME)

            self.toLevelSelectorTimer = 0.3

            self.sound.play(loops=10000)

            self.camera = None

            self.buttonMenu = Button(x=650, y=0, w=50, h=50, spriteName="Back", name=None, text=None, color=(230, 230, 230), onColor=(200, 200, 200), pressColor=(150, 150, 150), fontSize=25, func=self.ToLevelSelector)

            self.GenerateLevel()
示例#2
0
    def restart(self):
        self.ball = Ball(W // 2, H // 2)

        self.player1 = Player(5, H // 2 - 40)
        self.player2 = Player(W - 8, H // 2 - 40)

        self.isMove = True
        self.winner = None
示例#3
0
 def test_get_card(self):
     ben = Player("Ben", 2)
     ben.hand = [Card(1, 1), Card(2, 1)]
     c = ben.get_card()
     self.assertTrue(type(c) == Card)
     self.assertTrue(c == Card(1, 1) or c == Card(2, 1))
     after = ben.hand.copy()
     self.assertNotIn(c, after)
示例#4
0
    def __init__(self):
        self.ball = Ball(W // 2, H // 2)

        self.player1 = Player(5, H // 2 - 40)
        self.player2 = Player(W - 8, H // 2 - 40)

        self.isMove = True
        self.winner = None

        self.audio = Audio()
示例#5
0
    def nextLevel(self):
        # go to the next level
        self.curLevel += 1
        self.level = Level(self.curLevel)

        if not self.level.levelExist:
            self.win()

        # init game elements
        self.player = Player(W // 2 - PLAYER_WIDTH // 2)
        self.balls = [Ball(self.player.rect.center)]
示例#6
0
 def __init__(self, name1, name2):
     self.game_over = False
     self.tick = 0
     self.player1 = Player(34, 34, (57, 55, 91), name1)
     self.player2 = Player(29, 29, (255, 128, 128), name2)
     self.map = Map((Cfg.map_x_tiles, Cfg.map_y_tiles))
     self.bombs = []
     self.win = pg.display.set_mode((Cfg.display_x, Cfg.display_y))
     self.outcome = "Tie"
     pg.display.set_caption("Bomb Brigade")
     pg.init()
示例#7
0
文件: App.py 项目: Cyned/Snake
    def __init__(self):
        """init the game"""
        self.running = True         # the snake can move

        self.game = Game()
        self.player = Player(START_SIZE, CELL_SIZE)
        self.apple = Apple(START_POS_APPLE[0], START_POS_APPLE[1], CELL_SIZE)

        pygame.init()
        self._display_surf = pygame.display.set_mode((self.window_width, self.window_height), pygame.HWSURFACE)
        self.image_surf = pygame.image.load(IMAGE_CELL).convert()
        self.apple_surf = pygame.image.load(IMAGE_APPLE).convert()

        pygame.display.set_caption("Snake")     # the caption of the game
示例#8
0
 def generate_level(self, level_map):
     new_player = None
     for y in range(len(level_map)):
         for x in range(len(level_map[y])):
             if level_map[y][x] == 'P':
                 new_player = Player((self.player_group, self.all_sprites),
                                     self.player_image['right'], x, y, TILE_WIDTH, TILE_HEIGHT)
                 self.tiles[y][x] = new_player
             elif level_map[y][x] == 'T':
                 self.tiles[y][x] = Tile((self.tiles_group, self.all_sprites),
                                         self.tile_images['terrain'], x, y, TILE_WIDTH,
                                         TILE_HEIGHT)
             elif level_map[y][x] == 'S':
                 self.tiles[y][x] = Sack((self.sack_group, self.all_sprites),
                                         self.tile_images['sack'], x, y, TILE_WIDTH, TILE_HEIGHT,
                                         self)
             elif level_map[y][x] == 'G':
                 self.tiles[y][x] = Gold((self.gold_group, self.all_sprites),
                                         self.tile_images['gold'], x, y, TILE_WIDTH, TILE_HEIGHT,
                                         self)
             elif level_map[y][x] == 'M':
                 self.tiles[y][x] = Monster((self.monster_group, self.all_sprites),
                                            self.tile_images['monster'], x, y, TILE_WIDTH,
                                            TILE_HEIGHT, self)
             elif level_map[y][x] == 'F':
                 self.tiles[y][x] = Finish((self.finish_group, self.all_sprites),
                                            self.tile_images['finish'], x, y, TILE_WIDTH,
                                            TILE_HEIGHT)
     return new_player
示例#9
0
    def __init__(self, level=1):
        # init level
        self.level = Level(level)
        self.curLevel = level

        # status variables
        self.isFail = False
        self.isStop = False
        self.isWin = False

        self.boosters = []

        # init game elements
        self.player = Player(W // 2 - PLAYER_WIDTH // 2)
        self.balls = [Ball(self.player.rect.center)]

        self.boardSurf = pygame.Surface(SCREEN)
示例#10
0
    def setup_all(self):
        player = Player()
        self.setup_player(player)

        map_game = Board()
        self.map_game = map_game

        client = Client()
        self.client = client
示例#11
0
    def __init__(self):
        # Setup players
        pl1 = Player(1, "Carl", "Red", self)
        pl2 = Player(2, "Naish", "Blue", self)
        pl3 = Player(3, "Mark", "Yellow", self)
        pl4 = Player(4, "Greeny", "Green", self)

        SetupGame.players = [pl1, pl2, pl3, pl4]

        # Setup Game Board
        SetupGame.mainBoard = Board(12, 10)

        # Select next player
        SetupGame.currentPlayer = math.ceil(
            (random() * len(SetupGame.players)))
        SetupGame.nextPlayer = (SetupGame.currentPlayer + 1 - 1) % len(
            SetupGame.players) + 1

        # Set starting season
        season = math.ceil(random() * 4)
示例#12
0
class CardGame:

    # creating CardGame object with 2 players (each one has number of cards according to "player_cards' value), new deck of cards and calling to new_game method/
    def __init__(self, name1, name2, player_cards=10):
        self.player1 = Player(name1, player_cards)
        self.player2 = Player(name2, player_cards)
        self.deck = DeckOfCards()
        self.new_game()

# first it work only if it called from __init__ when we have fresh deck.
# than it shuffle the deck.
# and set the player's hand with number of cards according to the value the user gave when he create the game (default=10)

    def new_game(self):
        if len(self.deck.deck) == 52:
            self.deck.shuffle()
            self.player1.set_hand(self.deck)
            self.player2.set_hand(self.deck)
        else:
            print("ERROR")

# returning the player with the smallest hand.
# if the hands are equal it returns None.

    def get_winner(self):
        if len(self.player1.hand) < len(self.player2.hand):
            return self.player1
        elif len(self.player2.hand) < len(self.player1.hand):
            return self.player2
        else:
            return None


# game=CardGame()
# game.new_game()
# game.player1.get_card()
# print(game.get_winner())
# game.deck.show()
# print(len(game.deck.deck))
# game.player1.show()
# game.player2.show()
示例#13
0
class Game:
    def __init__(self, name1, name2):
        self.game_over = False
        self.tick = 0
        self.player1 = Player(34, 34, (57, 55, 91), name1)
        self.player2 = Player(29, 29, (255, 128, 128), name2)
        self.map = Map((Cfg.map_x_tiles, Cfg.map_y_tiles))
        self.bombs = []
        self.win = pg.display.set_mode((Cfg.display_x, Cfg.display_y))
        self.outcome = "Tie"
        pg.display.set_caption("Bomb Brigade")
        pg.init()

    def action_interpreter(self, player, action):
        if action == "MOVE_UP":
            player.move_up(self.map)
        elif action == "MOVE_DOWN":
            player.move_down(self.map)
        elif action == "MOVE_LEFT":
            player.move_left(self.map)
        elif action == "MOVE_RIGHT":
            player.move_right(self.map)
        elif action == "HARVEST":
            player.harvest(self.map)
        elif action == "BOMB" and player.bombs > 0:
            player.fitness += Cfg.bombs_fitness_place_reward

            self.bombs.append(Bomb(player.x, player.y, self.tick))
            player.bombs -= 1
            self.map.grid[player.x][player.y] = TileType.tile_bomb
        elif action == "WALL" and self.map.grid[player.x][player.y] not in [TileType.tile_wall, TileType.tile_bomb] \
                and player.walls > 0:
            player.fitness += Cfg.walls_fitness_place_reward

            self.map.grid[player.x][player.y] = TileType.tile_wall
            player.walls -= 1

    def loop(self, p1_action, p2_action):
        self.tick += 1

        if self.tick > 1000:
            self.game_over = True

        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.game_over = True

        for bomb in self.bombs:
            if bomb.detonation_tick >= self.tick:
                bomb.explode(self.map, (self.player1, self.player2))
                self.bombs.remove(bomb)

        if self.player1.health <= 0 and self.player2.health <= 0:
            print("Both " + str(self.player1.name) + " and " +
                  str(self.player2.name) + " died")
            self.game_over = True
        elif self.player1.health <= 0:
            print(self.player1.name, "died")
            self.outcome = self.player2.name
            self.game_over = True
        elif self.player2.health <= 0:
            print(self.player2.name, "died")
            self.outcome = self.player1.name
            self.game_over = True

        self.action_interpreter(self.player1, p1_action)
        self.action_interpreter(self.player2, p2_action)

        self.map.draw(self.win)
        self.player1.draw(self.win)
        self.player2.draw(self.win)
        pg.display.update()
示例#14
0
    Title: RPG Battle Sim.
    Copyright: May, 2018

    Description:    This File is used to drive the overall program. This program will
                    ask the user to create there player and then continue. 

"""

# Imports needed for the program. Both imports points to created classes
from Classes.Player import Player
from Classes.Game import Game
from Classes.Terminal_Commands import Terminal

# Local variables
difficulty = 0
player = Player()
Terminal.clear_CLI()
# Welcome message
print("Welcome to the RPG Battle Sim 2018!")
print("Please create your player! \n\n")

# Call to create the users character.
player.create_player()

# Asks the user to select the level of difficulty.
difficulty = input("Please select a level of difficulty. \n" + "1. Easy\n" +
                   "2. Normal\n" + "3. Hard\n" + "4. Extreme\n")

Terminal.clear_CLI()
# While loop that contines until the player currectly creates a character.
cont = False
示例#15
0
 def setUpClass(cls):
     """creating a test player"""
     Square.length = 40
     Test.test_player = Player("test")
     Test.test_player.set_board(1)
     Test.test_player.board.available_squares_dict(Test.test_player)
示例#16
0
 def __init__(self, name="", score=0):
     self.player = Player(name, score)
     self.next = None
示例#17
0
'''
Coded by Joel 'Jocomol' Meier
Contact me at: [email protected]
'''

##imports
from random import *
import time
from Classes.Player import Player
from Classes.enemy import Enemy

##Objects and Enititys
testobject = Player(
    "Testor", "Testonia", 1, 1, 2, 3,
    5)  #name, homeplanet, strenght, health, speed, shield, charsima
#testenemy

##Arrays
T_17 = ["T-17", 1, 12, 6]


##definitions
def new_weapon(weapon_array):
    new_weapon_take = False
    print("\nYou found a", weapon_array[0], "its damage is", weapon_array[1],
          "and it has a Magain Size of", weapon_array[3], "\n")
    print("Also you found", weapon_array[2], "Bolts whit it")
    while new_weapon_take == False:
        take_weapon = input(
            "\nDo you want to [T]ake your old Weapon or [K]eep your Current Weapon the WEAPON_2 "
        )
示例#18
0
pygame.init()
pygame.font.init()
pygame.display.set_mode((800, 600))
pygame.display.set_caption("Blackjack")
screen = pygame.display.get_surface()

# Позиции
pos_player = [254, 350]
pos_dealer = [254, 110]
pos_deck = [650, 110]

deck = Deck(pos_deck)

bankroll = 3000

player = Player(pos_player)
player.set_deck(deck)

dealer = Dealer(pos_dealer)
dealer.set_deck(deck)

chips = ChipsWindow(bankroll)
choice = ChoiceForm(screen)
bets = BetForm(screen, bankroll)
window = None

player.add_card(deck)


while True:
    for e in pygame.event.get():
示例#19
0
 def test_high_CardsNum_inRange(self):
     p = Player("Eyal", 26)
     self.assertTrue(p.cards_num == 26)
示例#20
0
 def test_low_CardsNum_inRange(self):
     p = Player("Eyal", 0)
     self.assertTrue(p.cards_num == 0)
示例#21
0
 def test_low_CardsNum_notInRange(self):
     try:
         p = Player("Eyal", -1)
         self.assertTrue(False)
     except TypeError:
         self.assertTrue(True)
示例#22
0
 def test_invalid_CardsNum(self):
     try:
         p = Player("Eyal", "string")
         self.assertTrue(False)
     except TypeError:
         self.assertTrue(True)
示例#23
0
 def test_valid_name(self):
     p = Player("Dor")
     self.assertTrue(p.name == "Dor")
     self.assertTrue(p.cards_num == 10)
示例#24
0
def user_selection(window):
    window.nodelay(0)
    window.timeout(-5)
    global players_list, player_selected
    player = player_selected
    if player is None:
        player = Player("ANYONE")
    user = None

    x, y = defaultSetting(window)
    setTitle(window, "Snake Reloaded - User Selection", x)
    window.addstr(
        y - 7,
        x("<-------ACTUAL PLAYER: {}------->".format(player.name.strip())),
        "<-------ACTUAL PLAYER: {}------->".format(player.name.strip()))
    window.addstr(y + 1, x("Press [ESC] to back to the main menu"),
                  "Press [ESC] to back to the main menu")
    if players_list is None or players_list.size is 0:
        window.addstr(
            y - 3,
            x("ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
              ),
            "ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
        )
    else:
        user = players_list.head
        window.addstr(y - 3, x(user.player.name), user.player.name)
        window.addstr(y - 3, 70, "---> (L)")
        window.addstr(y - 3, 40, "(K) <---")
        window.addstr(y, x("Press [Enter] to select a player"),
                      "Press [Enter] to select a player")
        window.refresh()

    while 1:
        x, y = defaultSetting(window)
        setTitle(window, "Snake Reloaded - User Selection", x)
        key_s = window.getch()
        window.clear()
        window.addstr(
            y - 7,
            x("<-------ACTUAL PLAYER: {}------->".format(player.name.strip())),
            "<-------ACTUAL PLAYER: {}------->".format(player.name.strip()))

        if key_s == 27:
            window.clear()
            menu(window, 2)
            break
        elif (key_s == 76 or key_s == 108) and players_list is not None:
            user = user.next
            window.addstr(y - 3, x(user.player.name), user.player.name)
            window.addstr(y - 3, 70, "---> (L)")
            window.addstr(y - 3, 40, "(K) <---")
            window.addstr(y, x("Press [Enter] to select a player"),
                          "Press [Enter] to select a player")
        elif (key_s == 107 or key_s == 75) and players_list is not None:
            user = user.back
            window.addstr(y - 3, x(user.player.name), user.player.name)
            window.addstr(y - 3, 70, "---> (L)")
            window.addstr(y - 3, 40, "(K) <---")
            window.addstr(y, x("Press [Enter] to select a player"),
                          "Press [Enter] to select a player")
        elif key_s == curses.KEY_ENTER or key_s in [
                10, 13
        ] and players_list is not None:
            if (players_list.size is not 0):
                window.addstr(y - 3, x(user.player.name), user.player.name)
                window.addstr(y - 3, 70, "---> (L)")
                window.addstr(y - 3, 40, "(K) <---")
                window.addstr(y, x("Player Selected"), "Player Selected")
                player = player_selected = user.player
                window.addstr(
                    y - 7,
                    x("<-------ACTUAL PLAYER: {}------->".format(
                        player.name.strip())),
                    "<-------ACTUAL PLAYER: {}------->".format(
                        player.name.strip()))
            else:
                window.addstr(
                    y - 3,
                    x("ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
                      ),
                    "ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
                )
        else:
            if players_list is None:
                window.addstr(
                    y - 3,
                    x("ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
                      ),
                    "ANY USER, CHARGE A .CSV FILE IN A BULK LOADING OPTION OR CREATE A NEW USER"
                )
            else:
                window.addstr(y - 3, x(user.player.name), user.player.name)
                window.addstr(y - 3, 70, "---> (L)")
                window.addstr(y - 3, 40, "(K) <---")
                window.addstr(y, x("Press [Enter] to select a player"),
                              "Press [Enter] to select a player")

        window.addstr(y + 1, x("Press [ESC] to back to the main menu"),
                      "Press [ESC] to back to the main menu")
        window.refresh()
示例#25
0
 def test_invalid_name(self):
     try:
         p = Player(123)
         self.assertTrue(False)
     except TypeError:
         self.assertTrue(True)
示例#26
0
def eval_genomes(genome, config):
    # Grab our globals
    global G_gen
    global G_hall_of_fame

    # Increment generation
    G_gen += 1

    # Make our empty lists of players, genomes, and N networks
    players = []
    nets = []
    ge = []

    # Set an impossibly low best fitness, so we can easily find our best of each generation
    best_fitness = -1000
    best_player = Player()

    # For each genome...
    # Give them a starting fitness of 0

    g = genome

    g.fitness = 0

    # Add players, neural networks, and genomes to our own lists
    players.append(Player())
    nets.append(network(g, config))
    ge.append(g)

    # For every hand we want to play in a simulation...
    for i in range(C_HANDS_PER_GENERATION * 1000):
        # Let's use a new deck each time
        deck = Deck()
        dealer = Player()

        # Deal two cards to each player
        players, deck = deal_two_each(players, deck)

        for _ in range(2):
            deck.deal_to(dealer)

        for j, player in enumerate(players):
            d = Deck()
            d.cards = []
            for card in deck.cards:
                d.cards.append(card)

            # Activation function
            inputs = player.score, player.has_ace, dealer.hand[0].value
            output = nets[j].activate(inputs)

            # While we have less than 17 points, hit, except 10% of the time stay
            while output[0] > 0.5 and player.score < 21:
                player.hit(d)
                ge[j].fitness += 0.1

        # Standard dealer rules, hit on and up to 16
        while dealer.score <= 16:
            dealer.hit(deck)

        players, ge, msg = reward_genomes_for_wins(players, dealer, ge)

        for j, g in enumerate(ge):
            if g.fitness > best_fitness:
                best_fitness = g.fitness
                best_player = players[j]

        # Display the results of the final game
        if i + 1 == C_HANDS_PER_GENERATION:
            display_game_results(best_player, dealer, i, msg)

        # Make sure their hands are empty
        for player in players:
            player.clear_hand()
        dealer.clear_hand()

    # Display the results of the whole simulation
    display_sim_results(best_player)

    return ge[0]
示例#27
0
 def test_set_hand(self, mock_deal_one):
     deck = DeckOfCards()
     guy = Player("Guy", 3)
     guy.set_hand(deck)
     self.assertIn(Card(1, 1), guy.hand)
     self.assertEqual(guy.hand.count(Card(1, 1)), 3)
示例#28
0
    class Game:
        def __init__(self, surface):
            self.surface = surface

            self.BackGround = Background()
            self.DieText = Text(text="DIE! Press R to restart!", name="Die", w=WIN_WIDTH, h=WIN_HEIGHT, color=(30, 30, 30, 1), fontSize=90)
            # self.DieImage = pygame.image.load(PICTURE_AFTER_DIE)
            self.level_name = Menus.currentLevel

            self.on_level_collect = 0

            self.map = []
            self.player = Player()

            self.blocks = pygame.sprite.Group()
            self.wallList = pygame.sprite.Group()
            self.prefabs = []
            self.reload = False

            self.sound = pygame.mixer.Sound(SOUNDS_GAME["W1_Music"])
            self.sound.set_volume(SavesManager.AUDIO_VOLUME)

            self.toLevelSelectorTimer = 0.3

            self.sound.play(loops=10000)

            self.camera = None

            self.buttonMenu = Button(x=650, y=0, w=50, h=50, spriteName="Back", name=None, text=None, color=(230, 230, 230), onColor=(200, 200, 200), pressColor=(150, 150, 150), fontSize=25, func=self.ToLevelSelector)

            self.GenerateLevel()

        def ToLevelSelector(self):
            self.sound.stop()
            Menus.currentStage = "Level Selector"
            Menus.currentLevel = ""
            time.sleep(PAUSE_TO_LOAD)

        def OpenNextLevel(self):
            if (Menus.currentLevel != list(SavesManager.save["levels"].keys())[-1]):
                SavesManager.save["levels"][list(SavesManager.save["levels"].keys())[list(SavesManager.save["levels"].keys()).index(Menus.currentLevel) + 1]]["open"] = True

        def GenerateLevel(self):
            print(self.level_name)
            try:
                with open(f"Levels\\{self.level_name}.json", "r") as levels:
                    self.level = json.load(levels)
            except:
                raise Exception("Level not found in json!")
            typeWorld = self.level["type"]
            self.level = self.level["map"]

            self.BackGround = Background(typeWorld=typeWorld)

            if (typeWorld == "World_2"):
                self.sound.stop()
                self.sound = pygame.mixer.Sound(SOUNDS_GAME["W2_Music"])
                self.sound.set_volume(SavesManager.AUDIO_VOLUME)
                self.sound.play(loops=10000)

            x, y, step = 0, 0, 32
            level_for = ""
            for i in self.level: level_for += i
            for symbol in level_for:
                if (symbol in LEVEL_GENERATOR_SPRITES[typeWorld].keys() and symbol not in "WVKCDPS|"):
                    block = Block(x, y, symbol, typeWorld=typeWorld)
                    self.blocks.add_internal(block)
                    self.wallList.add_internal(block)
                    x += step
                elif (symbol == "C"):
                    coin = Coin(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(coin)
                    self.wallList.add_internal(coin)
                    x += step
                elif (symbol == "D"):
                    door = Door(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(door)
                    self.wallList.add_internal(door)
                    x += step
                elif (symbol == "K"):
                    key = Key(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(key)
                    self.wallList.add_internal(key)
                    x += step
                elif (symbol == "W"):
                    water = Water(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(water)
                    self.wallList.add_internal(water)
                    x += step
                elif (symbol == "V"):
                    waterKill = WaterKill(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(waterKill)
                    self.wallList.add_internal(waterKill)
                    x += step
                elif (symbol == "S"):
                    spikes = Spikes(x, y, typeWorld=typeWorld)
                    self.blocks.add_internal(spikes)
                    self.wallList.add_internal(spikes)
                    x += step
                elif (symbol == "P"):
                    self.player.rect.topleft = (x, y)
                    x += step
                elif (symbol == "|"):
                    x = 0
                    y += step
                else:
                    x += step
            self.blocks.add_internal(self.player)
            self.player.walls = self.wallList


            total_level_width = len(self.level[0]) * BLOCK_SIZE[0]  # Высчитываем фактическую ширину уровня
            total_level_height = len(self.level) * BLOCK_SIZE[1]  # высоту
            self.camera = Camera(camera_configure, total_level_width, total_level_height)
        
        def Update(self, windows):
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    SavesManager.SaveGame(SavesManager)
                    sys.exit()

                if (event.type == pygame.KEYDOWN):
                    if (self.player.die and event.key == pygame.K_r):
                        self.sound.stop()
                        self.reload = True

            if (not self.player.die):
                self.sound.set_volume(SavesManager.AUDIO_VOLUME)

                self.player.Move(pygame.key.get_pressed())
                self.player.update()
                # self.surface.fill((255, 255, 255))
                self.surface.blit(self.BackGround.image, self.BackGround.rect)

                self.camera.update(self.player)

                for i in self.blocks:
                    if (not i.use):
                        self.surface.blit(i.image, self.camera.apply(i))

            else:
                self.DieText.Update(self.surface)
                # self.surface.blit(self.DieImage, (0, 0))
                

            self.buttonMenu.Update(self.surface)

            if (self.player.inDoor):
                if (self.toLevelSelectorTimer <= 0):
                    SavesManager.ApeendMoneys(SavesManager, self.player.on_level_collect)
                    self.OpenNextLevel()
                    SavesManager.SaveGame(SavesManager)
                    self.ToLevelSelector()
                self.toLevelSelectorTimer -= (pygame.time.get_ticks() - self.getTicksLastFrame) / 1000.0

            self.getTicksLastFrame = pygame.time.get_ticks()

            windows.blit(self.surface, (0, 0))
示例#29
0
def init():
    pygame.init()
    screen = pygame.display.set_mode((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT))
    pygame.display.set_caption(Settings.GAME_TITLE)
    display = pygame.image.load(Settings.IMAGES_DIRECTORY + "spaceBackground.png")
    display = pygame.transform.scale(display, (Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT))
    screen.blit(display, (0, 0))
    gameover = Label(32)
    sb = Scoreboard()

    p1 = Player(1)
    p2 = Player(2)

    clock = pygame.time.Clock()

    startingTimer = 4
    counter = startingTimer

    pygame.time.set_timer(pygame.USEREVENT, 1000)
    countdown = Label(64)
    countdown.text = str(counter-1)
    sprites.add(countdown)
    countdownFinished = False

    fps = 60
    done = False
    p1creating, p2creating = False, False
    gameScreen = True
    instructions = False

    gameScreenSprites = initMainScreen()
    while not done:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if not gameScreen:
                if event.type == pygame.USEREVENT and not countdownFinished:
                    counter -= 1
                    if counter > 0:
                        pygame.mixer.Sound("resources/sounds/select.ogx").play()
                        countdown.text = str(counter)
                    else:
                        countdownFinished = True
                        countdown.text = ''
                        p1.changeDirection('down')
                        p2.changeDirection('up')
                if event.type == pygame.KEYDOWN and countdownFinished:
                    if event.key == pygame.K_ESCAPE:
                        done = True
                    if event.key == pygame.K_LEFT:
                        p2.changeDirection('left')
                    if event.key == pygame.K_RIGHT:
                        p2.changeDirection('right')
                    if event.key == pygame.K_UP:
                        p2.changeDirection('up')
                    if event.key == pygame.K_DOWN:
                        p2.changeDirection('down')
                    if event.key == pygame.K_SPACE:
                        p1creating = True
                    if event.key == pygame.K_w:
                        p1.changeDirection('up')
                    if event.key == pygame.K_s:
                        p1.changeDirection('down')
                    if event.key == pygame.K_a:
                        p1.changeDirection('left')
                    if event.key == pygame.K_d:
                        p1.changeDirection('right')
                    if event.key == pygame.K_RETURN:
                        p2creating = True
                if event.type == pygame.KEYUP and countdownFinished:
                    if event.key == pygame.K_SPACE:
                        p1creating = False
                    if event.key == pygame.K_RETURN:
                        p2creating = False
            elif instructions:
                # Instruction screen keys
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        instructions = False
                        gameScreen = False
                        gameScreenSprites.clear(screen, display)

            else:
                # Game Screen keys
                if event.type == pygame.KEYDOWN:
                    pygame.mixer.Sound("resources/sounds/select.ogx").play()
                    if event.key == pygame.K_F1 or event.key == pygame.K_F2 or event.key == pygame.K_F3:
                        if event.key == pygame.K_F1:
                            Settings.GAME_DIFFICULTY = 0
                            p1.changeDifficulty(0)
                            p2.changeDifficulty(0)
                        elif event.key == pygame.K_F2:
                            Settings.GAME_DIFFICULTY = 1
                            p1.changeDifficulty(1)
                            p2.changeDifficulty(1)
                        elif event.key == pygame.K_F3:
                            Settings.GAME_DIFFICULTY = 2
                            p1.changeDifficulty(2)
                            p2.changeDifficulty(2)
                        gameScreenSprites.clear(screen, display)
                        gameScreenSprites = initInstructionsScreen()
                        instructions = True

        if not gameScreen:
            if p1creating or not checkIfDead(p1, p2):
                p1.createTrail()
            if p2creating or not checkIfDead(p1, p2):
                p2.createTrail()

            for i in range(0, len(p1.trails)):
                if p2.rect.colliderect(p1.trails[i]) and countdownFinished:
                    if not p2.exploded:
                        p2.explode()
                    p1.stop()
                    if not p2.exploding:
                        countdownFinished = False
                        restart(p1, p2)
                        sb.addScore('p1')
                        counter = startingTimer
                        p1creating, p2creating = False, False
                    break
                if i - (len(p1.trails) - 5) < 0 and p1.rect.colliderect(p1.trails[i]) and countdownFinished:
                    if not p1.exploded:
                        p1.explode()
                    p2.stop()
                    if not p1.exploding:
                        countdownFinished = False
                        restart(p1, p2)
                        sb.addScore('p2')
                        counter = startingTimer
                        p1creating, p2creating = False, False
                    break
            for i in range(0, len(p2.trails)):
                if p1.checkOutOfBounds() or p1.rect.colliderect(p2.trails[i]) and countdownFinished:
                    if not p1.exploded:
                        p1.explode()
                    p2.stop()
                    if not p1.exploding:
                        countdownFinished = False
                        restart(p1, p2)
                        sb.addScore('p2')
                        counter = startingTimer
                        p1creating, p2creating = False, False
                    break
                if i - (len(p2.trails) - 5) < 0 and p2.rect.colliderect(p2.trails[i]) and countdownFinished:
                    if not p2.exploded:
                        p2.explode()
                    p1.stop()
                    if not p2.exploding:
                        countdownFinished = False
                        restart(p1, p2)
                        sb.addScore('p1')
                        counter = startingTimer
                        p1creating, p2creating = False, False
                    break

            if sb.p1score >= Settings.GAMEPLAY_MAX_SCORE:
                Gameover('Player 1', gameover)
            if sb.p2score >= Settings.GAMEPLAY_MAX_SCORE:
                Gameover('Player 2', gameover)

            if p2.checkOutOfBounds():
                if not p2.exploded:
                    p2.explode()
                p1.stop()
                if not p2.exploding:
                    countdownFinished = False
                    restart(p1, p2)
                    sb.addScore('p1')
                    counter = startingTimer
                    p1creating, p2creating = False, False
            if p1.checkOutOfBounds():
                if not p1.exploded:
                    p1.explode()
                p2.stop()
                if not p1.exploding:
                    countdownFinished = False
                    restart(p1, p2)
                    sb.addScore('p2')
                    counter = startingTimer
                    p1creating, p2creating = False, False
            if p1.rect.colliderect(p2.rect):
                if not p1.exploded:
                    p1.explode()
                if not p2.exploded:
                    p2.explode()
                if not p2.exploding and not p1.exploding:
                    restart(p1, p2)
                    counter = startingTimer
                    countdownFinished = False
                    p1creating, p2creating = False, False

            redrawScreen(screen, display, sprites)
        else:
            redrawScreen(screen, display, gameScreenSprites)

    pygame.quit()
    quit()
示例#30
0
def main(spectate):

    #Initialize pygame
    pygame.init()
    pygame.font.init()
    DISPLAY = pygame.display.set_mode((625, 600))
    pygame.display.set_caption('Settlers of Catan')
    WHITE = (255, 255, 255)
    DISPLAY.fill(WHITE)

    #Randomly Assign Land Tiles
    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)
    colors = [BLUE] * 46
    land, resource = pull_land()
    tile_resources = {}
    land_count = 1
    for number in [
            8, 9, 10, 14, 15, 16, 17, 20, 21, 22, 23, 24, 27, 28, 29, 30, 34,
            35, 36
    ]:
        colors[number] = land[land_count]
        tile_resources[number] = resource[land_count]
        land_count += 1

    ############Create Hexagonal Board Pieces#################

    size = 100
    start = 50
    running_counter = 0
    center_list = []
    point_list = []
    line_list = []

    ############ First Row of Tiles
    hex_center = (start + ((size / 4) * (3**(1 / 2))), start)
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 5:
        hex_center = (points[2][0] + (2 * points[1]), start)
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Second Row of Tiles
    hex_center = (start, start + (size * 3 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 6:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 3 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Third Row of Tiles
    hex_center = (start + ((size / 4) * (3**(1 / 2))), start + (size * 6 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 5:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 6 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Fourth Row of Tiles
    hex_center = (start, start + (size * 9 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 6:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 9 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Fifth Row of Tiles
    hex_center = (start + ((size / 4) * (3**(1 / 2))), start + (size * 12 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 5:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 12 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Sixth Row of Tiles
    hex_center = (start, start + (size * 15 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 6:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 15 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############ Seventh Row of Tiles
    hex_center = (start + ((size / 4) * (3**(1 / 2))), start + (size * 18 / 4))
    center_list.append(hex_center)
    if colors[running_counter] == (255, 255, 255):
        robber = running_counter
    points = HexCoords(size, hex_center)
    point_list = StorePoints(points[0], point_list, running_counter)
    line_list = StoreLines(points[0], line_list, running_counter)
    pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
    running_counter += 1

    count = 0
    while count < 5:
        hex_center = (points[2][0] + (2 * points[1]), start + (size * 18 / 4))
        center_list.append(hex_center)
        if colors[running_counter] == (255, 255, 255):
            robber = running_counter
        points = HexCoords(size, hex_center)
        point_list = StorePoints(points[0], point_list, running_counter)
        line_list = StoreLines(points[0], line_list, running_counter)
        pygame.draw.polygon(DISPLAY, colors[running_counter], points[0])
        count = count + 1
        running_counter += 1

    ############Done Creating Hexagonal Game Board Pieces#################

    #Add Ports
    font = pygame.font.Font('freesansbold.ttf', 24)
    text = font.render('2:1', True, (255, 255, 0))
    text = pygame.transform.rotate(text, 330)
    DISPLAY.blit(text, (260, 455))
    text = font.render('3:1', True, (0, 0, 0))
    text = pygame.transform.rotate(text, 30)
    DISPLAY.blit(text, (405, 455))
    text = font.render('2:1', True, (0, 100, 0))
    text = pygame.transform.rotate(text, 90)
    DISPLAY.blit(text, (485, 335))
    text = font.render('2:1', True, (204, 85, 0))
    text = pygame.transform.rotate(text, 90)
    DISPLAY.blit(text, (485, 185))
    text = font.render('3:1', True, (0, 0, 0))
    text = pygame.transform.rotate(text, -30)
    DISPLAY.blit(text, (405, 60))
    text = font.render('3:1', True, (0, 0, 0))
    text = pygame.transform.rotate(text, 30)
    DISPLAY.blit(text, (265, 57))
    text = font.render('2:1', True, (124, 252, 0))
    text = pygame.transform.rotate(text, 30)
    DISPLAY.blit(text, (132, 132))
    text = font.render('3:1', True, (0, 0, 0))
    text = pygame.transform.rotate(text, 90)
    DISPLAY.blit(text, (68, 258))
    text = font.render('2:1', True, (68, 60, 84))
    text = pygame.transform.rotate(text, -30)
    DISPLAY.blit(text, (130, 380))

    #Assign Numbers to Tiles and Create 19 Tile Objects
    numbers = number_pull(robber)
    center_list = [(item[0] - 8, item[1] - 15) for item in center_list]
    font = pygame.font.Font('freesansbold.ttf', 32)
    tiles = {}
    for number in [
            8, 9, 10, 14, 15, 16, 17, 20, 21, 22, 23, 24, 27, 28, 29, 30, 34,
            35, 36
    ]:
        tiles[number] = Tile(number, tile_resources[number], numbers[number])
        text = font.render(str(numbers[number]), True, (0, 0, 0))
        if len(numbers[number]) > 1:
            center_list[number] = (center_list[number][0] - 8,
                                   center_list[number][1])
        DISPLAY.blit(text, center_list[number])

    #Mark corner spots on board and Create 54 Spot Obejcts
    spots = {}
    #font = pygame.font.Font('freesansbold.ttf', 48)
    #font = pygame.font.Font('freesansbold.ttf', 12)
    count = 1
    for point in point_list:
        tile_ids = spot_tile_dict[count]
        values = [numbers[x] for x in tile_ids]
        values = ['0' if x == '' else x for x in values]
        values = list(map(int, values))
        value = sum([probability_dict[x] for x in values])
        spots[count] = Spot(count, [tiles[x] for x in tile_ids], values, value)
        #text = font.render('.', True, (0,0,0))
        #DISPLAY.blit(text, (point[0]-6, point[1]-35))
        #text = font.render(str(count), True, (0,0,0))
        #DISPLAY.blit(text, (point[0]-8, point[1]-8))
        count += 1

    #Mark lines that connect spots
    #font = pygame.font.Font('freesansbold.ttf', 12)
    count = 1
    for line in line_list:
        pygame.draw.line(DISPLAY, (0, 0, 0), line[0], line[1], 1)
        #text = font.render(str(count), True, (100,0,0))
        #DISPLAY.blit(text, (((line[0][0]+line[1][0])/2)-8, ((line[0][1]+line[1][1])/2)-8))
        count += 1

    pygame.display.update()

    players = {}
    players[1] = Player(color=(0, 0, 139), id=1)
    players[2] = Player(color=(254, 127, 156), id=2)
    players[3] = Player(color=(106, 13, 173), id=3)
    players[4] = Player(color=(215, 215, 215), id=4)

    nobuild_spots = []

    print('                                 ')

    starting_spots = {}
    for p in [1, 2, 3, 4]:
        starting_spots[p] = {}
        for resource in ['WHEAT', 'ORE', 'WOOD', 'BRICK', 'SHEEP']:
            starting_spots[p][resource] = 0

    time.sleep(0.5)

    count = 0
    for p in [1, 2, 3, 4, 4, 3, 2, 1]:
        count += 1
        start = BuildingSpotSelection(spots, nobuild_spots)
        road = OpeningRoad(
            start, spots,
            [str(x) for x in spots.keys() if x not in nobuild_spots],
            players[1].return_network())
        players[p].build_settlement(start, DISPLAY, point_list)
        players[p].build_road(start, road, DISPLAY, line_list)
        for spot in players[p].return_network().neighbors(str(start)):
            nobuild_spots.append(int(spot))
        nobuild_spots.append(start)
        for tile in spots[start].return_tile_ids():
            number = tile.return_number_tile()
            resource = tile.return_resource()
            try:
                starting_spots[p][resource] += probability_dict[int(number)]
            #For when starting spot is on desert tile
            except:
                continue
        for opp_player in [x for x in [1, 2, 3, 4] if x != p]:
            players[opp_player].edit_network([start], [[start, road]])
        if count > 4:
            for tile in spots[start].return_tile_ids():
                players[p].draw_card(str(tile.return_resource()))
        if spectate is True:
            time.sleep(0.5)

    points = 0
    turn_count = 0
    current_longest_road = 4
    current_road_champion = 0
    current_largest_army = 2
    current_army_champion = 0

    v = ['VP'] * 5
    p = ['YOP'] * 2
    m = ['M'] * 2
    k = ['K'] * 14
    r = ['RB'] * 2
    dev_cards = []
    for card_type in [v, p, m, k, r]:
        for card in card_type:
            dev_cards.append(card)

    while points < 10:
        p = turn_count % 4 + 1
        roll_result = Roll()
        for each in [1, 2, 3, 4]:
            players[each].reap(roll_result, spots)
        turn_output = players[p].use_cards(spots, DISPLAY, point_list,
                                           line_list, nobuild_spots, dev_cards,
                                           players)
        for opp_player in [x for x in [1, 2, 3, 4] if x != p]:
            players[opp_player].edit_network(turn_output[0], turn_output[1])
        for build in turn_output[0]:
            for spot in BuildNetwork().neighbors(str(build)):
                nobuild_spots.append(int(spot))
            nobuild_spots.append(build)
        current_longest_road, current_road_champion = players[
            p].CalculateLongestRoad(current_longest_road,
                                    current_road_champion, players)
        current_largest_army, current_army_champion = players[
            p].EvaluateLargestArmy(current_largest_army, current_army_champion,
                                   players)
        points = players[p].return_points()
        if spectate is True:
            time.sleep(0.1)
        #print(p, turn_count, points)
        turn_count += 1

    print('                                 ')
    print('Player #' + str(p) + ' Wins The Game in', turn_count, 'turns!')
    print('                                 ')
    print('Largest Army:', current_largest_army, 'Player:',
          current_army_champion)
    print('Longest Road:', current_longest_road, 'Player:',
          current_road_champion)
    print('                                 ')
    print('FINAL SCOREBOARD:')
    print('-------------------')
    print('Player 1 (Blue):', players[1].return_points())
    print('Player 2 (Pink):', players[2].return_points())
    print('Player 3 (Purple):', players[3].return_points())
    print('Player 4 (Gray):', players[4].return_points())

    results_df = pd.DataFrame()

    for p in [1, 2, 3, 4]:
        total_starting_prob = 0
        for resource in ['BRICK', 'ORE', 'SHEEP', 'WHEAT', 'WOOD']:
            total_starting_prob += starting_spots[p][resource]
            starting_spots[p][resource] = [starting_spots[p][resource]]
        starting_spots[p]['TOTAL'] = [total_starting_prob]
        starting_spots[p]['POINTS PER TURN'] = [
            players[p].return_points() / turn_count
        ]
        new_row = pd.DataFrame.from_dict(starting_spots[p])
        results_df = pd.concat([results_df, new_row], sort=False)

    pygame.quit()

    #while True:
    #    for event in pygame.event.get():
    #        if event.type == pygame.QUIT:
    #            pygame.quit()
    #            sys.exit()

    return results_df
示例#31
0
 def test_add_card(self):
     Eyal = Player("Eyal")
     Eyal.add_card(Card(3, 3))
     after = Eyal.hand.copy()
     self.assertIn(Card(3, 3), after)