Ejemplo n.º 1
0
    def __init__(self):
        self.screen = pygame.display.set_mode((setting.WIDTH, setting.HEIGHT))
        self.clock = pygame.time.Clock()
        self.running = True
        self.state = 'start'
        self.cell_width = setting.MAZE_WIDTH // setting.COLS
        self.cell_height = setting.MAZE_HEIGHT // setting.ROWS

        #load from environment file
        self.walls = []
        self.coins = []
        self.powerups = []
        self.turns = []
        self.enemies = []
        self.enemies_to_respawn = []
        self.scatter_targets = []
        self.e_pos = []
        self.p_pos = None
        self.respawn = None
        self.load()

        self.player = Player(self, vec(self.p_pos))
        self.make_enemies()
        self.current_score = 0
        self.highscore = self.get_highscore()
        self.level = 0
        self.difficulty = 'normal'
        self.map_type = 'basic'
Ejemplo n.º 2
0
async def roles(ctx):
    summoner = cass.get_summoner(name='aresyama')
    match = summoner.match_history[0]
    teams = match.teams
    team_1 = teams[0].participants
    player_1 = Player(team_1[0].summoner.name, team_1[0].champion.name)
    best_role = player_1.main_role()
    await ctx.send(best_role)
Ejemplo n.º 3
0
 def __init__(self):
     self.dico_sum_position = {
         key: 0
         for key in list(map(str, range(1, 8)))
     }
     self.current_serie = ''
     self.player_list = [
         Player('René Caravel', 'x'),
         Player('Miroslav O\'matic ', 'o')
     ]
Ejemplo n.º 4
0
    def play_game(self):
        P1 = Player(self.player_1_type, 1)
        P2 = Player(self.player_2_type, 2)
        B = Board()
        player_list = [P1, P2]
        turn_count = 0
        error_count = 0
        winner_id = ''

        while turn_count < 42:
            current_player = player_list[turn_count % 2]
            move, piece = current_player.make_move_master(B.board_dict)
            # print("You are here. This is move we got coming in: " + str(move))

            if B.is_error(move) != 0:
                if B.is_error(int(move)) == 1:
                    print('ERROR CODE 1 move not int!')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    continue
                if B.is_error(int(move)) == 2:
                    print('ERROR CODE 2 move not 1-7!')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    if current_player.player_type == 'Human':
                        continue
                    else:
                        break
                if B.is_error(int(move)) == 3:
                    # print('ERROR CODE 3 move off board')
                    error_count += 1
                    # print('Error count: ' + str(error_count))
                    continue
            error_count = 0

            B.board_move(move, piece)
            if self.print_status == 2:
                B.print_board()
            if B.is_win() is True:
                winner_id = (turn_count % 2) + 1
                print("Game Won!!!")
                break
            turn_count += 1
        if winner_id == '':
            winner_id = 3

        if self.print_status == 1 or self.print_status == 2:
            print("FINAL BOARD: ")
            B.print_board()
            print(B.board_dict)
            print('')
            print(B.move_list)

        return winner_id, B.board_dict
def main():
    #display introductory text describing the game
    introText()

    #create a player object with parameters for the player's name (to be entered by player) and
    player = Player(inputName())

    print(
        "You hop into the Ecto-1 and see the Empire State Building 10 blocks ahead of you."
    )
    stepsLeft = stepForward(player)
    currentEnergy = player.getProtonEnergy()

    if currentEnergy > 0 and stepsLeft == 0:
        print(
            "\nCongratulations! You have reached the Empire State Building and rescued the Ghostbusters!"
        )
        print("FINAL STATS FOR {}: ".format(player.getPlayerName()))
        print("     Ghosts Caught: {}".format(player.getGhostsCollected()))
        print("     Proton Energy: {}".format(player.getProtonEnergy()))
        winnerGraphic()

    if currentEnergy <= 0:
        currentEnergy = 0
        print("\nGAME OVER")
        print(
            "You and the rest of New York City have succumbed to this paranormal war. The world is doomed."
        )
        print("FINAL STATS FOR {}: ".format(player.getPlayerName()))
        print("     Ghosts Caught: {}".format(player.getGhostsCollected()))
        print("     Proton Energy: {}".format(currentEnergy))
Ejemplo n.º 6
0
 def play(self) -> None:  # game loop that handles playing the game
     curPlayer = None
     for playerNum in range(2):
         self.players.append(Player(self.players, self.board))
         self.players[playerNum].getListOfShips()
         curPlayer = self.getCurPlayer()
         self.takeShips()
         self.changeTurn()
     self.possibleTotalHits = self.getMaxHits()
     outerCheck = False
     while not self.someoneWon(outerCheck):
         curPlayer = self.getCurPlayer()
         print("{}'s Scanning Board".format(curPlayer.name))
         print(curPlayer.scanningBoard)
         print("{}'s Board".format(curPlayer.name))
         print(curPlayer.playerBoard)
         curPlayer.move(curPlayer, self.getOtherPlayer())
         print(
             f"{curPlayer.name}'s Scanning Board\n{curPlayer.scanningBoard}\n{curPlayer.name}'s Board\n{curPlayer.playerBoard}\n",
             end='')
         if (curPlayer.hitCounter == self.possibleTotalHits):
             outerCheck = True
             self.someoneWon(outerCheck)
             continue
         self.changeTurn()
     self.displayTheWinner(curPlayer)
Ejemplo n.º 7
0
	def createSprites(self):
		player = Player(2, self.width, self.height) #Create player at speed 2
		self.player = player
		self.loadSprite(player, "player") #load player into sprite group
		

		self.loadSprite(Number(0, self.height, self.width, 0, 100, False, 50, self.wins), "scores")
		self.loadSprite(Number(0, self.height, self.width, 750, 100, False, 50, self.losses), "scores")
		
		numbers = []
		equation = self.randomEquationGen()
		
		xpos = 250
		for val in equation[0].split(" "):
			numbers.append(Number(0, self.height, self.width, xpos , 325, False, 50, val))
			xpos += 100

		

		rand = random.choice([250, 425])
		self.answer = Number(0, self.height, self.width, rand, 100, False, 50, str(equation[1]))
		numbers.append(self.answer)
		randans = str(random.randint(0, 81))
		if randans == str(equation[1]):
			randans = str(int(randans)+1)
		if rand == 250:
			numbers.append(Number(0, self.height, self.width, 425, 100, False, 50, randans))
		else:
			numbers.append(Number(0, self.height, self.width, 250, 100, False, 50, randans))

		for num in numbers:
			self.loadSprite(num, "number")
def create_players(p, bots, minimum, maximum):
	""" Create and append players and bots and return list of players."""
	players = []
	for i in range(0, p):
		n, b = get_user_info(i)
		players.append(Player(n, b, "Human", minimum, maximum))
	if not bot_bets:
		for i in range(0, bots):
			entering = True
			while entering:
				try:
					cash = int(
							raw_input(
								"Enter starting cash for Bot {num} "
								"(20, 50, 100, 200, 500, 1000, 2000): "
								.format(num = i+1)))
					if cash in [20, 50, 100, 200, 500, 1000, 2000]:
						entering = False
					else:
						print(
						"Please enter one of these: (20, 50, 100, 200, 500): "
						)
				except ValueError, e:
					print("Enter a number please")
			players.append(BotPlayer("",cash, "Bot", minimum, maximum))
Ejemplo n.º 9
0
def init_players(player_number):
    player_list = []
    for i in range(player_number):
        player_list.append(Player(i))
    for i, player in enumerate(player_list):
        print(f"Insert name for player {i + 1}:")
        player.get_player_name()
    return player_list
    def new(self):
        """For things that should happen once, at the start of a new game"""
        # Load map from file
        self.map_folder = path.join(self.game_folder, 'data/maps')
        # self.map = Map(path.join(game_folder, 'map.txt'))
        self.map = TiledMap(self, path.join(self.map_folder, MAP_NAME))
        self.map_img = self.map.make_map()
        self.map_rect = self.map_img.get_rect()
        # self.paths = breadth_first_search(self.map, self
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.LayeredUpdates()
        self.walls = pg.sprite.Group()
        self.mobs = pg.sprite.Group()
        self.bullets = pg.sprite.Group()
        self.items = pg.sprite.Group()

        # For Loading map from tmx data
        for tile_object in self.map.tmxdata.objects:
            obj_center = vec(tile_object.x + tile_object.width / 2,
                             tile_object.y + tile_object.height / 2)
            if tile_object.name == 'player':
                self.player = Player(self, obj_center.x, obj_center.y)
            if tile_object.name == 'zombie':
                Mob(self, obj_center.x,
                    obj_center.y)  # For EM all entities must have unique id
            if tile_object.name == 'wall':
                Obstacle(self, tile_object.x, tile_object.y, tile_object.width,
                         tile_object.height)
            if tile_object.name in ['health', 'shotgun', 'pistol']:
                Item(self, obj_center, tile_object.name)

#        self.EM = AI.EntityManager()
        for mob in self.mobs:
            # self.EM.add_entity(mob.id) #All entities must have a unique id
            mob.SM.current_state = zombie_states.Idle(self, mob)
            mob.SM.global_state = zombie_states.ZombieGlobalState(self, mob)

        assert self.player is not None
        self.camera = Camera(self.map.width,
                             self.map.height)  # Give camera total size of map
        # Flags
        self.draw_debug = False
        self.paused = False
        self.night = False
        self.effects_sounds['level_start'].play()
Ejemplo n.º 11
0
    def __init__(self):
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        self.running = True
        self.state = 'start'
        self.cell_width = MAZE_WIDTH // COLS
        self.cell_height = MAZE_HEIGHT // ROWS
        self.walls = []
        self.coins = []
        self.enemies = []
        self.e_pos = []
        self.p_pos = None
        self.highscore = 0
        self.load()

        self.player = Player(self, vec(self.p_pos))

        self.make_enemies()
