Ejemplo n.º 1
0
 def __init__(self, width=600, height=400, fps=50, title="Planet Invader"):
     self.width = width
     self.height = height
     self.screen = pygame.display.set_mode((self.width, self.height))
     self.fps = fps
     self.title = title
     self.bgColor = (255, 255, 255)
     pygame.init()
     self.highScore=0
     self.score=0
     self.viewScores=Scores(self.highScore)
     self.scoreList=[]
     self.scoreList=self.viewScores.getScores('scores.txt')
     self.scoreList=self.getNumList(self.scoreList)
     self.highScore=max(self.scoreList)
     self.viewScores.drawList()
     self.intro=Start(self.highScore)
     self.tutorial=Instructions()
     self.gamePlay=Game(self.highScore)
     self.over=GameOver(self.highScore,self.score)
     self.clear=GameClear(self.highScore,self.score)
     self.start=True
     self.play=False
     self.howTo=False
     self.isOver=False
     self.congrats=False
     self.scores=False
     self._keys = dict()
     pygame.mixer.pre_init(44100,16,5,4096)
     pygame.mixer.init()
Ejemplo n.º 2
0
def main():
    data = Scores()  # create Scores object
    gen = data.getOne()  # create generator object
    print(next(gen))  # fetch first data of object
    data.printByLast()  # print all data sorted by last field
    print(next(gen))  # fetch next data of object
    data.printMaxMin()  # print the max and min of the total scores
    print(next(gen))  # fetch next data of object
Ejemplo n.º 3
0
def back_populator():
    # Start date of season
    start_date = datetime.date(2020, 12, 22)
    end_date, _ = get_dates()
    while start_date <= end_date:
        Report().generate_reports(start_date)
        Scores(start_date).poll()
        start_date = start_date + datetime.timedelta(days=1)
Ejemplo n.º 4
0
 def __init__(self, wrapper):
     super(Game, self).__init__(wrapper)
     self.type_scores = {'s': 10, 'e': 50}
     self.field = Field('1_lvl.txt')
     self.units = Units(self)
     self.scores = Scores(position=Vector(
         10,
         self.field.get_size().to_abs().y + 5),
                          level=1)
Ejemplo n.º 5
0
    def draw(self):

        cursor = Scores()
        topten = cursor.get_top_ten_scores()

        background = pygame.image.load("res/background_main.jpg").convert()
        self.screen.blit(background, [0, 0])

        mouse = pygame.mouse.get_pos()
        release = pygame.mouse.get_pressed()
        if (self.width / 2 - 75) < mouse[0] < (self.width / 2 +
                                               75) and 700 < mouse[1] < 750:
            pygame.draw.rect(self.screen, (220, 40, 55),
                             (self.width / 2 - 75, 700, 150, 50))
            if release[0] == 1:
                print 'click'
                return False
        else:
            pygame.draw.rect(self.screen, (163, 40, 55),
                             (self.width / 2 - 75, 700, 150, 50))

        pygame.font.init()
        myfont = pygame.font.SysFont("monospace", 72)
        hslabel = myfont.render("HIGHSCORES", 1, BLACK)
        myfont = pygame.font.SysFont("monospace", 24)
        bcklabel = myfont.render("BACK", 1, (0, 0, 0))
        text_rect = hslabel.get_rect(center=(self.width / 2, 30))

        self.screen.blit(hslabel, text_rect)
        self.screen.blit(bcklabel, (self.width / 2 - 33, 715))

        pygame.draw.line(self.screen, BLACK, (0, 60), (600, 60), 5)

        top = 100
        labels = []
        i = 0
        j = len(topten)
        myfont = pygame.font.SysFont("monospace", 32)
        for record in topten:
            labels.insert(
                i,
                myfont.render(
                    '{0}.{1: <55s}{2: >10s}'.format(
                        i + 1,
                        str(record[1]).strip(),
                        str(record[0]).strip()).replace(" ", "."), 0, BLACK))
            i = i + 1

        for label in labels:
            self.screen.blit(label, (50, top))
            top = top + 35

        pygame.display.flip()

        return True
