def __init__(self):
        '''
        Constructor
        '''
        logging.basicConfig(level=logging.DEBUG)
        self._path = './youtubePlayer.config'
        self._sSection = 'youtubePlayerConfiguration'

        self.configReader = self._getConfigReader()
        self._sAudioFolder = self.configReader.getValue('audioFolder')
        self._sUrlFile = self.configReader.getValue('urlFile')

        sPlayingLoop = self.configReader.getValue('loop')
        bPlayingLoop = sPlayingLoop in listTrueValues

        sPlayingRandom = self.configReader.getValue('random')
        bPlayingRandom = sPlayingRandom in listTrueValues

        self.listUrl = self._getListUrlFromDisk(self._sUrlFile)

        self.listUrl = self._parseListUrl(self.listUrl)

        self.bIsPlaying = False
        self._player = Player(isPlayInLoop=bPlayingLoop,
                              isPlayRandom=bPlayingRandom)

        #self._iChunk= 1024

        threadDownloader = ThreadDownloader(self.listUrl, self._sAudioFolder,
                                            self.initPlayingMedia,
                                            self._player.addPlayable,
                                            self._writeListUrlInDisk)
        threadDownloader.start()
Exemple #2
0
 def create_player(self, player_name):
     """
     Creates a player and adds him to the player dict
     :param player_name: str 
     """
     _player = Player(player_name)
     self.players[_player.get_id()] = _player
     return _player.get_id()
Exemple #3
0
def draw_asteroids():
    for asteroid in asteroids:
        global invincible_timer
        # CollisionDetector.draw_circle_collider(Screen.screen, asteroid)
        if invincible_timer == 0:
            if CollisionDetector.circle_collision(Player, asteroid):
                global hit
                global hit_cooldown
                global lives

                if not hit:
                    hit_cooldown = 60
                    lives -= 1
                    if asteroid.size != 3:
                        asteroids.append(
                            Asteroid((asteroid.x, asteroid.y),
                                     asteroid.size + 1))
                        asteroids.append(
                            Asteroid((asteroid.x, asteroid.y),
                                     asteroid.size + 1))
                    global score
                    asteroids.remove(asteroid)

                hit = True
                invincible_timer = hit_cooldown + 200
                if lives == 0:
                    # Player hit asteroid
                    print("You died, press 'r' to restart")
                    global dead
                    dead = True
                    break
                else:
                    global respawn_timer
                    Player.reset()
                    respawn_timer = respawn_time

        for bullet in Player.bullets:
            if CollisionDetector.circle_collision(bullet, asteroid):
                # Bullet hit asteroid
                if asteroid.size != 3:
                    asteroids.append(
                        Asteroid((asteroid.x, asteroid.y), asteroid.size + 1))
                    asteroids.append(
                        Asteroid((asteroid.x, asteroid.y), asteroid.size + 1))
                global score
                score += asteroid.size * 10
                asteroids.remove(asteroid)
                Player.bullets.remove(bullet)
                break

        asteroid.draw(Screen.screen)
    global timer
    if len(asteroids) == 0 and timer > game_start_time:
        parameters.starting_asteroid_count += 4
        global current_level
        current_level += 1
        timer = 0
Exemple #4
0
    def __init__(self):
        self.screen = pg.display.set_mode(screen)
        self.timer = pg.time.Clock()

        pg.display.set_caption('Super Mario Bros 2018')
        pg.display.set_icon(pg.image.load(r'lib\img\icon.png').convert_alpha())

        self.world = World()
        self.player = Player(hp=100, spawn_coords=(192, WINDOW_HEIGHT - 32))
        self.camera = Camera(len(self.world.level[0]) * 32, len(self.world.level) * 31)
        self.debugTable = DebugTable()
        self.sound = Sound()

        self.running = True
Exemple #5
0
    def setUp(self):

        # self.board = Board()
        # self.board.buildCells(["H", "E"])
        # # self.cell = self.board.ds["0"]
        self.cell = {'classify': 'H', 'ownedby': 'Bank'}
        self.player1 = Player("Player-1", 1000)
        self.player2 = Player("Player-2", 1000)

        self.all_players = dict()
        self.all_players["Player-1"] = self.player1
        self.all_players["Player-2"] = self.player2

        self.bank = Banker()
        self.player_in_hotel = PlayerInHotel()