Ejemplo n.º 12
0
def add_players():
    """ Add players to the game """

    x = int(input('How many players do you wanna add to the game? '))
    num = 0
    while x != num:
        name = Player(input('Add a new player: '))
        players.append(name.name)
        num += 1
    print(len(players))
	def __init__(self, n, c, t, tbl_min, tbl_max,s=None, bs=None):
		Player.__init__(self, n, c, t, tbl_min, tbl_max)
		if s is not None:
			self._hand_strategy = s
		else:
			self._hand_strategy = BotPlayer \
								.hand_strategies \
								[randint(0, len(BotPlayer.hand_strategies)-1)]
		self._hand_strategy_name = BotPlayer \
								.hand_strategy_names[self.hand_strategy-1]

		if bs is not None:
			self._bet_strategy = s
		else:
			self._bet_strategy = BotPlayer \
								.bet_strategies \
								[randint(0, len(BotPlayer.bet_strategies)-1)]
		self._bet_strategy_name = BotPlayer \
								.bet_strategy_names[self.bet_strategy-1]
    def __init__(self, n, c, t, tbl_min, tbl_max, s=None, bs=None):
        Player.__init__(self, n, c, t, tbl_min, tbl_max)
        if s is not None:
            self._hand_strategy = s
        else:
            self._hand_strategy = BotPlayer \
                 .hand_strategies \
                 [randint(0, len(BotPlayer.hand_strategies)-1)]
        self._hand_strategy_name = BotPlayer \
              .hand_strategy_names[self.hand_strategy-1]

        if bs is not None:
            self._bet_strategy = s
        else:
            self._bet_strategy = BotPlayer \
                 .bet_strategies \
                 [randint(0, len(BotPlayer.bet_strategies)-1)]
        self._bet_strategy_name = BotPlayer \
              .bet_strategy_names[self.bet_strategy-1]
Ejemplo n.º 15
0
def main():

    # Pretending there is some input data that
    namestring = "Michael Jackson,Janice Joplin,Tina Turner,Billy Joel"    
    # Calling the previous function
    listed_and_separated = name_sep(namestring)
    # Create an empty player dictionary
    player_dictionary = dict()
    # Loop through all names, I chose the first names, doesn't matter
    for i in range(len(listed_and_separated[0])):
        # Create a player class with a temporary variable name
        name = Player(listed_and_separated[0][i],listed_and_separated[1][i], i+1)
        # Add the id from the current player and add it to the dictionary as a key 
        # and assign a Dice instance as a value, with the name of the owner.
        player_dictionary[name.get_id()] = Dice(listed_and_separated[0][i])
    # Loop through keys, roll their dices and print the names
    # and the dices current values
    for key in player_dictionary:
        player_dictionary[key].roll()
        print(player_dictionary[key].get_owner(),player_dictionary[key].get_sideup())
Ejemplo n.º 16
0
class PlayerTest(unittest.TestCase):
    def setUp(self):
        name = "Beata"
        score = 20
        lives = 2
        self.player = Player(score=score, name=name, lives=lives)

    def test_is_name_correct(self):
        expected_name = "Beata"
        msg = "Name is not set correctly"
        self.assertEqual(expected_name, self.player.get_name(), msg)

    def test_is_score_correct(self):
        expected_score = 20
        msg = "Score is not set correctly"
        self.assertEqual(expected_score, self.player.get_score(), msg)

    def test_is_arg_lives_correct(self):
        expected_lives = 2
        msg = "Lives are not set correctly"
        self.assertEqual(expected_lives, self.player.get_lives(), msg)
Ejemplo n.º 17
0
    def start_tutorial(self):
        '''Plays if there is no save file'''
        player_name = self.get_name()
        time.sleep(2)
        player_type = self.get_type()

        if player_type == "Special":
            player = Player(name=player_name, attack=25, sp_attack=50)
            print(
                "Valder: Great! You can have this Spellbook, it's about flames"
            )
            player.inventory.add(Item("Flame Spellbook", 50, 50))
        else:
            player = Player(name=player_name, attack=50, sp_attack=25)
            print("Valder: Then have this Iron Sword, it will keep you safe")
            player.inventory.add(Item("Iron Sword", 50, 50))

        file = open("save_file.sav", "wb")
        pickle.dump(player, file)
        file.close()

        return player
Ejemplo n.º 18
0
def playAdventure():
    print("Welcome to Codebreakers 2018 Adventures!\n")
    name = input("What is your name? ")
    global player
    player = Player(name)
    print("\nWelcome, {}! Remember, if you ever get lost or confused during the game, all you \
have to do is input 'help' and I'll tell you your options. Got it? Good!\n\nLet's get \
started!".format(player.name))
    print('\n')
    print('You are standing outside of an old house. You see a old sign out front and \
the front door appears to be the only way inside.\n')
    while True:
          user_choice = input("\nWhat do you want to do? ")
          if user_choice.lower() == 'quit':
              print("Thanks for playing!")
              return 
          choice(user_choice)
    K_ESCAPE,
    KEYDOWN,
    QUIT,
)

#==============================================================================
# Set up the drawing window
#==============================================================================
pygame.display.init()
screen_dim = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(screen_dim, pygame.FULLSCREEN)
#DISPLAYSURF = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
screen.fill((0, 0, 0))

# Create player
player = Player("stimulus.jpg", screen_dim, GAIN)
position = player.stim_center()
stim_threshold = position[0] + THRESHOLD
# create inital stimulus
screen.blit(player.surf, position)

#-----------------------------------------------------------------------------
# on soft code of state 4
#-----------------------------------------------------------------------------
# present initial stimulus
pygame.display.flip()

#==============================================================================
# py game loop
#==============================================================================
running = True
Ejemplo n.º 20
0
 def setUp(self):
     self.player1 = Player('roie')
     self.player2 = Player('itamar')
     self.card_deck = CardDeck()
     self.card_deck2 = CardDeck()
Ejemplo n.º 21
0
class TestPlayer(TestCase):
    def setUp(self):
        self.player1 = Player('roie')
        self.player2 = Player('itamar')
        self.card_deck = CardDeck()
        self.card_deck2 = CardDeck()

    def test__set_hand(self):
        """
        checks that no duplicated card is dealt to both players
        """
        self.player1._Player__set_hand(self.card_deck, 26)
        self.player2._Player__set_hand(self.card_deck, 26)
        self.assertTrue(len(self.player1.hand) == len(self.player2.hand))
        self.assertTrue(len(self.player1.hand) == 26)
        for p1_card in self.player1.hand:
            self.assertNotIn(p1_card, self.player2.hand)

    def test__set_hand2(self):
        """
        test the condition of the deck after dealing all of it remained as it should.
        """
        self.player1._Player__set_hand(self.card_deck, 26)
        self.player2._Player__set_hand(self.card_deck, 26)
        # deck is empty ofter dealing all of it
        self.assertEqual(self.card_deck.cards_list, [])

        self.player1._Player__set_hand(self.card_deck2, 0)
        self.player2._Player__set_hand(self.card_deck2, 0)
        # deck is left with 50 cards after dealing 2
        self.assertEqual(len(self.card_deck2.cards_list), 50)

    def test_get_card(self):
        """
        check that get_card get a card from the given player not somewhere else
        """
        self.player1._Player__set_hand(self.card_deck, 1)
        p1_card = self.player1.hand[0]
        # checks a card from the players hand is dealt and not a random card from somewhere else
        self.assertEqual(p1_card, self.player1.get_card())
        # checks the card is removed
        self.assertEqual(self.player1.hand, [])

    def test_get_card2(self):
        """
        checks the cards got from the player are random and not the first in the deck.
        the test will be on three cards, because 1 if tried with 1 card
        """
        self.player2._Player__set_hand(self.card_deck, 10)
        p2_hand = self.player2.hand.copy(
        )  # saves a copy of the first hand to compare later
        cards_dealt = []
        for i in range(3):
            cards_dealt.append(
                self.player2.get_card())  # get three cards from the player.

        self.assertNotEqual(cards_dealt, p2_hand[0:3])
        self.assertNotEqual(cards_dealt.reverse(), p2_hand[-3:-1])

    def test_add_cards(self):
        """
        checks the add_cards func can get as many cards as given.
        checks 0, 1, 3
        and check that no card type input is not added to the list
        """
        from Card_class import Card
        self.player1.add_cards(Card({"Diamonds": 1}, 1))
        self.assertEqual(len(self.player1.hand), 1)
        self.player1.add_cards(Card({"Harts": 3}, 3), Card({"Spades": 2}, 8),
                               Card({"Clubs": 4}, 11), 4, "abba", 5.2345)
        self.assertEqual(len(self.player1.hand), 4)
        self.assertNotIn('abba', self.player1.hand)
        self.player1.add_cards()
        self.assertEqual(len(self.player1.hand), 4)
Ejemplo n.º 22
0
Archivo: war.py Proyecto: clausserg/war
if __name__ == "__main__":

    # get player names
    player_names = get_players()
    game_over = False

    # start the actual War game
    while not game_over:
        # create a new deck of cards and shuffle it
        deck = Deck()
        deck.shuffle()

        # randomize which player goes first in game
        random.shuffle(player_names)
        player_one = Player(player_names[0])
        player_two = Player(player_names[1])

        # deal cards to players from the deck
        while len(deck):  # i.e. is not empty
            player_one.get_cards(deck.deal_card())
            player_two.get_cards(deck.deal_card())

        # create the gaming table
        table = Table(player_one.name, player_two.name)
        round = 0  # counting the rounds

        # game session starts here
        playing = True
        while playing:
            round += 1