Ejemplo n.º 6
0
def main():
    s1 = Scores("input1.txt")
    s1.readFile()
    while True:  # CORRECTION: instead while choice != 5:
        menu_options = [
            0, printByTotal, printByLimit, generateCountry, printByFrequency, 5
        ]
        menu_choice = displayMenu()
        if menu_choice == 5:
            break
        menu_options[menu_choice](s1)
Ejemplo n.º 7
0
    def __init__(self):
        self.settings = Settings()
        self.show_scores = False
        self.play_game = False
        self.bg_music.play(99)
        self.elapsed_time = 0
        self.count = 0

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Alien Invasion")

        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.highscores = Scores(self)
        self.scores = []
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()

        self.aliens = pygame.sprite.Group()
        self.aliens2 = pygame.sprite.Group()
        self.aliens3 = pygame.sprite.Group()
        self.ufo_group = pygame.sprite.Group()

        # Images
        self.image = 'images/alien.png'
        self.image2 = 'images/alien2.png'
        self.image3 = 'images/alien3.png'
        self.image4 = 'images/alien4.png'
        self.image5 = 'images/alien5.png'
        self.image6 = 'images/alien6.png'
        self.al_image = pygame.image.load('images/alien.png')
        self.al_image2 = pygame.image.load('images/alien2.png')
        self.al_image3 = pygame.image.load('images/alien3.png')
        self.al_image4 = pygame.image.load('images/alien4.png')
        self.al_image5 = pygame.image.load('images/alien5.png')
        self.al_image6 = pygame.image.load('images/alien6.png')

        self.al_image7 = pygame.image.load('images/ufo.png')
        self.ufo_spawned = False

        self._create_fleet()
        self.load_ufo()

        self.clock = pygame.time.Clock()
        self.fps = 120

        # Buttons
        self.play_button = Button(self, "PLAY", 700, 400)
        self.restart_button = Button(self, "RESTART", 900, 10)
        self.exit_button = Button(self, "EXIT", 1000, 400)
        self.scores_button = Button(self, "SCORES", 850, 500)
        self.back_button = Button(self, "BACK", 100, 200)
Ejemplo n.º 8
0
def main():
    iris_parameters = []
    iris_species = []

    with open('datasets/iris.csv', mode='r') as iris_file:
        irises = list(csv.reader(iris_file))
        rd.shuffle(irises)  # get our lines of data in random order
        for iris in irises:
            parameters = [float(n) for n in iris[0:4]]
            iris_parameters.append(parameters)
            species = iris[4]
            iris_species.append(species)

    iris_parameters = np.array(iris_parameters)
    normalizar(iris_parameters)
    iris_species = np.array(iris_species).reshape(-1, 1)

    print("\nTreinando...\n")

    iris_network = Perceptron(taxa=0.2, ativacao="l_relu", N=[4], debug=1)

    # número de dados de treino
    n_train = 120

    # train over the first 140 irises in the data set 50 times
    x_train = iris_parameters[:n_train]
    y_train = iris_species[:n_train]

    iris_network.treinar(x_train, y_train, M=100)
    y_train_pred = iris_network.prever(x_train)
    scores = Scores(y_train, y_train_pred)
    scores.exibir_grafico()

    # test over the last 10 of the irises in the data set
    x_test = iris_parameters[n_train:]
    y_test = iris_species[n_train:]
    y_test_pred = iris_network.prever(x_test)

    # minha classe geradora da matriz de confusão
    scores = Scores(y_test, y_test_pred)
    scores.exibir_grafico()