Exemple #6
0
    def create_players(self) -> None:
        """ check the names fields, open the game screen """

        players = {}

        if self.names_screen.player_colors == []:
            for i in range(len(self.names_screen.player_names)):
                self.names_screen.player_colors.append("#FFFFFF")

        for player, color in zip(self.names_screen.player_names,
                                 self.names_screen.player_colors):
            name = player.text().strip()

            if name == "":
                error = QErrorMessage()
                error.showMessage("Please give all players names")
                error.exec_()
                return
            else:
                names = [player.get_name() for player in players]

                if name in names:
                    error = QErrorMessage()
                    error.showMessage("2 players can't have the same name")
                    error.exec_()
                    return

            players[Player(name)] = color

        self.game = Monopoly(players, self.debug)
        self.central_widget.addWidget(self.game)
        self.central_widget.setCurrentWidget(self.game)
    def __init__(self, list_of_cells: list, dice: list, player_count: int):
        if not isinstance(player_count, int):
            raise TypeError("{}, Player Count should be integer".format(
                self.__class__))

        if player_count < 2:
            raise ValueError(
                "{}, Player Count should be greater than 2".format(
                    self.__class__))

        if len(dice) > (self.MAX_ROUNDS * player_count):
            raise ValueError("{}, Game cannot be more than 10 rounds".format(
                self.__class__))

        self.list_of_cells = list_of_cells
        self.dice = dice
        self.player_count = player_count

        self.bank = Banker()
        self.bank.cash = self.Initial_Money_Bank
        bank_debit = BankerDebit()

        self.board = Board()
        self.board.buildCells(list_of_cells)

        for p in range(player_count):
            player_name = "Player-" + str(p + 1)
            bank_debit(self.bank, self.Initial_Money_Player)
            self.players[player_name] = Player(player_name,
                                               self.Initial_Money_Player)
Exemple #8
0
    def loadData(self, data):  #load data from protobuf obj
        newGameState = data
        plyList = []
        for ply in newGameState.Players:  #go through all players and add them
            aPlayer = Player(ply.playerName, ply.colour, ply.unitsFree)
            plyList.append(aPlayer)

        #self.__init__(newGameState.mapdir,newGameState.sizex,newGameState.sizey,plyList,False)

        self.mapdir = newGameState.mapdir  #map size and currents player stuff
        self.totxsize = newGameState.sizex
        self.totysize = newGameState.sizey
        self.CurrPlayerTurn = newGameState.currentPlayerIndex

        self.amtOfPlayers = len(plyList)  ###RECREATING IMPORTANT OBJECTS below
        self.done = False
        self.Players = plyList
        self.INFBar = InfoBar(self.Players)

        self.CurrPlayer = self.Players[self.CurrPlayerTurn]
        self.myStatBar = StatBar(self.CurrPlayer)
        self.ghTextManager = ghostTextManager()
        self.loadMap()

        for x in range(0, len(plyList)):  ###setting regions correctly
            for y in range(0, len(newGameState.Players[x].regionsIndex)):
                currentReg = self.Regions[
                    newGameState.Players[x].regionsIndex[y]]
                plyList[x].ownedLand.append(currentReg)
                currentReg.SetOwner(plyList[x])
                currentReg.setUnit(newGameState.Players[x].unitsIndex[y])

        self.CurrPlayer.Phase = newGameState.currentPlayerPhase
Exemple #9
0
def CreatePlayers(amt):
    playerList = []
    for _ in range(0, amt):
        colour = (random.randint(0, 255), random.randint(0, 255),
                  random.randint(0, 255))
        newPlayer = Player("Player " + str(_), colour, 100)
        playerList.append(newPlayer)
    return playerList
Exemple #10
0
 def start(self):
     self.start_time = time.time()
     pygame.init()
     pygame.mouse.set_visible(False)
     pygame.key.set_repeat(True)
     self.display_info = pygame.display.Info()
     self.screen = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT))
     # pylint: disable=I0011,E1121
     self.background = pygame.Surface(self.screen.get_size()).convert()
     self.background.fill(BACKGROUND_COLOR)
     # pylint: disable=I0011,I0012; enable=E1121
     self.font_mgr = FontManager()
     self.size = Vector(self.screen.get_size()[0], self.screen.get_size()[1])
     self.clock = pygame.time.Clock()
     self.player = Player(self.size.div(2))
     self.spawn_enemy()
     self.loop()
     pygame.quit()
