Ejemplo n.º 1
0
def main():
    display = pygame.display.set_mode(
        (Config['game']['width'], Config['game']['height']))
    pygame.display.set_caption(Config['game']['caption'])

    game = Game(display)
    game.loop()
Ejemplo n.º 2
0
 def __init__(self):
     self.apps_path = ""
     self.working_dir = ""
     self.hack_dir = ""
     self.decrypt_dir = ""
     self.backup_dir = ""
     self.user = User()
     self.game = Game()
Ejemplo n.º 3
0
    def __init__(self):
        self.n_player = 0
        self.game = Game()

        scneration01(self.game)

        self.display_game()

        super(MyPrompt, self).__init__()
        self.do_pow('')
Ejemplo n.º 4
0
    def __init__(self, categoriesSelected, parent):
        super(GameWindow, self).__init__(parent)
        self.categories = self.getCategories(categoriesSelected)
        self.setupUi(self, self.categories)
        self.game = Game(self.categories)
        self.spin = ""

        self.updateUI()

        self.spinner.clicked.connect(self.spinWheel)
        self.back.clicked.connect(self.close)
        self.back.clicked.connect(parent.show)
Ejemplo n.º 5
0
    def get_games(self):
        a = [
            s for s in os.listdir(self.path)
            if os.path.isdir(os.path.join(self.path, s))
        ]

        if len(a) == 0:
            print(
                f"{self.path} contains no games. Please ensure you have run QCMA and backed up your game."
            )
            sys.exit("No Game In User Path")

        a.sort(reverse=True,
               key=lambda s: os.path.getmtime(os.path.join(self.path, s)))
        for folder in a:
            game_id = findall(r"([A-Z]{4}[0-9]{5})$", folder)
            if game_id:
                game = Game()
                game.set_id(game_id[0])
                game.set_path(self.path)
                self.games.append(game)
Ejemplo n.º 6
0
 def test_model(self, model):
     steps_arr = []
     scores_arr = []
     for _ in range(self.test_games):
         steps = 0
         game_memory = []
         game = Game()
         _, score, snake, apple = game.start()
         prev_observation = self.generate_observation(snake, apple)
         for _ in range(self.goal_steps):
             predictions = []
             for action in range(-1, 2):
                 predictions.append(
                     model.predict(
                         self.add_action_to_observation(
                             prev_observation, action).reshape(-1, 5, 1)))
             action = np.argmax(np.array(predictions))
             game_action = self.get_game_action(snake, action - 1)
             done, score, snake, apple = game.step(game_action)
             game_memory.append([prev_observation, action])
             if done:
                 print('-----')
                 print(steps)
                 print(snake)
                 print(apple)
                 print(prev_observation)
                 print(predictions)
                 break
             else:
                 prev_observation = self.generate_observation(snake, apple)
                 steps += 1
         steps_arr.append(steps)
         scores_arr.append(score)
     print('Average steps:', mean(steps_arr))
     print(Counter(steps_arr))
     print('Average score:', mean(scores_arr))
     print(Counter(scores_arr))
Ejemplo n.º 7
0
    def initial_population(self):
        training_data = []
        for _ in range(self.initial_games):
            display = pygame.display.set_mode(
                (Config['game']['width'], Config['game']['height']))
            pygame.display.set_caption(Config['game']['caption'])

            game = Game(display)

            _, prev_score, snake, apple = game.start()
            prev_observation = self.generate_observation(snake, apple)
            prev_apple_distance = self.get_apple_distance(snake, apple)
            for _ in range(self.goal_steps):
                action, game_action = self.generate_action(snake)
                done, score, snake, apple = game.step(game_action)
                if done:
                    training_data.append([
                        self.add_action_to_observation(prev_observation,
                                                       action), -1
                    ])
                    break
                else:
                    apple_distance = self.get_apple_distance(snake, apple)
                    if score > prev_score or apple_distance < prev_apple_distance:
                        training_data.append([
                            self.add_action_to_observation(
                                prev_observation, action), 1
                        ])
                    else:
                        training_data.append([
                            self.add_action_to_observation(
                                prev_observation, action), 0
                        ])
                    prev_observation = self.generate_observation(snake, apple)
                    prev_apple_distance = apple_distance
        return training_data
Ejemplo n.º 8
0
    "item": hiPotion,
    "quantity": 5
}, {
    "item": superPotion,
    "quantity": 5
}, {
    "item": elixer,
    "quantity": 5
}, {
    "item": hiElixier,
    "quantity": 2
}, {
    "item": grenade,
    "quantity": 5
}]

#Instantiate People
player = Person("Mario", 3260, 200, 60, 34, playerSpells, playerItems)
player2 = Person("Mario", 4160, 200, 60, 34, playerSpells, playerItems)
player3 = Person("Robot", 3889, 200, 60, 34, [], playerItems)