Ejemplo n.º 9
0
def main():

    pygame.display.set_caption(TITLE)
    crashed = False

    while not crashed:
        if GAMESTATE.changed():
            if GAMESTATE.get() == 0:
                backgroundGroup = Backgrounds()
                groundGroup = Grounds()
                menuGroup = pygame.sprite.Group(Menu(0))

                GROUPS.add(backgroundGroup, groundGroup, menuGroup)

            elif GAMESTATE.get() == 1:
                birdGroup = Birds()
                backgroundGroup = Backgrounds()
                pipeGroup = Pipes(birdGroup.getBird())
                groundGroup = Grounds()
                scoreGroup = Scores()

                GROUPS.add(backgroundGroup, pipeGroup, groundGroup, birdGroup,
                           scoreGroup)

            elif GAMESTATE.get() == 2:
                menuGroup = pygame.sprite.Group(Menu(1))

                GROUPS.add(menuGroup)
            else:
                crashed = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True
            elif event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:
                if GAMESTATE.get() == 0:
                    GAMESTATE.set(1)
                elif GAMESTATE.get() == 1:
                    birdGroup.getBird().bounce()
                elif GAMESTATE.get() == 2:
                    GAMESTATE.set(0)
                else:
                    crash = True

        GROUPS.update()
        GROUPS.draw(DISPLAY)

        pygame.display.update()
        CLOCK.tick(TICKRATE)

    pygame.quit()
    quit()
Ejemplo n.º 10
0
    def run(self):
        """Compute the statistical significance of a difference between
        the systems via a paired two-sided approximate randomization test.

        Returns:
            An approximation of the probability of observing corpus-wide
            differences in scores at least as extreme as observed here, when
            there is no difference between the systems.
        """

        absolute_difference = math.fabs(
            self.aggregator(self.system1_scores) -
            self.aggregator(self.system2_scores))
        shuffled_was_at_least_as_high = 0

        for i in range(0, self.trials):
            pseudo_system1_scores = Scores()
            pseudo_system2_scores = Scores()

            for score1, score2 in zip(self.system1_scores,
                                      self.system2_scores):
                if random.randint(0, 1) == 0:
                    pseudo_system1_scores.append(score1)
                    pseudo_system2_scores.append(score2)
                else:
                    pseudo_system1_scores.append(score2)
                    pseudo_system2_scores.append(score1)

            pseudo_difference = math.fabs(
                self.aggregator(pseudo_system1_scores) -
                self.aggregator(pseudo_system2_scores))

            if pseudo_difference >= absolute_difference:
                shuffled_was_at_least_as_high += 1

        significance_level = (shuffled_was_at_least_as_high +
                              1) / (self.trials + 1)

        return significance_level
Ejemplo n.º 11
0
    def __init__(self, pacSettings):
        pygame.init()
        self.screen = pygame.display.set_mode(
            (pacSettings.screen_width, pacSettings.screen_height))
        pygame.display.set_caption("Pacman Portal")

        self.player = Player(self.screen, 'images/PacMaze.txt', 'pacman0')

        self.maze = Maze(self.screen, "images/PacMaze.txt", "square")

        self.pellets = Pellets(self.screen, "images/PacMaze.txt", "pellets")

        self.nodes = Nodes(self.screen, "images/PacMaze.txt", "node")

        self.blueGhost = BlueGhost(self.screen, 'images/PacMaze.txt',
                                   'BlueGhost0')

        self.redGhost = RedGhost(self.screen, 'images/PacMaze.txt',
                                 'RedGhost0')

        self.yellowGhost = YellowGhost(self.screen, 'images/PacMaze.txt',
                                       'YellowGhost0')

        self.pinkGhost = PinkGhost(self.screen, 'images/PacMaze.txt',
                                   'PinkGhost0')

        self.stats = GameStats(pacSettings)

        self.playButton = Button(pacSettings, self.screen, "Play")

        self.pac = PacMan(self.screen, "pacman0")

        self.yellow = Yellow(self.screen, 'YellowGhost0')

        self.pink = Pink(self.screen, 'PinkGhost0')

        self.red = Red(self.screen, 'RedGhost0')

        self.blue = Blue(self.screen, "BlueGhost0")

        self.oldHiscore = 0

        self.scores = Scores(pacSettings, self.screen, self.stats)

        fo = open("foo.txt", "r+")
        self.stats.high_score = int(fo.readline())
        fo.close()
        self.oldHiscore = self.stats.high_score
        self.title = Scoreboard(self.screen, "pacmantitle")
Ejemplo n.º 12
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Pong")

    first_time = True
    play_but = Button(screen, 'Play')
    ball = Ball(screen)
    paddles = Group()
    score = Scores(screen)
    func.create_paddles(screen, ball, paddles)

    while True:
        func.check_events(ai_settings, paddles, play_but)
        if ai_settings.game_active:
            paddles.update()
            first_time = False
        func.update_screen(ai_settings, screen, ball, paddles, score, play_but,
                           first_time)