Exemple #11
0
 def reset(
     self, amtPl
 ):  #reset for new game (resets defualt values and creates some temp players)
     playerList = []
     for x in range(0, amtPl):
         colour = (random.randint(0, 255), random.randint(0, 255),
                   random.randint(0, 255))
         newPlayer = Player("Player " + str(x + 1), colour, 100)
         playerList.append(newPlayer)
     self.amtOfPlayers = amtPl
     self.done = False
     self.multiplayer = False
     self.Regions = []
     self.Players = playerList
     self.INFBar = InfoBar(self.Players)
     self.CurrPlayerTurn = 0
     self.CurrPlayer = self.Players[self.CurrPlayerTurn]
     self.myStatBar = StatBar(self.CurrPlayer)
Exemple #12
0
from config import *
from lib.Player import Player
from lib.GameMap import GameMap

pygame.init()

# Set up window & FPS clock
clock = pygame.time.Clock()

pygame.display.set_caption("wumpus game")
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

# Create objects and changed_rects
changed_rects = []
player = Player((WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2))

background = pygame.image.load('assets/grokwallpaper.png').convert()
changed_rects.append(window.blit(background, background.get_rect()))

# Initialize map
map = GameMap()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            break

    # Level Handling
Exemple #13
0
class Game(object):
    def __init__(self):
        self.coords = []
        self.player = None
        self.enemies = []
        self.last_spawn_time = 0
        self.start_time = 0
        self.score = 0
        self.screen = None
        self.display_info = None
        self.clock = None
        self.font_mgr = None
        self.is_ended = False
        self.should_stop = False
        self.size = None
        self.background = None

    def start(self):
        self.start_time = time.time()
        pygame.init()
        pygame.mouse.set_visible(False)
        pygame.key.set_repeat(True)
        self.display_info = pygame.display.Info()
        self.screen = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT))
        # pylint: disable=I0011,E1121
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.background.fill(BACKGROUND_COLOR)
        # pylint: disable=I0011,I0012; enable=E1121
        self.font_mgr = FontManager()
        self.size = Vector(self.screen.get_size()[0], self.screen.get_size()[1])
        self.clock = pygame.time.Clock()
        self.player = Player(self.size.div(2))
        self.spawn_enemy()
        self.loop()
        pygame.quit()

    def loop(self):
        while not self.should_stop:
            self.clock.tick(60)
            self.render()
            pygame.display.flip()
            self.update()
            for event in pygame.event.get():
                if event.type == Pygame.QUIT:
                    self.should_stop = True

    def render(self):
        self.screen.blit(self.background, (0, 0))
        if self.is_ended:
            self.draw_text(FONT_END, "You have lost!", Vector(0, 256), COLOR_BLUE)
            return
        now = time.time()
        for enemy in self.enemies:
            enemy.render(self)
        self.player.render(self.screen)
        acceleration_text = "Acceleration: {}".format(self.player.velocity)
        position_text = "Position: {}".format(self.player.pos)
        score_text = "Score: {}".format(self.score)
        hps_text = "Hits / Second: {}".format(str(self.score / (now - self.start_time))[0:6])
        end_text = "Press X to end the game."
        self.draw_text(FONT_NORMAL, acceleration_text, Vector(0, 0), COLOR_WHITE)
        self.draw_text(FONT_NORMAL, position_text, Vector(0, 16), COLOR_WHITE)
        self.draw_text(FONT_NORMAL, score_text, Vector(0, 32), COLOR_WHITE)
        self.draw_text(FONT_NORMAL, hps_text, Vector(0, 48), COLOR_WHITE)
        self.draw_text(FONT_NORMAL, end_text, Vector(0, 64), COLOR_WHITE)

    def update(self):
        now = time.time()
        if now - self.last_spawn_time > 0.5 and len(self.enemies) < MAX_ENEMY_COUNT:
            self.spawn_enemy()
        keys = pygame.key.get_pressed()
        if keys[Pygame.K_ESCAPE]:
            self.end()
            return
        if keys[Pygame.K_r] or keys[Pygame.K_z] or keys[Pygame.K_b]:
            self.player.is_bot = True
        self.player.update(self)
        for index in range(0, len(self.enemies)):
            if self.player.collides(self.enemies[index]):
                if self.player.target is not None and index < self.player.target:
                    self.player.target -= 1
                if self.enemies[index].is_target:
                    self.player.is_target_destroyed = True
                self.enemies.pop(index)
                self.score += 1
                break
            time_since_creation = now - self.enemies[index].creation_time
            if time_since_creation > TIME_TO_LOSE:
                self.end()
                return

    def end(self):
        print("ended: {}".format(self.score))

    def draw_text(self, size, text, pos, color):
        rendered = self.font_mgr.get(size).render(text, True, color)
        self.screen.blit(rendered, (pos.x, pos.y))

    def spawn_enemy(self):
        size = Vector(ENTITY_SIZE)
        pos = Vector.rand(size, self.size.sub(ENTITY_SIZE))
        enemy = Enemy(pos)
        self.enemies.append(enemy)
        self.last_spawn_time = time.time()