enemy = Person("Evil Mario", 18200, 701, 525, 25, [], [])
enemy2 = Person("MXMXM", 1250, 130, 560, 325, [], [])
enemy3 = Person("Imp", 1250, 130, 560, 325, [], [])

players = [player, player2, player3]
enemies = [enemy, enemy2, enemy3]

game = Game(players, enemies)
game.announcement()
game.play()
Ejemplo n.º 9
0
        game.next_Round()
        # update gui
        self.update_Main_Window_Information()


def load_cats_data(path,file_name):
    cats=[]
    file_path=path+file_name
    for i in range(1,DataBaseIO.len_Database(file_path,"CAT")+1):
        t_name=DataBaseIO.read_Database(file_path,"CAT",i,"NAME")
        t_is_alive=DataBaseIO.read_Database(file_path,"CAT",i,"IS_ALIVE")
        t_friendly_const=DataBaseIO.read_Database(file_path,"CAT",i,"FRIENDLY_CONST")
        t_consumption=DataBaseIO.read_Database(file_path,"CAT",i,"CONSUMPTION")
        t_appeared_yesterday=DataBaseIO.read_Database(file_path,"CAT",i,"APPEARED_YESTERDAY")
        cats.append(Cat(t_name,t_is_alive,t_friendly_const,t_consumption,appeared_yesterday=t_appeared_yesterday))
    return cats

if __name__ == "__main__":
    import sys

    path = "savings/"
    file_name="init.db"
    cats = load_cats_data(path,file_name)
    campus = Campus(cats)
    game = Game(campus, cats)
    app = QApplication(sys.argv)
    Main_Window = QtWidgets.QMainWindow()
    win = myWindow(Main_Window)
    Main_Window.show()
    sys.exit(app.exec_())
Ejemplo n.º 10
0
def get_games_stats(config, upcoming_flg, begin_yr=None, begin_wk=None):

    if upcoming_flg:
        start_yr = datetime.datetime.now().year
        current_yr = datetime.datetime.now().year + 1
    else:
        start_yr = config["start_yr"] if begin_yr is None else begin_yr
        current_yr = datetime.datetime.now().year

    root_dir = os.getcwd().replace("/src", "").replace("/data", "")
    data_dir = os.path.join(root_dir, "data", "external")
    games_by_team_path = os.path.join(data_dir, "game_summary_by_team.csv")

    for season in range(start_yr, current_yr):
        season = Season(season, config)
        games_table = season.get_schedule_table()
        weekly_dict = season.get_weekly_dict(games_table, upcoming_flg,
                                             begin_yr, begin_wk)

        for week_num, games in weekly_dict.items():

            week = Week(season, week_num, weekly_dict[str(week_num)],
                        upcoming_flg)

            print("\nYear: {} / Week: {}".format(season.season, week_num))
            for game_idx, game_info in enumerate(week.games):
                if os.path.exists(games_by_team_path):
                    games_by_team_df = pd.read_csv(games_by_team_path)
                else:
                    games_by_team_df = pd.DataFrame()

                game = Game(week, week.games[game_idx], upcoming_flg)
                print(game.game_full_url)

                for team_idx, team_info in enumerate(game.teams_list):

                    opp_info = game.teams_list[abs(team_idx - 1)]
                    home_flg = team_info["home_flg"]
                    team = Team(game, team_info["team"], opp_info["team"],
                                home_flg)
                    opponent = Team(game, opp_info["team"], team_info["team"],
                                    opp_info["home_flg"])
                    team_row_dict = team.get_team_game_summary(game)
                    team_game_stats_dict = team.get_indiv_game_stats()
                    rush_dir_dict = team.get_rush_dir_stats()
                    drive_summary_dict = team.get_drive_summary_dict()

                    team_row_dict.update(team_game_stats_dict)
                    team_row_dict.update(rush_dir_dict)
                    team_row_dict.update(drive_summary_dict)

                    team_snap_rows = team.get_game_snap_rows(opp_flg=False)
                    team_game_player_stats = get_player_stats_rows(
                        team_snap_rows, team)

                    opp_snap_rows = team.get_game_snap_rows(opp_flg=True)
                    opp_game_player_stats = get_player_stats_rows(
                        opp_snap_rows, opponent)

                    team_game_player_df = pd.DataFrame(team_game_player_stats)
                    team.drop_to_csv(team_game_player_df,
                                     "game_summary_by_player")

                    opp_game_player_df = pd.DataFrame(opp_game_player_stats)

                    if len(team_game_player_df) > 0 and len(
                            opp_game_player_df) > 0:
                        team_pos_dict = team.aggregate_game_stats_by_pos(\
                             team_game_player_df, opp_flg = False, \
                             off_snaps = team_row_dict["team_plays"], def_snaps = team_row_dict["opp_plays"])
                        opp_pos_dict = team.aggregate_game_stats_by_pos(\
                             opp_game_player_df, opp_flg = True, \
                             off_snaps = team_row_dict["opp_plays"], def_snaps = team_row_dict["team_plays"])

                        team_row_dict.update(team_pos_dict)
                        team_row_dict.update(opp_pos_dict)
                    team_idx_dict = team.get_idx_cols(games_by_team_df,
                                                      team_row_dict)
                    team_row_dict.update(team_idx_dict)

                    team.add_row_to_csv(team_row_dict)