Ejemplo n.º 13
0
# assim o tipo de rede é definido pelo tipo da conexão dos neurônios
# e o mesmo tipo pode ser treinado de formas diferentes, mas 
# mesmo assim usando esse formato de conexão

# "adam" é outro tipo de otimização, diferente do SGD
model.compile(optimizer="adam", loss='sparse_categorical_crossentropy', metrics=['accuracy'])

print("\nTreinando...\n")
model.fit(x_train, y_train, epochs=20)

# avaliando dados de treinamento
print("\navaliando dados de treinamento")
model.evaluate(x_train, y_train, verbose=2)

# avaliando os dados de teste
print("\navaliando os dados de teste")
model.evaluate(x_test, y_test, verbose=2)

# prevendo a partir dos dados de teste
y_train_pred = np.argmax(model.predict(x_train), axis=-1)
y_test_pred = np.argmax(model.predict(x_test), axis=-1)

# usando a minha classe de validação que mostra a matriz de confusão
score_train = Scores(y_train, y_train_pred)
score_train.exibir_grafico("Dados de treino")

score_test = Scores(y_test, y_test_pred)
score_test.exibir_grafico("Dados de teste")

Ejemplo n.º 14
0
def run():
    if with_viewer:
        view = Viewer(config_file)

    loader_test = create_loader(dataset_name, config_file)
    loader_test.start()

    first_time = True
    iter_test_nr = 0  #nr of batches processed
    samples_test_processed = 0

    #torch stuff
    lattice_to_splat = LatticePy()
    lattice_to_splat.create(
        config_file, "splated_lattice"
    )  #IMPORTANT THAT the size of the lattice in this file is the same as the size of the lattice that was used during training
    model_ctx = ModelCtx(base_lr,
                         learning_rate,
                         weight_decay,
                         batch_size,
                         nr_epochs_per_half_cycle,
                         exponential_gamma,
                         model_params,
                         with_debug_output=with_debug_output,
                         with_error_checking=with_error_checking)
    mode = "eval"  #this will switch between train and eval as we finish each epoch

    torch.set_grad_enabled(False)
    scores = Scores(node_name, port)

    write_scannet_predictions = False

    cloud = MeshCore()
    cloud.load_from_file(
        "/home/local/staff/rosu/data/ais_kitchen/kitchen_meshes/kitchen_2105.ply"
    )
    cloud.random_subsample(0.7)
    cloud.rotate_x_axis(1.0)
    cloud.C = cloud.C / 255
    cloud.C = cloud.C + 0.2  # for some reason this yields better results
    # nr_classes=21
    #use the dataloader to get the labelmngr
    while True:
        if (loader_test.has_data()):
            cloud_with_label_mngr = loader_test.get_cloud()
            cloud.m_label_mngr = cloud_with_label_mngr.m_label_mngr
            break

    # for sigma in np.arange(0.04, 0.1, 0.01):
    # lattice_to_splat.lattice.set_sigma(sigma)
    # sigma=0.07
    # lattice_to_splat.lattice.set_sigma(sigma)

    positions, values, target = model_ctx.prepare_cloud(
        cloud
    )  #prepares the cloud for pytorch, returning tensors alredy in cuda
    pred_softmax, pred_raw, delta_weight_error_sum = model_ctx.forward(
        lattice_to_splat, positions, values, mode,
        cloud.m_label_mngr.nr_classes(), 1)

    if first_time:
        first_time = False
        #now that all the parameters are created we can fill them with a model from a file
        model_ctx.model.load_state_dict(torch.load(checkpoint_path))
        #need to rerun forward with the new parameters to get an accurate prediction
        pred_softmax, pred_raw, delta_weight_error_sum = model_ctx.forward(
            lattice_to_splat, positions, values, mode,
            cloud.m_label_mngr.nr_classes(), 1)

    lattice_to_splat.compute_nr_points_per_lattice_vertex()
    print("max color is ", cloud.C.max())

    if with_viewer:
        show_predicted_cloud(pred_softmax, cloud)

    if do_write_predictions:
        pred_path = os.path.join(
            output_predictions_path,
            str(samples_test_processed) + "_2105_pred.ply")
        print("writing prediction to ", pred_path)
        write_prediction(pred_softmax, cloud, pred_path)