class Game:
    def __init__(self):
        self.logger = logging.getLogger(f"{__name__}.Game")
        self.logger.debug("Initializing game object")
        pg.mixer.pre_init(
            44100, -16, 1,
            1024)  # increase sound buffer to minise lag when playing sounds
        pg.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        # pg.key.set_repeat(10, 100)  # Lets you hold down a key to keep the move going
        self.game_folder = path.dirname(__file__)
        self.load_images()
        self.load_sounds()
        self.player = None

    def draw_text(self, text, font_name, size, color, x, y, align="nw"):
        font = pg.font.Font(font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        if align == "nw":
            text_rect.topleft = (x, y)
        if align == "ne":
            text_rect.topright = (x, y)
        if align == "sw":
            text_rect.bottomleft = (x, y)
        if align == "se":
            text_rect.bottomright = (x, y)
        if align == "n":
            text_rect.midtop = (x, y)
        if align == "s":
            text_rect.midbottom = (x, y)
        if align == "e":
            text_rect.midright = (x, y)
        if align == "w":
            text_rect.midleft = (x, y)
        if align == "center":
            text_rect.center = (x, y)
        self.screen.blit(text_surface, text_rect)

    def load_images(self):
        self.logger.debug("loading images...")
        # Define game folders
        image_folder = path.join(self.game_folder, 'data/images')
        # Load images from files
        self.title_font = path.join(image_folder, 'ZOMBIE.TTF')
        self.hud_font = path.join(image_folder, 'Impacted2.0.TTF')
        self.dim_screen = pg.Surface(self.screen.get_size()).convert_alpha()
        self.dim_screen.fill((0, 0, 0, 180))
        self.player_imgs = {}
        for img in PLAYER_IMGS:
            self.player_imgs[img] = pg.image.load(
                path.join(image_folder, PLAYER_IMGS[img])).convert_alpha()
        self.wall_img = pg.image.load(path.join(image_folder,
                                                WALL_IMG)).convert_alpha()
        self.wall_img = pg.transform.scale(self.wall_img, (TILESIZE, TILESIZE))
        self.mob_img = pg.image.load(path.join(image_folder,
                                               MOB_IMG)).convert_alpha()
        self.bullet_images = {}
        self.bullet_images['lg'] = pg.image.load(
            path.join(image_folder, BULLET_IMG)).convert_alpha()
        self.bullet_images['lg'] = pg.transform.scale(self.bullet_images['lg'],
                                                      (5, 5))
        self.splat = pg.image.load(path.join(image_folder,
                                             SPLAT)).convert_alpha()
        self.splat = pg.transform.scale(self.splat, (64, 64))
        self.gun_smoke = []
        for img in MUZZLE_SMOKE:
            self.gun_smoke.append(
                pg.image.load(path.join(image_folder, img)).convert_alpha())
        self.item_images = {}
        for item in ITEM_IMAGES:
            self.item_images[item] = pg.image.load(
                path.join(image_folder, ITEM_IMAGES[item])).convert_alpha()
        # Lighting
        self.fog = pg.Surface((WIDTH, HEIGHT))
        self.fog.fill(NIGHT_COLOUR)
        self.light_mask = pg.image.load(path.join(image_folder,
                                                  LIGHT_MASK)).convert_alpha()
        self.light_mask = pg.transform.scale(self.light_mask, LIGHT_RADIUS)
        self.light_rect = self.light_mask.get_rect()

    def load_sounds(self):
        self.logger.debug("loading sounds...")
        sound_folder = path.join(self.game_folder, 'data/sounds')
        self.music_folder = path.join(self.game_folder, 'data/music')
        # Load initial music - define user event to trigger when it ends, picked up in events()
        self.SONG_END = pg.USEREVENT + 1
        self.current_song = random.choice(BG_MUSIC)
        pg.mixer.music.set_endevent(self.SONG_END)
        pg.mixer.music.load(path.join(self.music_folder, self.current_song))
        pg.mixer.music.set_volume(BG_MUSIC_LEVEL)
        # Effects
        self.effects_sounds = {}
        for eff in EFFECTS_SOUNDS:
            self.effects_sounds[eff] = pg.mixer.Sound(
                path.join(sound_folder, EFFECTS_SOUNDS[eff]['file']))
            self.effects_sounds[eff].set_volume(EFFECTS_SOUNDS[eff]['volume'])

        # Weapons
        self.weapon_sounds = {}
        for weapon in WEAPON_SOUNDS:
            self.weapon_sounds[weapon] = []
            for sound in WEAPON_SOUNDS[weapon]:
                s = pg.mixer.Sound(path.join(sound_folder, sound))
                s.set_volume(GUN_SOUND_LEVEL)
                self.weapon_sounds[weapon].append(s)
        #  Zombies
        self.zombie_moan_sounds = []
        for sound in ZOMBIE_MOAN_SOUNDS:
            s = pg.mixer.Sound(path.join(sound_folder, sound))
            s.set_volume(ZOMBIE_MOAN_LEVEL)
            self.zombie_moan_sounds.append(s)
        self.zombie_hit_sounds = []
        for sound in ZOMBIE_HIT_SOUNDS:
            s = pg.mixer.Sound(path.join(sound_folder, sound))
            s.set_volume(ZOMBIE_HIT_LEVEL)
            self.zombie_hit_sounds.append(s)
        # Player
        self.player_hit_sounds = []
        for sound in PLAYER_HIT_SOUNDS:
            s = pg.mixer.Sound(path.join(sound_folder, sound))
            s.set_volume(PLAYER_HIT_LEVEL)
            self.player_hit_sounds.append(s)
        self.player_pain_sounds = []
        for sound in PLAYER_PAIN_SOUNDS:
            s = pg.mixer.Sound(path.join(sound_folder, sound))
            s.set_volume(PLAYER_PAIN_LEVEL)
            self.player_pain_sounds.append(s)
        self.player_panic_sounds = []
        for sound in PLAYER_PANIC_SOUNDS:
            s = pg.mixer.Sound(path.join(sound_folder, sound))
            s.set_volume(PLAYER_PANIC_LEVEL)
            self.player_panic_sounds.append(s)

    def new(self):
        """For things that should happen once, at the start of a new game"""
        # Load map from file
        self.map_folder = path.join(self.game_folder, 'data/maps')
        # self.map = Map(path.join(game_folder, 'map.txt'))
        self.map = TiledMap(self, path.join(self.map_folder, MAP_NAME))
        self.map_img = self.map.make_map()
        self.map_rect = self.map_img.get_rect()
        # self.paths = breadth_first_search(self.map, self
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.LayeredUpdates()
        self.walls = pg.sprite.Group()
        self.mobs = pg.sprite.Group()
        self.bullets = pg.sprite.Group()
        self.items = pg.sprite.Group()

        # For Loading map from tmx data
        for tile_object in self.map.tmxdata.objects:
            obj_center = vec(tile_object.x + tile_object.width / 2,
                             tile_object.y + tile_object.height / 2)
            if tile_object.name == 'player':
                self.player = Player(self, obj_center.x, obj_center.y)
            if tile_object.name == 'zombie':
                Mob(self, obj_center.x,
                    obj_center.y)  # For EM all entities must have unique id
            if tile_object.name == 'wall':
                Obstacle(self, tile_object.x, tile_object.y, tile_object.width,
                         tile_object.height)
            if tile_object.name in ['health', 'shotgun', 'pistol']:
                Item(self, obj_center, tile_object.name)

#        self.EM = AI.EntityManager()
        for mob in self.mobs:
            # self.EM.add_entity(mob.id) #All entities must have a unique id
            mob.SM.current_state = zombie_states.Idle(self, mob)
            mob.SM.global_state = zombie_states.ZombieGlobalState(self, mob)

        assert self.player is not None
        self.camera = Camera(self.map.width,
                             self.map.height)  # Give camera total size of map
        # Flags
        self.draw_debug = False
        self.paused = False
        self.night = False
        self.effects_sounds['level_start'].play()

    def run(self):
        pg.mixer.music.play()
        # game loop - set self.playing = False to end the game
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.events()
            if not self.paused:
                self.update()
            self.draw()

    def quit(self):
        pg.quit()
        sys.exit()

    def update(self):
        """For things that should happen every frame"""
        # update portion of the game loop
        self.all_sprites.update()
        self.camera.update(
            self.player
        )  # Call camera.update - give player as target to follow

        # Game over condition - No more zombies
        #        if len(self.mobs) == 0:
        #            self.playing = False

        # Mobs hit player
        hits = pg.sprite.spritecollide(self.player, self.mobs, False,
                                       collide_hit_rect)
        for hit in hits:
            now = pg.time.get_ticks()
            if now - hit.last_hit > MOB_HIT_TIMEOUT and random.random(
            ) < MOB_HIT_CHANCE:
                hit.last_hit = now
                # self.player.health -= MOB_DAMAGE
                hit.vel = vec(0, 0)
                random.choice(self.player_hit_sounds).play()
                if self.player.health <= 0:
                    self.playing = False
                self.player.got_hit()
                self.player.pos += vec(MOB_KNOCKBACK, 0).rotate(-hits[0].rot)

        # Bullets hit mobs
        hits = pg.sprite.groupcollide(self.mobs, self.bullets, False, True)
        for mob in hits:
            # hit.health -= WEAPONS[self.player.weapon]['damage'] * len(hits[hit])
            # hit.draw_health()
            for bullet in hits[mob]:
                mob.health -= bullet.damage
            mob.vel = vec(0, 0)

        # Player hits items
        hits = pg.sprite.spritecollide(self.player, self.items, False)
        for hit in hits:
            if hit.type == 'health' and self.player.health < PLAYER_HEALTH:
                hit.kill()
                self.effects_sounds['health_up'].play()
                self.player.add_health(HEALTH_PACK_AMOUNT)

            if hit.type in WEAPONS.keys():
                hit.kill()
                self.player.pickup(hit.type)
                # print(hit.type)

    def draw_grid(self):
        for x in range(0, WIDTH, TILESIZE):
            pg.draw.line(self.screen, GREEN, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, TILESIZE):
            pg.draw.line(self.screen, GREEN, (0, y), (WIDTH, y))

    def render_fog(self):
        # draw light mask (gradient) onto fog image
        self.fog.fill((NIGHT_COLOUR))
        self.light_rect.center = self.camera.apply(self.player).center
        self.fog.blit(self.light_mask, self.light_rect)
        self.screen.blit(self.fog, (0, 0), special_flags=pg.BLEND_MULT)

    def draw(self):
        pg.display.set_caption("{:.2f}".format(self.clock.get_fps()))
        # self.screen.fill(BGCOLOR)
        self.screen.blit(self.map_img, self.camera.apply_rect(self.map_rect))
        # self.draw_grid()
        # self.all_sprites.draw(self.screen)
        for sprite in self.all_sprites:
            if isinstance(sprite, Mob):
                sprite.draw_health()
            self.screen.blit(
                sprite.image, self.camera.apply(sprite)
            )  # blit all sprites to screen in location of where the camera says the sprite is


#            if self.draw_debug:
#                pg.draw.rect(self.screen, CYAN, self.camera.apply_rect(sprite.hit_rect), 1)

        if self.night:
            self.render_fog()
        # DEBUG HUD
        if self.draw_debug:
            for wall in self.walls:
                pg.draw.rect(self.screen, CYAN,
                             self.camera.apply_rect(wall.rect), 1)
            for sprite in self.all_sprites:
                if isinstance(sprite, Mob):
                    sprite.draw_health()
                    pg.draw.circle(self.screen, CYAN,
                                   (self.camera.apply(sprite).centerx,
                                    self.camera.apply(sprite).centery),
                                   sprite.detect_radius, 1)
                pg.draw.rect(self.screen, CYAN,
                             self.camera.apply_rect(sprite.hit_rect), 1)

        # HUD functions
        draw_player_stats(self.screen, 10, 10,
                          (self.player.health / PLAYER_HEALTH))
        draw_player_stats(self.screen, 10, 40,
                          (self.player.fatigue / PLAYER_FATIGUE), BEIGE)
        self.draw_text("Zombies: {}".format(len(self.mobs)),
                       self.hud_font,
                       30,
                       WHITE,
                       WIDTH - 10,
                       10,
                       align="ne")
        if self.player.weapon is not None:
            self.draw_text("{}:{}".format(self.player.weapon.name,
                                          self.player.weapon.remaining_shots),
                           self.hud_font,
                           30,
                           WHITE,
                           10,
                           HEIGHT - 50,
                           align="nw")

        # Paused
        if self.paused:
            self.screen.blit(self.dim_screen, (0, 0))
            self.draw_text("Paused",
                           self.title_font,
                           105,
                           RED,
                           WIDTH / 2,
                           HEIGHT / 2,
                           align='center')

        pg.display.flip()

    def play_new_song(self):
        next_song = random.choice(BG_MUSIC)
        self.current_song = next_song
        # pg.mixer.music.load(next_song)
        pg.mixer.music.load(path.join(self.music_folder, next_song))
        pg.mixer.music.play()

    def events(self):
        # catch all events here
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.MOUSEBUTTONDOWN:
                # print(event.button)
                if event.button == 1:
                    self.player.shoot()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()
                if event.key == pg.K_h:
                    self.draw_debug = not self.draw_debug
                if event.key == pg.K_p:
                    self.paused = not self.paused
                if event.key == pg.K_n:
                    self.night = not self.night
                if event.key == pg.K_r:
                    self.player.reload()
                if event.key == pg.K_SPACE:
                    self.player.cycle_weapon()
                if event.key == pg.K_g:
                    self.player.print_inventory()
            if event.type == self.SONG_END:
                self.play_new_song()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        self.screen.fill(BLACK)
        pg.mixer.fadeout(5000)
        self.draw_text("GAME OVER",
                       self.title_font,
                       180,
                       RED,
                       WIDTH / 2,
                       HEIGHT / 2,
                       align='center')
        self.draw_text("Press any key to start",
                       self.title_font,
                       75,
                       WHITE,
                       WIDTH / 2,
                       HEIGHT * 3 / 4,
                       align='center')
        pg.display.flip()
        self.wait_for_key()

    def wait_for_key(self):
        pg.event.wait()  # Clears event queue
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    waiting = False
                    self.quit()

                if event.type == pg.KEYUP:
                    waiting = False
Ejemplo n.º 24
0
def psap(participant_name, opponent_image_name_list):
    """Initialize the game screen"""
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption(screen_name)
    """Initialize clock variables"""
    clock = pygame.time.Clock()
    safe_period = 0
    """Initialize game phases"""
    phase = 0
    phase_timer = 0
    start = ObjectPrint(start_message, start_message_fontsize, start_message_x,
                        start_message_y, screen)
    practice = ObjectPrint(practice_opponent_name, practice_opponent_fontsize,
                           practice_opponent_x, practice_opponent_y, screen)
    transition = ObjectPrint(transition_message, transition_message_fontsize,
                             transition_message_x, transition_message_y,
                             screen)
    end = ObjectPrint(end_message, end_message_fontsize, end_message_x,
                      end_message_y, screen)
    """Initialize AI variables"""
    opponent = AI()
    screen_opponent_name = ObjectPrint(opponent_name, opponent_name_fontsize,
                                       opponent_name_x, opponent_name_y,
                                       screen)
    screen_opponent_points = FlashingObject(opponent.points,
                                            opponent_points_fontsize,
                                            opponent_points_x,
                                            opponent_points_y, screen)
    """Initialize Player variables"""
    participant = Player()
    screen_player_name = ObjectPrint(participant_name,
                                     participant_name_fontsize,
                                     participant_name_x, participant_name_y,
                                     screen)
    screen_player_points = FlashingObject(participant.points,
                                          participant_points_fontsize,
                                          participant_points_x,
                                          participant_points_y, screen)
    """Initialize interface variables"""
    screen_counter = FlashingObject(participant.count, counter_fontsize,
                                    counter_x, counter_y, screen)
    screen_choice_1 = ObjectPrint('1', indicators_fontsize, indicators_x,
                                  indicators_y, screen)
    screen_choice_2 = ObjectPrint('2', indicators_fontsize,
                                  indicators_x + indicator_spacing,
                                  indicators_y, screen)
    screen_choice_3 = ObjectPrint('3', indicators_fontsize,
                                  indicators_x + (2 * indicator_spacing),
                                  indicators_y, screen)
    defense_meter_label = ObjectPrint(meter_label, meter_label_fontsize,
                                      meter_label_x, meter_label_y, screen)
    choice_list = [screen_choice_1, screen_choice_2, screen_choice_3]
    """DATA OUTPUT"""
    data = {'1': {}, '2': {}, '3': {}}
    """Functions"""
    def game_screen_display(tic, screen_player_points, screen_opponent_points,
                            opponent, participant, screen_counter,
                            screen_choice_1, screen_choice_2, screen_choice_3,
                            screen_opponent_name, screen_player_name,
                            choice_list, opponent_image_print):
        if participant_earned_animation:
            screen_player_points.begin_flashing(
                participant.earned_point_animation_timer, 'pos')
        if participant_provoked_animation:
            screen_player_points.begin_flashing(
                participant.provoked_animation_timer, 'neg')
        if opponent_earned_animation:
            screen_opponent_points.begin_flashing(
                opponent.earned_point_animation_timer, 'pos')
        if opponent_provoked_animation:
            screen_opponent_points.begin_flashing(
                opponent.provoked_animation_timer, 'neg')
        screen_player_points.flashing_check(tic)
        screen_opponent_points.flashing_check(tic)
        if participant_choice_dump_animation:
            if participant.choice_dump_animation_timer > 0:
                screen_counter.font_color = (255, 0, 0)
            else:
                screen_counter.font_color = (0, 0, 0)
        # USE: Light up active counter.
        if active_counter_animation:
            for choice in choice_list:
                if choice.content == participant.active_counter:
                    choice.font_color = (0, 255, 0
                                         )  # choose active counter color
                else:
                    choice.font_color = (0, 0, 0)
        # Display objects
        if meter_print:
            defense_meter_label.display_object()
        if opponent_points_print:
            screen_opponent_points.display_object()
        if counter_print:
            screen_counter.display_object()
        if indicators_print:
            screen_choice_1.display_object()
            screen_choice_2.display_object()
            screen_choice_3.display_object()
        if opponent_name_print:
            screen_opponent_name.display_object()
        if participant_name_print:
            screen_player_name.display_object()
        if participant_points_print:
            screen_player_points.display_object()
        if opponent_image_print:
            screen.blit(opponent_image, (opponent_image_x, opponent_image_y))

    def get_block_quantities(number):
        hundreds = number // 100
        number -= (100 * hundreds)
        tens = number // 10
        ones = number % 10
        return [hundreds, tens, ones]

    def print_meters(block_list, screen, meter_x, meter_y, block_spacing_x,
                     block_spacing_y, hundreds_block_color, tens_block_color,
                     ones_block_color, block_width, block_height):
        if meter_print:
            for block in range(block_list[0]):
                pygame.draw.rect(screen, pygame.Color(hundreds_block_color),
                                 (meter_x + (block_spacing_x * block), meter_y,
                                  block_width, block_height))
            for block in range(block_list[1]):
                pygame.draw.rect(
                    screen, pygame.Color(tens_block_color),
                    (meter_x + (block_spacing_x * block),
                     meter_y + block_spacing_y, block_width, block_height))
            for block in range(block_list[2]):
                pygame.draw.rect(
                    screen, pygame.Color(ones_block_color),
                    (meter_x + (block_spacing_x * block), meter_y +
                     (2 * block_spacing_y), block_width, block_height))

    # ----------------------------------------------------------------------------------------------------------------------
    """Game Loop"""
    running = True
    while running:
        tic = clock.tick(30) / 1000
        screen.fill((255, 255, 255))
        for event in pygame.event.get():

            #   ALL THE OUTPUT THING GO HERE
            if event.type == pygame.QUIT:
                print(phase)
                running = False
            # ----------------------------------------------------------------------------------------------------------------------
            """Keydown events"""
            if event.type == pygame.KEYDOWN:

                if phase % 2 == 0:
                    if event.key == pygame.K_n:
                        if phase < 8:
                            participant = Player()
                            opponent = AI()
                            screen_player_points = FlashingObject(
                                participant.points,
                                participant_points_fontsize,
                                participant_points_x, participant_points_y,
                                screen)
                            screen_opponent_points = FlashingObject(
                                opponent.points, opponent_points_fontsize,
                                opponent_points_x, opponent_points_y, screen)
                            screen_counter = FlashingObject(
                                participant.count, counter_fontsize, counter_x,
                                counter_y, screen)
                            phase += 1
                            if phase == 1:
                                phase_timer = practice_phase_duration
                                opponent.points = practice_opponent_points
                            else:
                                phase_timer = block_phase_duration
                                safe_period = safe_period_default

                if event.key == pygame.K_ESCAPE:
                    data_file_name = os.path.join('Data', 'pickle', participant_name + "_" + \
                    str(datetime.datetime.now()).replace(" ", "_").replace(":", "_").replace(".", "_").replace("-", "_") + ".pickle")
                    data_file = open(data_file_name, 'ab')
                    pickle.dump(data, data_file)
                    data_file.close()
                    dumpDict = pickle2Dumps(data_file_name)
                    writer = ExcelWriter(data_file_name.replace('.pickle', '.xlsx').replace('pickle', 'excel')\
                        .replace(participant_name, 'Dumps_' + participant_name), engine='xlsxwriter')
                    for trial in dumpDict:
                        trialDumps = DataFrame(dumpDict[trial])
                        trialDumps.to_excel(writer,
                                            sheet_name=str('dumps_trial_' +
                                                           trial))
                    writer.save()
                    pygame.display.quit()
                    running = False

                if not phase % 2 == 0:
                    if event.key == pygame.K_KP1:
                        participant.counter_update('1')

                    if event.key == pygame.K_KP2:
                        participant.counter_update('2')

                    if event.key == pygame.K_KP3:
                        participant.counter_update('3')
        # ---------------------------------------------------------------------------------------------------------------------
        if phase == 0:  # PHASE: start
            if start_message_print:
                start.display_object()
            pygame.display.update()
            continue
        # ---------------------------------------------------------------------------------------------------------------------
        if phase == 1:  # PHASE: practice
            phase_timer -= tic  # TODO: code smell
            if phase_timer <= 0: phase += 1  # TODO: code smell

            participant.timekeeping(tic)
            opponent.timekeeping(tic)
            participant.condition_check(tic, option1_presses, option2_presses,
                                        option3_presses,
                                        participant_earned_animation_duration,
                                        participant_defense_duration_mean,
                                        participant_defense_duration_sd)

            # use: participant stealing points
            if participant.stole_point == 1 and len(
                    opponent.defense_blocks) <= 0 < opponent.points:
                """Successful point steal"""
                opponent.points -= 1
                opponent.provoked_animation_timer = opponent_provoked_animation_duration
                participant.stole_point = 0
            else:
                participant.stole_point = 0
            """ObjectPrint content updates"""
            screen_player_points.content = participant.points
            screen_counter.content = participant.count
            screen_opponent_points.content = opponent.points

            print_meters(get_block_quantities(len(participant.defense_blocks)),
                         screen, meter_x, meter_y, block_spacing_x,
                         block_spacing_y, hundreds_block_color,
                         tens_block_color, ones_block_color, block_width,
                         block_height)

            game_screen_display(tic,
                                screen_player_points,
                                screen_opponent_points,
                                opponent,
                                participant,
                                screen_counter,
                                screen_choice_1,
                                screen_choice_2,
                                screen_choice_3,
                                practice,
                                screen_player_name,
                                choice_list,
                                opponent_image_print=False)

            pygame.display.update()
            continue
        # ----------------------------------------------------------------------------------------------------------------------
        if phase % 2 == 0:  # PHASE: transitionnn
            if phase > 2:
                if participant.points > 0:
                    data[str((int(phase / 2) -
                              1))]['player_points'] = participant.points
                else:
                    data[str((int(phase / 2) - 1))]['player_points'] = 0
                data[str(
                    (int(phase / 2) -
                     1))]['total_presses'] = participant.counters_data_output
                data[str((int(phase / 2) -
                          1))]['player_provoked'] = participant.provoked_total
                data[str((int(phase / 2) - 1))]['dumps'] = participant.dumps
                # TODO: remove the seconds latency, add number of clicks on the dumped counter
                data[str(
                    (int(phase / 2) -
                     1))]['defense_rewards'] = participant.defense_blocks_data
            # CHANGED: adjustable phase num
            if phase >= (num_phases * 2 + 2):  # PHASE: end
                if end_message_print:
                    end.display_object()
                pygame.display.update()
                continue
            else:
                if transition_message_print:
                    transition.display_object()
                pygame.display.update()
                continue

        else:  # PHASE: block
            opponent_image = pygame.image.load(opponent_image_name_list[int(
                (phase - 1) / 2)])
            phase_timer -= tic
            if phase_timer <= 0: phase += 1
            if safe_period > 0:
                safe_period -= tic
            else:
                safe_period = 0

            participant.timekeeping(tic)
            opponent.timekeeping(tic)
            """Participant's move"""
            participant.condition_check(tic, option1_presses, option2_presses,
                                        option3_presses,
                                        participant_earned_animation_duration,
                                        participant_defense_duration_mean,
                                        participant_defense_duration_sd)
            # use: participant stealing points
            if participant.stole_point == 1 and len(
                    opponent.defense_blocks) <= 0 < opponent.points:
                """Successful point steal"""
                opponent.points -= 1
                opponent.provoked_animation_timer = opponent_provoked_animation_duration
                participant.stole_point = 0
            else:
                participant.stole_point = 0
            """Opponent's move"""
            # use: opponent choice
            if opponent.choice_cooldown == 0:
                opponent.ai_choose(opponent_aggression)
                opponent.manage_choice_result(
                    choice1_delay_mean, choice1_delay_sd, choice2_delay_mean,
                    choice2_delay_sd, choice3_delay_mean, choice3_delay_sd)
            opponent.manage_choice_timer(tic,
                                         opponent_earned_animation_duration,
                                         opponent_defense_duration_mean,
                                         opponent_defense_duration_sd)
            # use: opponent stole points
            if opponent.stole_point == 1:
                if safe_period <= 0:
                    if len(participant.defense_blocks
                           ) <= 0 < participant.points:
                        participant.points -= 1
                        participant.provoked = 1
                        participant.provoked_total += 1
                        participant.provoked_animation_timer = participant_provoked_animation_timer
                        opponent.stole_point = 0
                    elif participant.points <= 0:
                        opponent.stole_point = 0
                        opponent.choice = 1
                        opponent.choice_cooldown = 1
                        opponent.choice_timer = choice1_delay_mean - choice1_delay_sd
                    else:
                        opponent.stole_point = 0
                else:
                    # opponent.defense_blocks = np.append(opponent.defense_blocks, np.random.normal(opponent_defense_duration_mean, opponent_defense_duration_sd, 1))
                    opponent.stole_point = 0
                    opponent.choice = 1
                    opponent.choice_cooldown = 1
                    opponent.choice_timer = choice1_delay_mean - choice1_delay_sd
            """Data Processes"""
            """ObjectPrint content updates"""
            screen_player_points.content = participant.points
            screen_counter.content = participant.count
            screen_opponent_points.content = opponent.points
            """Print Display"""
            print_meters(get_block_quantities(len(participant.defense_blocks)),
                         screen, meter_x, meter_y, block_spacing_x,
                         block_spacing_y, hundreds_block_color,
                         tens_block_color, ones_block_color, block_width,
                         block_height)
            game_screen_display(tic,
                                screen_player_points,
                                screen_opponent_points,
                                opponent,
                                participant,
                                screen_counter,
                                screen_choice_1,
                                screen_choice_2,
                                screen_choice_3,
                                screen_opponent_name,
                                screen_player_name,
                                choice_list,
                                opponent_image_print=True)

            pygame.display.update()
            continue
Ejemplo n.º 25
0
    def __init__(self):

        self.__window = Tk()
        self.__window.title("tic tac toe")
        self.__top = Frame(self.__window)
        self.__middle = Frame(self.__window)
        self.__bottom = Frame(self.__window)
        self.__startframe = Frame(self.__window)
        self.__top.pack()
        self.__middle.pack()
        self.__bottom.pack()
        self.__startframe.pack()
        self.__text1 = 'A1'
        self.__text2 = 'A2'
        self.__text3 = 'A3'
        self.__text4 = 'A4'
        self.__text5 = 'A5'
        self.__text6 = 'A6'
        self.__text7 = 'A7'
        self.__text8 = 'A8'
        self.__text9 = 'A9'
        self.__text_list = [
            self.__text1, self.__text2, self.__text3, self.__text4,
            self.__text5, self.__text6, self.__text7, self.__text8,
            self.__text9
        ]
        self.__font = font.Font(family="Comic Sans MS", size=15,
                                weight='bold')  #bg = "PeachPuff")
        self.__x_image = PhotoImage(file='x_image.gif')
        self.__o_image = PhotoImage(file='o_image.gif')
        self.player = Player()
        self.board = Board()


        self.__button1 = Button(self.__top, text = self.__text1,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(1,self.__text1))
        self.__button1.config(width=bwidth, height=bheight, bg='white')
        self.__button1.pack(side='left')
        self.__button2 = Button(self.__top, text = self.__text2,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(2,self.__text2))
        self.__button2.config(width=bwidth, height=bheight, bg='white')
        self.__button2.pack(side='left')
        self.__button3 = Button(self.__top, text = self.__text3, font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(3,self.__text3))
        self.__button3.config(width=bwidth, height=bheight, bg='white')
        self.__button3.pack(side='left')
        self.__button4 = Button(self.__middle, text = self.__text4,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(4,self.__text4))
        self.__button4.config(width=bwidth, height=bheight, bg='white')
        self.__button4.pack(side='left')
        self.__button5 = Button(self.__middle, text = self.__text5,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(5,self.__text5))
        self.__button5.config(width=bwidth, height=bheight, bg='white')
        self.__button5.pack(side='left')
        self.__button6 = Button(self.__middle, text = self.__text6,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(6,self.__text6))
        self.__button6.config(width=bwidth, height=bheight, bg='white')
        self.__button6.pack(side='left')
        self.__button7 = Button(self.__bottom, text = self.__text7,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(7,self.__text7))
        self.__button7.config(width=bwidth, height=bheight, bg='white')
        self.__button7.pack(side='left')
        self.__button8 = Button(self.__bottom, text = self.__text8,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(8,self.__text8))
        self.__button8.config(width=bwidth, height=bheight, bg='white')
        self.__button8.pack(side='left')
        self.__button9 = Button(self.__bottom, text = self.__text9,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(9,self.__text9))
        self.__button9.config(width=bwidth, height=bheight, bg='white')
        self.__button9.pack(side='left')

        self.__button_list = [
            self.__button1, self.__button2, self.__button3, self.__button4,
            self.__button5, self.__button6, self.__button7, self.__button8,
            self.__button9
        ]

        #Start game button
        self.__start_game_text = StringVar()
        self.__start_game_text.set('Start Game')
        self.__start_game_button = Button(self.__startframe, text = self.__start_game_text.get(),\
                                          command = self.start_game)

        #Reset game button
        self.__reset_game_text = StringVar()
        self.__reset_game_text.set('Reset Game')
        self.__reset_game_button = Button(self.__startframe, text = self.__reset_game_text.get(),\
                                          command = self.reset_game)
        #Graph button
        self.__graph_wins_button = Button(self.__startframe,
                                          text='Graph',
                                          command=self.graph_wins)

        #X wins labels
        self.__x_win_label = Label(self.__startframe, text='X: ')
        self.__num_x_wins = IntVar()
        self.__num_x_wins.set(self.player.get_x_wins())
        self.__x_win = Label(self.__startframe, textvariable=self.__num_x_wins)
        #O wins labels
        self.__num_o_wins = IntVar()
        self.__num_o_wins.set(self.player.get_o_wins())
        self.__o_win_label = Label(self.__startframe, text='O: ')
        self.__o_win = Label(self.__startframe, textvariable=self.__num_o_wins)
        #Ties labels
        self.__num_ties = IntVar()
        self.__num_ties.set(self.player.get_ties())
        self.__num_ties_label = Label(self.__startframe, text='Tie: ')
        self.__ties = Label(self.__startframe, textvariable=self.__num_ties)
        #Pack start,end,graph buttons and x,o,ties labels
        self.__start_game_button.pack(side='left')
        self.__reset_game_button.pack(side='left')
        self.__graph_wins_button.pack(side='left')
        self.__x_win_label.pack(side='left')
        self.__x_win.pack(side='left')
        self.__o_win_label.pack(side='left')
        self.__o_win.pack(side='left')
        self.__num_ties_label.pack(side='left')
        self.__ties.pack(side='left')
        self.__window.mainloop()
Ejemplo n.º 26
0
class App:
    def __init__(self):
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.clock = pygame.time.Clock()
        self.running = True
        self.state = 'start'
        self.cell_width = MAZE_WIDTH // COLS
        self.cell_height = MAZE_HEIGHT // ROWS
        self.walls = []
        self.coins = []
        self.enemies = []
        self.e_pos = []
        self.p_pos = None
        self.highscore = 0
        self.load()

        self.player = Player(self, vec(self.p_pos))

        self.make_enemies()

    def run(self):
        while self.running:
            if self.state == 'start':
                self.start_events()
                self.start_update()
                self.start_draw()
            elif self.state == 'playing':
                self.playing_events()
                self.playing_update()
                self.playing_draw()
            elif self.state == 'game over':
                self.game_over_events()
                self.game_over_update()
                self.game_over_draw()
            elif self.state == 'winner':
                self.winner_events()
                self.winner_update()
                self.winner_draw()
            else:
                self.running = False
            self.clock.tick(FPS)
        pygame.quit()
        try:
            sys.exit()
        except:
            print("Game over, bye")

################### HELPER FUNCTIONS #####################

    def draw_text(self,
                  words,
                  screen,
                  pos,
                  size,
                  color,
                  font_name,
                  centered=False):
        font = pygame.font.SysFont(font_name, size)
        text = font.render(words, False, color)
        text_size = text.get_size()
        if centered:
            pos[0] = pos[0] - text_size[0] // 2
            pos[1] = pos[1] - text_size[1] // 2
        screen.blit(text, pos)

    def load(self):
        self.background = pygame.image.load('maze.png')
        self.background = pygame.transform.scale(self.background,
                                                 (MAZE_WIDTH, MAZE_HEIGHT))

        # Opening walls file
        # Creating walls list with co-ords of walls
        with open("walls.txt", mode='r') as file:
            for yidx, line in enumerate(file):
                for xidx, char in enumerate(line):
                    if char == "1":
                        self.walls.append(vec(xidx, yidx))
                    elif char == "C":
                        self.coins.append(vec(xidx, yidx))
                    elif char == "P":
                        self.p_pos = [xidx, yidx]
                    elif char in ["2", "3", "4", "5", "6", "7"]:
                        self.e_pos.append([xidx, yidx])
                    elif char == "B":
                        pygame.draw.rect(
                            self.background, BLACK,
                            (xidx * self.cell_width, yidx * self.cell_height,
                             self.cell_width, self.cell_height))
        #print(self.walls)

        # read Highscore from highscore.txt
        with open("highscore.txt", mode='r') as highscore_file:
            for line in highscore_file:
                name, var = line.partition("=")[::2]
                self.highscore = int(var)

    def make_enemies(self):
        for idx, pos in enumerate(self.e_pos):
            self.enemies.append(Enemy(self, vec(pos), idx))

    def draw_grid(self):
        for x in range(WIDTH // self.cell_width):
            pygame.draw.line(self.background, GREY, (x * self.cell_width, 0),
                             (x * self.cell_width, HEIGHT))
        for x in range(HEIGHT // self.cell_height):
            pygame.draw.line(self.background, GREY, (0, x * self.cell_height),
                             (WIDTH, x * self.cell_height))

        # Shows wall as rectangles
        # for wall in self.walls:
        # pygame.draw.rect(self.background, (112,55,163), (wall.x*self.cell_width, wall.y*self.cell_height, self.cell_width, self.cell_width))

        # for coin in self.coins:
        #     pygame.draw.rect(self.background, (167, 179, 34), (coin.x*self.cell_width, coin.y*self.cell_height, self.cell_width, self.cell_width))

    def reset(self):
        self.player.lives = 3
        self.player.current_score = 0
        self.player.grid_pos = vec(self.player.starting_pos)
        self.player.pix_pos = self.player.get_pix_pos()
        self.player.direction *= 0
        for enemy in self.enemies:
            enemy.grid_pos = vec(enemy.starting_pos)
            enemy.pix_pos = enemy.get_pix_pos()
            enemy.direction *= 0
        self.coins = []
        with open("walls.txt", mode='r') as file:
            for yidx, line in enumerate(file):
                for xidx, char in enumerate(line):
                    if char == 'C':
                        self.coins.append(vec(xidx, yidx))
        self.state = "playing"

################### INIT FUNCTIONS #####################

    def start_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.state = 'playing'

    def start_update(self):
        pass

    def start_draw(self):
        self.screen.fill(BLACK)
        self.draw_text('PUSH SPACE BAR',
                       self.screen, [WIDTH // 2, HEIGHT // 2 - 50],
                       START_TEXT_SIZE, (170, 132, 58),
                       START_FONT,
                       centered=True)
        self.draw_text('1 PLAYER ONLY',
                       self.screen, [WIDTH // 2, HEIGHT // 2 + 50],
                       START_TEXT_SIZE, (44, 167, 198),
                       START_FONT,
                       centered=True)
        # self.draw_text('HIGH SCORE', self.screen, [4,0],
        #START_TEXT_SIZE, (255, 255, 255), START_FONT)
        pygame.display.update()

################### PLAYING FUNCTIONS #####################

    def playing_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.player.move(vec(-1, 0))
                if event.key == pygame.K_RIGHT:
                    self.player.move(vec(1, 0))
                if event.key == pygame.K_UP:
                    self.player.move(vec(0, -1))
                if event.key == pygame.K_DOWN:
                    self.player.move(vec(0, 1))

    def playing_update(self):
        self.player.update()
        for enemy in self.enemies:
            enemy.update()

        for enemy in self.enemies:
            if enemy.grid_pos == self.player.grid_pos:
                self.remove_life()

        if self.player.current_score == 287:
            if self.highscore < self.player.current_score:
                self.write_highscore(self.player.current_score)
            self.state = "winner"

    def write_highscore(self, new_highscore):
        with open("highscore.txt", "a+") as highscore_file:
            line = highscore_file.readline()
            highscore_file.truncate(0)
            self.highscore = new_highscore
            highscore_file.write('highscore={}'.format(self.highscore))
            highscore_file.close()

    def playing_draw(self):
        self.screen.fill(BLACK)
        self.screen.blit(self.background,
                         (TOP_BOTTOM_BUFFER // 2, TOP_BOTTOM_BUFFER // 2))
        self.draw_grid()
        self.draw_coins()
        self.draw_text('CURRENT SCORE: {}'.format(self.player.current_score),
                       self.screen, [70, 5], 30, WHITE, START_FONT)
        self.draw_text('HIGH SCORE: {}'.format(self.highscore), self.screen,
                       [WIDTH // 2 + 60, 5], 30, WHITE, START_FONT)
        self.player.draw()
        for enemy in self.enemies:
            enemy.draw()
        pygame.display.update()

    def remove_life(self):
        self.player.lives -= 1
        if self.player.lives == 0:
            # if self.highscore < self.player.current_score:
            #     self.highscore = self.player.current_score
            self.state = "game over"
        else:
            self.player.grid_pos = vec(self.player.starting_pos)
            self.player.pix_pos = self.player.get_pix_pos()
            self.player.direction *= 0
            for enemy in self.enemies:
                enemy.grid_pos = vec(enemy.starting_pos)
                enemy.pix_pos = enemy.get_pix_pos()
                enemy.direction *= 0

    def draw_coins(self):
        for coin in self.coins:
            pygame.draw.circle(
                self.screen, (124, 123, 7),
                (int(coin.x * self.cell_height) + self.cell_width // 2 +
                 TOP_BOTTOM_BUFFER // 2, int(coin.y * self.cell_height) +
                 self.cell_width // 2 + TOP_BOTTOM_BUFFER // 2), 5)

################### GAME OVER FUNCTIONS #####################

    def game_over_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.reset()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.state = False

    def game_over_update(self):
        pass

    def game_over_draw(self):
        self.screen.fill(BLACK)
        again_text = "Press SPACE bar to PLAY AGAIN"
        quit_text = "Press the escape button to QUIT"
        self.draw_text("GAME OVER",
                       self.screen, [WIDTH // 2, 100],
                       36,
                       RED,
                       "arial",
                       centered=True)

        if self.highscore < self.player.current_score:
            self.write_highscore(self.player.current_score)
            highscore_text = "New Highscore is {}".format(self.highscore)
        else:
            highscore_text = "Highscore is {}".format(self.highscore)
        self.draw_text(highscore_text,
                       self.screen, [WIDTH // 2, 150],
                       36,
                       YELLOW,
                       "arial",
                       centered=True)
        self.draw_text(again_text,
                       self.screen, [WIDTH // 2, HEIGHT // 2],
                       36, (190, 190, 190),
                       "arial",
                       centered=True)
        self.draw_text(quit_text,
                       self.screen, [WIDTH // 2, HEIGHT // 1.5],
                       36, (190, 190, 190),
                       "arial",
                       centered=True)
        pygame.display.update()

##################### WINNER FUNCTIONS #####################

    def winner_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.reset()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.state = False

    def winner_update(self):
        pass

    def winner_draw(self):
        self.screen.fill(BLACK)
        again_text = "Press SPACE bar to PLAY AGAIN"
        quit_text = "Press the escape button to QUIT"
        winner_text = "YOU ARE A WINNER WITH {} POINTS".format(
            self.player.current_score)
        highscore_text = "Highscore is {} points!".format(self.highscore)
        self.draw_text(winner_text,
                       self.screen, [WIDTH // 2, 100],
                       36,
                       YELLOW,
                       "arial",
                       centered=True)
        self.draw_text(highscore_text,
                       self.screen, [WIDTH // 2, 150],
                       36,
                       YELLOW,
                       "arial",
                       centered=True)
        self.draw_text(again_text,
                       self.screen, [WIDTH // 2, HEIGHT // 2],
                       36, (190, 190, 190),
                       "arial",
                       centered=True)
        self.draw_text(quit_text,
                       self.screen, [WIDTH // 2, HEIGHT // 1.5],
                       36, (190, 190, 190),
                       "arial",
                       centered=True)
        pygame.display.update()
Ejemplo n.º 27
0
def main():

    pygame.init()

    winner = ""

    blue_player = Player(530, 200, COWBOY_WIDTH, COWBOY_HEIGHT, LIMIT_BULLETS,
                         BULLET_VEL)
    red_player = Player(130, 200, COWBOY_WIDTH, COWBOY_HEIGHT, LIMIT_BULLETS,
                        BULLET_VEL)

    obsta = Obstacles(LIMIT_OBSTACLES, OBSTACLE_WIDTH, OBSTACLE_HEIGHT,
                      OBSTACLES_VEL, LEFT_OBSTACLES_LIMIT,
                      RIGHT_OBSTACLES_LIMIT, HEIGHT)

    clock = pygame.time.Clock()
    pygame.time.set_timer(OBSTACLE_TIME_EVENT, 800)
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

            if event.type == pygame.KEYDOWN and pygame.time.get_ticks() > 6000:
                red_player.create_bullets(event, pygame.K_q)
                blue_player.create_bullets(event, pygame.K_RCTRL, COWBOY_WIDTH)

            red_player.handle_health(event, RED_HIT)
            blue_player.handle_health(event, BLUE_HIT)

            obsta.create_obstacles(event, OBSTACLE_TIME_EVENT)

        if red_player.health <= 0:
            winner = "Blue Wins!!"
        if blue_player.health <= 0:
            winner = "Red Wins!!"
        if winner != "":
            draw_win(winner)
            break

        keys_pressed = pygame.key.get_pressed()
        red_handle_movement(keys_pressed, red_player)
        blue_handle_movement(keys_pressed, blue_player)
        obsta.handle_obstacles_movement()

        red_player.handle_bullets_impact(blue_player, obsta, RED_HIT, BLUE_HIT,
                                         WIDTH)

        draw_screen(red_player, blue_player, obsta)

    main()
Ejemplo n.º 28
0
    def run_game(self):
        # pygame config
        pygame.init()
        fpsClock = pygame.time.Clock()
        fpsClock.tick(self.FPS)

        # define keys and user interaction
        from pygame.locals import (
            K_ESCAPE,
            KEYDOWN,
            QUIT,
        )

        #===========================
        # Set up the drawing window
        pygame.display.init()
        screen_dim = [self.SCREEN_WIDTH, self.SCREEN_HEIGHT]
        screen = pygame.display.set_mode(screen_dim, pygame.FULLSCREEN)
        #DISPLAYSURF = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        screen.fill((0, 0, 0))

        # Create player
        player = Player(self.STIMULUS, screen_dim, self.GAIN)
        position = player.stim_center()
        stim_threshold = position[0] + self.THRESHOLD
        # create inital stimulus
        screen.blit(player.surf, position)

        #-----------------------------------------------------------------------------
        # on soft code of state 1
        #-----------------------------------------------------------------------------
        # present initial stimulus
        self.display_stim_event.wait()
        pygame.display.flip()

        #=========================
        # py game loop
        # loop is running while open loop active
        data_pref = [[0, 0, 0]]
        while self.run_open_loop:
            # Fill the background with white
            screen.fill((0, 0, 0))
            screen.blit(player.surf, position)

            #-------------------------------------------------------------------------
            # on soft code of state 2
            #-------------------------------------------------------------------------
            # read rotary encoder stream
            self.move_stim_event.wait()
            data = rotary_encoder.read_stream()
            running = True
            if len(data) == 0:
                continue
            else:
                pos_change = abs(data[0][2]) - abs(data_pref[0][2])
                #print(f"data-pref: {data_pref[0][2]}  data-now: {data[0][2]} n")
                data_pref = data

                #repositin based on changes
                if data[0][2] < 0:
                    #player.move_left(pos_change)
                    position[0] -= (pos_change * self.GAIN)

                if data[0][2] > 0:
                    #player.move_right(pos_change)
                    position[0] += (pos_change * self.GAIN)
                # # keep on screen
                # if abs(position[0]) >= stim_threshold:
                #     running = False

            pygame.display.update()

        #show stimulus after closed loop period is over until reward gieven
        self.still_show_event.wait()
        screen.fill((0, 0, 0))
        pygame.display.flip()

        fpsClock.tick(self.FPS)
        pygame.quit()
        print("end of game loop")
Ejemplo n.º 29
0
import random
import function as Fun
from player_class import Player
Cards=['A','K','Q']
players=[]
player_num=2
for i in range(player_num):
    player=Player()
    players.append(player)   


SB=1
BB=1


while players[0].stack !=0 and player[1].stack !=0 :
    players[0].stack -=SB
    player[1].stack -=BB
    pot=SB+BB
    for i in range(player_num)
    player[i-1].clear_bet()
    player[i-1].clear_status()
    
    x=random.sample(Cards,2)
    players[0].hand,players[1].hand=Fun.split_list(x,1)    
    print("player1のハンド:"+player[0].hand+" palyer2のハンド:"+player[1].hand)
    
    while players[0].status==1 and players.status[1]==1
        players[0].action=input('player1のアクションを選択してください(0:チェック 1:ベットorレイズ 2:コール 3:フォールド ):')
        while Fun.validate_action(action,player_bet,enemy_bet,player_stack)==False:
            players[0].action=input('player1の正しいアクションを選択してください(0:チェック 1:ベットorレイズ 2:コール 3:フォールド ):')
Ejemplo n.º 30
0
from army_class import Army
from bowman_class import Bowman
from player_class import Player
from scouter_class import Scouter
from swordsman_class import Swordsman

army_red = Army("Red Army", [])
army_black = Army("Red Army", [])

player_one = Player(1000, army_red)
player_two = Player(100, army_black)

bowman_1 = Bowman("Arc smecher")
bowman_2 = Bowman("Arc mai putin smecher")
scouter_1 = Scouter("Papuci")

scouter_1.join(player_one, army_red)
bowman_1.join(player_one, army_red)
bowman_2.join(player_one, army_red)
bowman_1.say_hurray()

scouter_1.inform_army(army_red)

swordman = Swordsman("Sabie de carton")
bowman_3 = Bowman("Elastic")
swordman.say_hurray()

swordman.join(player_two, army_black)
bowman_3.join(player_two, army_black)

army_red.fight(army_black)
Ejemplo n.º 31
0
class tttGUI():
    def __init__(self):

        self.__window = Tk()
        self.__window.title("tic tac toe")
        self.__top = Frame(self.__window)
        self.__middle = Frame(self.__window)
        self.__bottom = Frame(self.__window)
        self.__startframe = Frame(self.__window)
        self.__top.pack()
        self.__middle.pack()
        self.__bottom.pack()
        self.__startframe.pack()
        self.__text1 = 'A1'
        self.__text2 = 'A2'
        self.__text3 = 'A3'
        self.__text4 = 'A4'
        self.__text5 = 'A5'
        self.__text6 = 'A6'
        self.__text7 = 'A7'
        self.__text8 = 'A8'
        self.__text9 = 'A9'
        self.__text_list = [
            self.__text1, self.__text2, self.__text3, self.__text4,
            self.__text5, self.__text6, self.__text7, self.__text8,
            self.__text9
        ]
        self.__font = font.Font(family="Comic Sans MS", size=15,
                                weight='bold')  #bg = "PeachPuff")
        self.__x_image = PhotoImage(file='x_image.gif')
        self.__o_image = PhotoImage(file='o_image.gif')
        self.player = Player()
        self.board = Board()


        self.__button1 = Button(self.__top, text = self.__text1,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(1,self.__text1))
        self.__button1.config(width=bwidth, height=bheight, bg='white')
        self.__button1.pack(side='left')
        self.__button2 = Button(self.__top, text = self.__text2,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(2,self.__text2))
        self.__button2.config(width=bwidth, height=bheight, bg='white')
        self.__button2.pack(side='left')
        self.__button3 = Button(self.__top, text = self.__text3, font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(3,self.__text3))
        self.__button3.config(width=bwidth, height=bheight, bg='white')
        self.__button3.pack(side='left')
        self.__button4 = Button(self.__middle, text = self.__text4,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(4,self.__text4))
        self.__button4.config(width=bwidth, height=bheight, bg='white')
        self.__button4.pack(side='left')
        self.__button5 = Button(self.__middle, text = self.__text5,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(5,self.__text5))
        self.__button5.config(width=bwidth, height=bheight, bg='white')
        self.__button5.pack(side='left')
        self.__button6 = Button(self.__middle, text = self.__text6,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(6,self.__text6))
        self.__button6.config(width=bwidth, height=bheight, bg='white')
        self.__button6.pack(side='left')
        self.__button7 = Button(self.__bottom, text = self.__text7,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(7,self.__text7))
        self.__button7.config(width=bwidth, height=bheight, bg='white')
        self.__button7.pack(side='left')
        self.__button8 = Button(self.__bottom, text = self.__text8,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(8,self.__text8))
        self.__button8.config(width=bwidth, height=bheight, bg='white')
        self.__button8.pack(side='left')
        self.__button9 = Button(self.__bottom, text = self.__text9,font = self.__font, state  = DISABLED, \
                                command=lambda: self.button_click(9,self.__text9))
        self.__button9.config(width=bwidth, height=bheight, bg='white')
        self.__button9.pack(side='left')

        self.__button_list = [
            self.__button1, self.__button2, self.__button3, self.__button4,
            self.__button5, self.__button6, self.__button7, self.__button8,
            self.__button9
        ]

        #Start game button
        self.__start_game_text = StringVar()
        self.__start_game_text.set('Start Game')
        self.__start_game_button = Button(self.__startframe, text = self.__start_game_text.get(),\
                                          command = self.start_game)

        #Reset game button
        self.__reset_game_text = StringVar()
        self.__reset_game_text.set('Reset Game')
        self.__reset_game_button = Button(self.__startframe, text = self.__reset_game_text.get(),\
                                          command = self.reset_game)
        #Graph button
        self.__graph_wins_button = Button(self.__startframe,
                                          text='Graph',
                                          command=self.graph_wins)

        #X wins labels
        self.__x_win_label = Label(self.__startframe, text='X: ')
        self.__num_x_wins = IntVar()
        self.__num_x_wins.set(self.player.get_x_wins())
        self.__x_win = Label(self.__startframe, textvariable=self.__num_x_wins)
        #O wins labels
        self.__num_o_wins = IntVar()
        self.__num_o_wins.set(self.player.get_o_wins())
        self.__o_win_label = Label(self.__startframe, text='O: ')
        self.__o_win = Label(self.__startframe, textvariable=self.__num_o_wins)
        #Ties labels
        self.__num_ties = IntVar()
        self.__num_ties.set(self.player.get_ties())
        self.__num_ties_label = Label(self.__startframe, text='Tie: ')
        self.__ties = Label(self.__startframe, textvariable=self.__num_ties)
        #Pack start,end,graph buttons and x,o,ties labels
        self.__start_game_button.pack(side='left')
        self.__reset_game_button.pack(side='left')
        self.__graph_wins_button.pack(side='left')
        self.__x_win_label.pack(side='left')
        self.__x_win.pack(side='left')
        self.__o_win_label.pack(side='left')
        self.__o_win.pack(side='left')
        self.__num_ties_label.pack(side='left')
        self.__ties.pack(side='left')
        self.__window.mainloop()

    #Update the number of wins x has
    #Invokes set()
    def update_x_wins(self):
        self.__num_x_wins.set(self.player.get_x_wins())

    def update_o_wins(self):
        self.__num_o_wins.set(self.player.get_o_wins())

    def update_ties(self):
        self.__num_ties.set(self.player.get_ties())

    def start_game(self):
        for button in self.__button_list:
            button.config(state=NORMAL)

    def reset_game(self):
        i = 0
        for button in self.__button_list:
            button.config(state=DISABLED, text=self.__text_list[i])
            i += 1
        self.board.reset()
        self.player.reset()
        self.update_x_wins()
        self.update_o_wins()

    #Responsible for all button functions
    def button_click(self, button_id, text):
        self.player.inc_turn()
        team = self.player.set_team()
        if team == 'X':
            self.board.add_x(button_id)
            if button_id == 1:
                self.__button1.config(state=DISABLED,
                                      text=team)  #image=self.__x_image)
            elif button_id == 2:
                self.__button2.config(state=DISABLED, text=team)
            elif button_id == 3:
                self.__button3.config(state=DISABLED, text=team)
            elif button_id == 4:
                self.__button4.config(state=DISABLED, text=team)
            elif button_id == 5:
                self.__button5.config(state=DISABLED, text=team)
            elif button_id == 6:
                self.__button6.config(state=DISABLED, text=team)
            elif button_id == 7:
                self.__button7.config(state=DISABLED, text=team)
            elif button_id == 8:
                self.__button8.config(state=DISABLED, text=team)
            elif button_id == 9:
                self.__button9.config(state=DISABLED, text=team)
        else:
            self.board.add_o(button_id)
            if button_id == 1:
                self.__button1.config(state=DISABLED, text=team)
            elif button_id == 2:
                self.__button2.config(state=DISABLED, text=team)
            elif button_id == 3:
                self.__button3.config(state=DISABLED, text=team)
            elif button_id == 4:
                self.__button4.config(state=DISABLED, text=team)
            elif button_id == 5:
                self.__button5.config(state=DISABLED, text=team)
            elif button_id == 6:
                self.__button6.config(state=DISABLED, text=team)
            elif button_id == 7:
                self.__button7.config(state=DISABLED, text=team)
            elif button_id == 8:
                self.__button8.config(state=DISABLED, text=team)
            elif button_id == 9:
                self.__button9.config(state=DISABLED, text=team)
        if self.board.check_for_wins():
            #DISABLE BUTTONS
            if self.board.x_wins():
                message = "X wins!"
                self.player.inc_x_wins()
                self.update_x_wins()
            else:
                message = "O wins!"
                self.player.inc_o_wins()
                self.update_o_wins()
            messagebox.showinfo("Winner!", message)
            self.reset_game()
        elif (not self.board.check_for_wins()) and (self.board.full_board()):
            message = "Tie!"
            self.player.inc_ties()
            messagebox.showinfo("No winner...", message)
            self.reset_game()
            self.update_ties()

    def graph_wins(self):
        objects = ('X', 'O', 'Ties')
        y_pos = np.arange(len(objects))
        x = int(self.player.get_x_wins())
        o = int(self.player.get_o_wins())
        ties = int(self.player.get_ties())
        performance = [x, o, ties]
        plt.bar(y_pos, performance, align='center', alpha=1.0)
        plt.xticks(y_pos, objects)
        plt.ylabel('Number of Wins')
        plt.title('Number of X and O Wins')
        plt.show()
Ejemplo n.º 32
0
	def __init__(self, n, c, t, h):
		Player.__init__(self, n, c, t, 0, 0)
		self._house = h
		self._house_rule_name = Dealer.house_rule_names[self.house-1]