Ejemplo n.º 11
0
def main():
    g = Game()
    g.set_up()
    g.mainloop()
Ejemplo n.º 12
0
# -*- coding: utf-8 -*-

import pygame
import ctypes
from config import app_config, app_logger
from classes.Game import Game
from classes.Grid import Grid
from classes.Ball import Ball
from classes.UI import UI

pygame.init()

# Заглавие окна
pygame.display.set_caption(app_config['app']['name'].get())

# Две строчки ниже хак, чтобы FULLSCREEN рисовался строго по границам монитора, а не шире, как по умолчанию
ctypes.windll.user32.SetProcessDPIAware()
true_res = (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
window = pygame.display.set_mode(true_res, pygame.FULLSCREEN)

# Инициализируем UI
user_interface = UI(window)

# Инициализируем Grid
grid = Grid()
grid.draw(window)

# Головная игровая логика
game = Game(window, grid, user_interface)
game.start()
Ejemplo n.º 13
0
import pygame as pg

pg.init()
from classes.Game import Game

g = Game()
g.run()
g.show_end_screen()
Ejemplo n.º 14
0
import pygame, sys
from pygame.locals import *

sys.path.append('/home/denis/Documentos/developer/python/snake-game/classes')

from classes.Game import Game
from classes.Snake import Snake
from classes.Apple import Apple

pygame.init()

# GAME INITIALIZATION
snake_game = Game()

WINDOW_SIZE = (snake_game.WINDOW_WIDTH, snake_game.WINDOW_HEIGHT)
PIXEL_SIZE = snake_game.PIXEL_SIZE
COLORS = snake_game.COLORS
FPS = snake_game.FPS

# AUDIO
pygame.mixer.init()
pygame.mixer.music.load('./assets/audios/yamete-kudasai.wav')

# SNAKE INITIALIZATION
snake_head_image = pygame.image.load('./assets/images/snake-head.png')
initial_snake_pos = [(200, 200), (190, 200), (180, 200)]

snake = Snake(initial_snake_pos, snake_head_image)

# APPLE INITIALIZATION
initial_apple_pos = (100, 100)
Ejemplo n.º 15
0
from classes.Entity import HealFloor, Warrior

if __name__ == '__main__':

    a1 = Address("127.0.0.1 ", 3331)
    w1 = Warrior((0, 0))
    p1 = Player(a1, "p1", w1)

    a2 = Address("127.0.0.1 ", 3332)
    w2 = Warrior((0, 0))
    p2 = Player(a2, "p2", w2)

    hf1 = HealFloor((2, 1))

    columnList = [
        [Column((0, 0), 1, []),
         Column((1, 0), 1, []),
         Column((2, 0), 1, [])],
        [Column((0, 1), 1, []),
         Column((1, 1), 2, []),
         Column((2, 1), 2, [])],
        [Column((0, 2), 1, []),
         Column((1, 2), 2, []),
         Column((2, 2), 2, [])],
    ]
    map = Map(1, (3, 3), columnList)

    g1 = Game(map, [p1, p2], [w1, w2, hf1])

    print("\n")
    print(w1.skills[0].id)
Ejemplo n.º 16
0
from flask import Flask, request, render_template, redirect, send_from_directory
from classes.Game import Game

app = Flask(__name__,
            static_url_path='/js',
            static_folder='templates/js/',
            template_folder='templates/')


class Init(object):
    def __init__(self):
        self.player_id = 0


game = Game()
init = Init()


def initgame():

    if init.player_id != 0:
        return True

    init.player_id = 1

    # INIT
    ## INIT player 1
    y = 0
    while y < 24:
        for x in range(25, 27):
            game.player_play_pow(1, x, y)
Ejemplo n.º 17
0
Archivo: main.py Proyecto: edoelas/tfg
from classes.actions.Heal import Heal
from classes.actions.Throw import Throw
from classes.Position import Position
from classes.Game import Game
from classes.Entity import Entity
from classes.Client import Client
from classes.Map import Map

import json
import os

from classes.actions.Move import Move
from classes.actions.Strike import Strike

##

 __name__ == "__main__":
    game = Game("localhost", 1234)
    with open('./games/g1.json') as g1:
        game_data = json.load(g1)
        game.load_game(game_data
        print(game.map.entity_table[1])

        with open('./client_messages/cm1.json') as cm1:
            client_actions_data = json.load(cm1)
            game.unserialize_client([client_actions_data])

            print(game.map.entity_table[1])
Ejemplo n.º 18
0
import pygame

from classes.config import Config
from classes.Game import Game

pygame.init()

display = pygame.display.set_mode((Config['w_g'], Config['h_g']))
pygame.display.set_caption('Project 3 semester by Iliya Puzhaev')

game = Game(display)

game.start_screen()
Ejemplo n.º 19
0
 def build(self):
     game = Game()
     game.start()
     timer = Clock.schedule_interval(game.timer, 1)
     return game
Ejemplo n.º 20
0
from classes.Game import Game

Game()
Ejemplo n.º 21
0
#!/usr/bin/python
# -*- encoding: utf-8 -*-

__author__ = 'Oliver Banse'


# IDEA
# Import and Initialization
import pygame

from classes.Game import Game
from classes.Screen import Screen

pygame.init()

# Display configuration
screen = Screen('Hit the Mole!', 800, 600)
# Entities
game = Game(screen)
# Run Game
game.start()


# if __name__ == '__main__':
#     game.start()
Ejemplo n.º 22
0
 def test_something_2(self):
     game = Game(33, 2, 1)
     game.afficher_restant()
Ejemplo n.º 23
0
 def test_something_3(self):
     game = Game(1, 2, True)
     game.pc_play_first()
     self.assertEqual("humain", game.winner)
Ejemplo n.º 24
0
 def test_something_5(self):
     game = Game(1, 2, False)
     game.pc_play_first()
     self.assertEqual(game.nb_restantes, 1)
Ejemplo n.º 25
0
from classes.Game import Game

Game().run()
Ejemplo n.º 26
0
    def test_something(self):
        game = Game(200, 2, 1)

        while game.winner == "":
            self.assertTrue(game.jeu_ordinateur() > 0)
Ejemplo n.º 27
0
					'killing_as_a_service': Service('killing_as_a_service', '20113', killing_as_a_service),
					'ATM_machine': Service('ATM_machine', '20061', ATM_machine),
					'gdps': Service('gdps', '20037',gdps),
					'temperature': Service('temperature', '25096',temperature),
					'spiderman': Service('spiderman', '30000',spiderman),
					'tattletale': Service('tattletale', '13007',tattletale)
	}

	teamListStatus = { }
	for teamName, team in teamList.iteritems():
		serviceListStatus = { }
		for serviceName, service in serviceList.iteritems():
			serviceListStatus[serviceName] = "Down"
		teamListStatus[teamName] = serviceListStatus

	honeypotList = {'poemwriter','gdps'}

	game = Game(teamList, serviceList, honeypotList)
	
	newGame = 0
	for arg in sys.argv:
		if arg == "-n":
			newGame = 1
	if newGame:
		game.resetLog()
	else:
		game.restoreLog()
	
	threading.Timer(2, routine).start()
	app.run(host = "0.0.0.0")
Ejemplo n.º 28
0
def play_game(player_names):
    game = Game(player_names)
    print(get_game_intro_dialog(game))
    while game.game_over == False:
        game.advance_game()
Ejemplo n.º 29
0
# Expecting player input to pick a language
def language_picked():
    language = input(
        "Welcome to the Hangman ! Wich language would you like to use ? \n(use the first two letter of your language, ex: 'fr' for French\n")
    while len(language) != 2 or not language.isalpha():
        language = input("Use only two letters, ex: 'it' for Italian\n")
    print("You chose " + language.upper())
    return language

# Translate the random word generated based on language picked by the player
def translated_word():
    trans = Translator()
    return unidecode.unidecode(trans.translate(generated_word(), src='en', dest=language_picked()).text).lower()

# Game initialization
game = Game(translated_word())

# Write a welcome message
def welcome():
    print("Let's see if you will be able to save the man from hanging ... ;)")

# Check if the player have used all his chances or if he won
def is_game_over():
    return game.get_try_number() == 0 or game.game_won()

# Check if the letter has already been used
#   yes: send a message to warn the player that he already used that letter
#   no: add it to a list of letter been used
# Then check if the letter is in the secret word
#   yes: change current secret word state
#   no: the player lose one chance
Ejemplo n.º 30
0
import pygame
from classes.Game import Game

# Setting up the title of the game, and the window size:
game_title = 'Initial ABCross D'
screen_width = 800
screen_height = 800

# Initializing PYGAME:
pygame.init()

#Running the game:
game = Game(game_title, screen_width, screen_height, 'background.png')
game.run_game_loop(1)

# Leaving PYGAME:
pygame.quit()
quit()