Exemple #14
0
class Main(object):
    def __init__(self):
        self.screen = pg.display.set_mode(screen)
        self.timer = pg.time.Clock()

        pg.display.set_caption('Super Mario Bros 2018')
        pg.display.set_icon(pg.image.load(r'lib\img\icon.png').convert_alpha())

        self.world = World()
        self.player = Player(hp=100, spawn_coords=(192, WINDOW_HEIGHT - 32))
        self.camera = Camera(len(self.world.level[0]) * 32, len(self.world.level) * 31)
        self.debugTable = DebugTable()
        self.sound = Sound()

        self.running = True

    def run(self):
        while self.running:
            self.handle_events()
            self.handle_moves()
            self.render()
            self.timer.tick(100)

    def change_debug_text(self):
        if self.debugTable.mode == 2:
            self.debugTable.text = [
                'Mario 2018 ' + VERSION + ' (S&D © 2018)',
                'FPS: ' + str(round(self.timer.get_fps())),
                'OnGr: ' + str(self.player.onground),
                'Spd: ' + str(round(self.player.x_vel, 1)) + ' ' + str(round(self.player.y_vel, 1)),
                'Plr: ' + (str(round(self.player.rect[0], 1)) + ' ' +
                           str(round(self.player.rect[1], 1)) + ' ' +
                           str(round((self.player.rect[0] + self.player.rect[2]) / 32)) + ' ' +
                           str(round((self.player.rect[1] + self.player.rect[3]) / 32))) + ' ' +
                STATE_DICT[self.player.state] + ' ' + DIRECTION_DICT[self.player.direction],
                'Cam Rect: ' + str(round(self.camera.state[0], 1)) + ' ' +
                str(round(self.camera.state[1], 1)),
                'W/ Size: ' + str(round(self.camera.state[2] / 32)) + ' ' +
                str(round(self.camera.state[3] / 32)),
                'Obj Rendering: ' + (str(len(self.world.objects) + len(self.world.bg_objects))),
                'Obj Collision: ' + (str(len(self.world.obj_to_collide)))]
        if self.debugTable.mode == 1:
            self.debugTable.text = 'FPS: ' + str(round(self.timer.get_fps()))

    def handle_events(self):
        for e in pg.event.get():
            if e.type == pg.QUIT:
                raise SystemExit('Quit!')
            if e.type == KEYDOWN:
                if e.key == K_RIGHT:
                    self.player.right = 1
                if e.key == K_DOWN:
                    self.player.down = 1
                if e.key == K_LEFT:
                    self.player.left = 1
                if e.key == K_UP:
                    self.player.up = 1
                if e.key == K_F3:
                    if self.debugTable.mode < 2:
                        self.debugTable.mode += 1
                    else:
                        self.debugTable.mode = 0
            if e.type == KEYUP:
                if e.key == K_RIGHT:
                    self.player.right = 0
                if e.key == K_DOWN:
                    self.player.down = 0
                if e.key == K_LEFT:
                    self.player.left = 0
                if e.key == K_UP:
                    self.player.up = 0

    def handle_moves(self):
        self.player.move(self.world.obj_to_collide, self.world)
        self.player.control_image()
        self.camera.update(self.player.rect)

    def render(self):
        self.world.render(self.screen, self.camera)
        self.player.render(self.screen, self.camera)

        if self.debugTable.mode != 0:
            self.change_debug_text()
            self.debugTable.render(self.screen)
        pg.display.update()
Exemple #15
0
    def setUp(self):
        self.bank = Banker()
        self.bank.cash = 1000

        self.player1 = Player("Player-1", 1000)
        self.player_in_lottery = PlayerInLottery()