Ejemplo n.º 15
0
# _*_ coding: utf-8 _*_

import pygame  # pygame
from var import Var  # for const
from ship import Ship  # ship
from scores import Scores
from sounds import Sounds
import game_functions as gf  # Game functions
from pygame.sprite import Group

pygame.init()
ai_var = Var()
screen = pygame.display.set_mode([ai_var.screen_width, ai_var.screen_height])
pygame.display.set_caption("Alien War")
ship = Ship(screen)
sc = Scores(screen, ai_var)
sd = Sounds()
timer = pygame.time.Clock()
bullets = Group()
aliens = Group()


def main():
    while sc.game_active:  # Game Started
        gf.check_events(ship, ai_var, screen, bullets, sc, sd)  # Check events
        ship.update(ai_var)  # Update the status of the ship
        bullets.update()
        aliens.update(sc)
        gf.update_aliens(aliens, screen, ai_var, bullets, sc, ship, sd)
        gf.remove(bullets, aliens, screen)
        gf.update_screen(ai_var, screen, ship, bullets, aliens,
Ejemplo n.º 16
0
#pygame.init()
#fps = pygame.time.Clock()

#color palette
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
SILVER = (192, 192, 192)
BLUE = (0, 0, 255)
YELLOW = (237, 249, 57)
PURPLE = (189, 26, 221)
GOLD = (206, 184, 136)

CLOCK = pygame.time.Clock()
scoredb = Scores()
#BALL_RADIUS = math.sqrt(WIDTH*HEIGHT)
#PAD_WIDTH = WIDTH/10
#PAD_HEIGHT = HEIGHT/50
#HALF_PAD_WIDTH = PAD_WIDTH/2
#HALF_PAD_HEIGHT = PAD_HEIGHT/2
score = 0
score_multi = 1

#window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#pygame.display.set_caption('Brick Break')


def init(width, height):
    global fps
    global lives
Ejemplo n.º 17
0
 def __init__(self, train, label, extra):
     self.trainSet = train
     self.labelSet = label
     self.scores = Scores()
def train(env, hparams):
    # randomness (https://pytorch.org/docs/stable/notes/randomness.html)

    random_seed = hparams['seed']
    torch.manual_seed(random_seed)
    torch.cuda.manual_seed(random_seed)
    torch.cuda.manual_seed_all(random_seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(random_seed)
    random.seed(random_seed)



    # get the default brain
    brain_name = env.brain_names[0]
    brain = env.brains[brain_name]

    scores_hparams = hparams['scores']
    scores = Scores( scores_hparams['expectation'],size=scores_hparams['window_size'], check_solved=scores_hparams['check_solved']) 

    env_info = env.reset(train_mode=True)[brain_name]     # reset the environment    
    # number of agents
    num_agents = len(env_info.agents)

    # size of each action
    action_size = brain.vector_action_space_size
    states = env_info.vector_observations                  # get the current state (for each agent)
    state_size = states.shape[1]

    
    agents = []
    for _ in range(num_agents):
        agents.append( Agent(state_size, action_size, hparams))
    
    prefix = f'result/{hparams["output"]}'

    for i in range(hparams['epoch']):
        env_info = env.reset(train_mode=True)[brain_name]     # reset the environment    
        # number of agents
        num_agents = len(env_info.agents)
        
        for agent in agents:
            agent.reset()
    
        # size of each action
        action_size = brain.vector_action_space_size
        states = env_info.vector_observations                  # get the current state (for each agent)

        # initialize the score (for each agent)
        epoch_score = np.zeros(num_agents)
        for t in range(1, hparams['t_max']+1):
            actions = np.array( [agents[i].act(states[i]) for i in range(num_agents) ])
            env_info = env.step(actions)[brain_name]           # send all actions to tne environment
            next_states = env_info.vector_observations         # get next state (for each agent)
            dones = env_info.local_done                        # see if episode finished
    
            for i in range(num_agents):
                agents[i].step(t, states[i], actions[i], env_info.rewards[i], next_states[i], dones[i]) 

            states = next_states
            epoch_score += env_info.rewards
            #print('\rTimestep {}\tmin: {:.2f}\tmax: {:.2f}' .format(t, np.min(epoch_score), np.max(epoch_score)), end='') 

            if np.any(dones):
                break
        if scores.AddScore(np.max(epoch_score)) is True:
            break

    for i in range(len(agents)):
        agents[i].save( f'{prefix}_agent_{i}' )
        
    scores.FlushLog(prefix, False)
Ejemplo n.º 19
0
def main():
    #esto es para centrar la pantalla
    os.environ['SDL_VIDEO_CENTERED'] = "1"

    pygame.init()
    #mouse invisible
    pygame.mouse.set_visible(0)
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_icon(tool.load_image("skyhaw"))
    pygame.display.set_caption(NAME)
    f = load_file("options")
    c = 0
    for value in f:
        c += 1
        if c == 1:
            Options.music = str_to_bool(value)
        if c == 2:
            Options.sound = str_to_bool(value)
        if c == 3:
            Options.playername = value
    tool.load_music("music")
    #aca se controla con un if las  opciones de musica on/off
    if Options.music == True:
        pygame.mixer.music.play(-1)
    main_selection = 0
    Sea.global_sea = Sea()
    while not main_selection == 6:
        main_selection = Menu(screen,
                              ("Jugar", "Historia", "Mejores Puntos",
                               "Opciones", "Ayuda", "Creditos", "Salir"),
                              main_selection).run()
        if main_selection == 0:
            dificultad = 0
            dificultad = Menu(screen, ("Cadete", "Teniente", "Halcon"),
                              dificultad).run()
            if (dificultad is not 6):
                screen = pygame.display.set_mode((800, 200))
                puntos = main_loop(dificultad)
                screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

                objScores = Scores(screen, dificultad)
                objScores.scores, res = objScores.loadNewScore(
                    Options.playername, puntos, dificultad)
                if (res):
                    objScores.run()
        elif main_selection == 1:
            Text(screen, "history").run()
            #Historia
        elif main_selection == 2:
            view = 0
            view = Menu(screen, ("Cadete", "Teniente", "Halcon"), view).run()
            if (view is not 6):
                Scores(screen, view).run()
            #Mejores Puntos
        elif main_selection == 3:
            Option(screen).run()
            #Opciones
        elif main_selection == 4:
            Text(screen, "help").run()
        elif main_selection == 5:
            Text(screen, "credit").run()
        pygame.display.update()
    pygame.quit()
    sys.exit()
Ejemplo n.º 20
0
config = yaml.safe_load(open(args.config, "r", encoding="utf-8"))

GRADING_FILE = args.grading if args.grading is not None else config["file"]["grading"]
STUDENTS_FILE = args.student if args.student is not None else config["file"]["students"]
SCORES_FILE = args.score if args.score is not None else config["file"]["scores"]
OUTPUT_FILE = args.output if args.output is not None else config["file"]["output"]


if __name__ == "__main__":
    grading_wb = load_workbook(GRADING_FILE)
    grading_ws = grading_wb.active
    grading = Grading(grading_ws)

    score_wb = load_workbook(SCORES_FILE)
    scores = Scores(score_wb, grading)

    student_wb = load_workbook(STUDENTS_FILE)
    student_sheet = student_wb.active

    classcode_column = student_sheet["A"]

    ELECTIVES = ["m2", "x2", "x1"]
    for i, elective in enumerate(ELECTIVES):
        col_index = 7 - i
        # insert a new column to the right of column with electives name
        # start from the far right column which is m2
        student_sheet.insert_cols(col_index)
        for classcode_cell in classcode_column:
            row_index = classcode_cell.row
Ejemplo n.º 21
0
def poll():
    _, yesterday = get_dates()
    print(f"Polling for date: {yesterday}")
    Report().generate_reports(yesterday)
    Scores(yesterday).poll()
Ejemplo n.º 22
0
    def showScores(self, newScore, doki):
        outerRect = Rectangle(Point(CS, CS), Point(WIDTH - CS, HEIGHT - CS))
        outerRect.setFill('purple')
        outerRect.draw(self.win)
        innerRect = Rectangle(Point(CS + 5, CS + 5), \
         Point(WIDTH - CS - 5, HEIGHT - CS - 5))
        innerRect.setFill('floral white')
        innerRect.draw(self.win)

        text = Text(Point(WIDTH / 2, 2 * CS), "Game Over!")
        text.setTextColor('black')
        text.setSize(36)
        text.draw(self.win)

        text = Text(Point(WIDTH / 2, CS * 3.5),
                    "You cleared " + str(newScore) + ' lines!')
        text.setSize(18)
        text.setTextColor('black')
        text.draw(self.win)

        text = Text(Point(WIDTH / 2, CS * 4.5), "High Scores:")
        text.setSize(18)
        text.setTextColor('black')
        text.draw(self.win)

        for i in range(1, 11):
            text = Text(Point(CS * 1.65, CS * (4.4 + i)), str(i) + '.')
            text.draw(self.win)

        sc = Scores()
        newIdx = sc.addScore('', newScore)
        highScore = False
        if newIdx < 10:
            highScore = True
        scoreList = sc.getScores()
        vals = [5.5, 10]
        currScore = None
        for val in range(2):
            for i, scoreArr in enumerate(scoreList):
                if doki and not val:  # :)
                    text = Text(Point(CS * vals[val], CS * (5.4 + i)),
                                'Monika')
                else:
                    text = Text(Point(CS * vals[val], CS * (5.4 + i)),
                                str(scoreArr[val]))
                text.draw(self.win)
                if val == 0 and i == newIdx:
                    currScore = text
        if not highScore:
            return
        newEntry = Entry(Point(CS * 5.5, CS * (5.4 + newIdx)), 10)
        newEntry.draw(self.win)
        submitted = False
        newName = ''
        while self.win.getKey() != 'Return':
            newName = newEntry.getText()
        newEntry.undraw()
        currScore.undraw()
        if doki:
            currScore.setText('Just Monika')  # :')
        else:
            currScore.setText(newName)
        currScore.draw(self.win)
        sc.addName(newIdx, newName)
Ejemplo n.º 23
0
Archivo: main.py Proyecto: Adisok/Udemy
from turtle import Screen
from players import Players
from board import Gameboard
from scores import Scores
from ball import Ball
from time import sleep

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Invalid-Pong")
screen.tracer(0)

score = Scores()
gameborad = Gameboard()
player1 = Players(-350, 0)
player2 = Players(350, 0)
ball = Ball()

screen.update()
screen.listen()

screen.onkeypress(player1.up, "Up")
screen.onkeypress(player1.down, "Down")

screen.onkeypress(player2.up, "w")
screen.onkeypress(player2.down, "s")
ball.move()

on = True
Ejemplo n.º 24
0
                if "queued" in stats:
                    queued = stats["queued"]
                started = []
                if "started" in stats:
                    started = stats["started"]
                if not (queued + started):
                    jobs_done = True
                else:
                    print(sys.stderr,\
                          len(started), "started", len(queued), "queued")
                    sleep(10)
                if "error" in stats and stats["error"]:
                    print(sys.stderr, "Errors occurred", stats["error"])
                    sys.exit(1)

            finalScores = Scores()
            print(len(testPoints))
            for job in ssn:
                res, scores = job.results
                print(res)
                finalScores += scores
            classifier.scores = finalScores
        else:
            sys.exit(0)

    else:
        print(sys.stderr, "labeling...")
        classifier.label()

    print(sys.stderr, "test classifier performance")
    print(sys.stderr, classifier.scores)
Ejemplo n.º 25
0
from scores import Scores

scores = Scores(debug=True)
games = scores.get_games(only_major_games=True)
# games = scores.get_games()
# games = scores.get_games(include_cancelled=True, include_postponed=True)
# games = scores.get_games(include_cancelled=True, include_postponed=True, only_major_games=True)

print(len(games))

# games[0].jsonprint()

# scores.download_assets(games[0]).jsonprint()