class YoutubePlayerList(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        logging.basicConfig(level=logging.DEBUG)
        self._path = './youtubePlayer.config'
        self._sSection = 'youtubePlayerConfiguration'

        self.configReader = self._getConfigReader()
        self._sAudioFolder = self.configReader.getValue('audioFolder')
        self._sUrlFile = self.configReader.getValue('urlFile')

        sPlayingLoop = self.configReader.getValue('loop')
        bPlayingLoop = sPlayingLoop in listTrueValues

        sPlayingRandom = self.configReader.getValue('random')
        bPlayingRandom = sPlayingRandom in listTrueValues

        self.listUrl = self._getListUrlFromDisk(self._sUrlFile)

        self.listUrl = self._parseListUrl(self.listUrl)

        self.bIsPlaying = False
        self._player = Player(isPlayInLoop=bPlayingLoop,
                              isPlayRandom=bPlayingRandom)

        #self._iChunk= 1024

        threadDownloader = ThreadDownloader(self.listUrl, self._sAudioFolder,
                                            self.initPlayingMedia,
                                            self._player.addPlayable,
                                            self._writeListUrlInDisk)
        threadDownloader.start()

    def _parseListUrl(self, listUrl):

        listUrlFolder = []
        for sUrl in listUrl:
            listElementsUrl = sUrl.split('--')
            if (len(listElementsUrl) >= 3):
                sPath = listElementsUrl[1]
                isList = 'list' == listElementsUrl[2]
            else:
                sPath = None
                isList = False
            listUrlFolder.append({
                'url': listElementsUrl[0],
                'path': sPath,
                'isList': isList
            })
        return listUrlFolder

    def initPlayingMedia(self):
        if (self._player._playable and not self.bIsPlaying):
            self.bIsPlaying = True
            self._player.play()

    def _genConfigFile(self):
        fConfigFile = open(self._path, 'w')
        fConfigFile.write('[' + self._sSection + ']' + '''
urlFile=./urls.list
audioFolder=./audios
loop=true
random=true''')

        fConfigFile.close()
        fConfigFile = open(self._path, 'r+')
        return fConfigFile

    def _getConfigReader(self):
        fBufferConfig = None
        if os.path.isfile(self._path):
            fBufferConfig = open(self._path, 'r+')
        else:
            fBufferConfig = self._genConfigFile()

        return ConfigReader(fBufferConfig, self._sSection)

    def _getListUrlFromDisk(self, sUrlFile):

        try:
            fUrlFile = open(sUrlFile, 'r')

            listUrlReader = ListReader(fUrlFile)
            return listUrlReader.getAll()

        except (IOError, TypeError):
            logging.warn('Url file did not founded')

            return []

    def _writeListUrlInDisk(self, listUrl):
        try:
            fUrlFile = open(self._sUrlFile, 'w')

            for sUrl in listUrl:
                fUrlFile.write(sUrl + '\n')
            fUrlFile.close()

        except (IOError, TypeError):
            logging.warn('Url file did not founded')
Exemple #17
0
 def setUp(self):
     self.player = Player("alpha", 500)
Exemple #18
0
from lib.Player import Player
from lib.Background import Background
from lib.GameMap import GameMap
from lib.HUD import Minimap, Healthbar, Cards
from lib.Player.Cards import *

pygame.init()

# Set up window & FPS clock
clock = pygame.time.Clock()

pygame.display.set_caption("game")
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

# Create objects
player = Player((WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2))
healthbar = Healthbar(player, center=HEALTHBAR_CENTER)
cards = Cards(player, center=CARDS_CENTER)
background = Background()

# Initialize map
game_map = GameMap(ROOM_NUM)
minimap = Minimap(game_map, center=MINIMAP_CENTER)
minimap.render_minimap(game_map, None)

all_sprites = pygame.sprite.OrderedUpdates(
)  # renders sprites in order of addition
all_sprites.add(background)
all_sprites.add(game_map.environmental_sprites)
all_sprites.add(player)
all_sprites.add(healthbar)
Exemple #19
0
import Map_pb2
import GameState_pb2
import pygame
import pygame.font
import random
import time
import datetime
import os
import socket
import threading
from lib.Player import Player

testPlayer = Player("Name",
                    (255, 0, 0))  # define a player with name and colour
print(testPlayer)
Exemple #20
0
import pygame.freetype
import time
import random

from lib.Player import Player
from lib.Screen import Screen
from lib.Asteroid import Asteroid
from lib.CollisionDetector import CollisionDetector
from lib import parameters

COLORS_BLACK = (0, 0, 0)

Player = Player()
Screen = Screen()

pygame.init()
pygame.font.init()
info = pygame.freetype.Font(
    '/Users/giantjelly/Library/Fonts/Quicksand-Light.ttf', 30)
title = pygame.freetype.Font(
    '/Users/giantjelly/Library/Fonts/Quicksand-Medium.ttf', 50)

fps = 60
previous = time.time() * 1000
run = True
dead = False
current_level = 1
timer = 0
asteroids = []
level_started = False
spawn_safe_zone_size = 500
Exemple #21
0
 def setUp(self):
     self.bank = Banker()
     self.player1 = Player("Player-1", 1000)
     self.player_in_jail = PlayerInJail()