Ejemplo n.º 1
0
def start():
    pg.init()

    game = Game('Conway\'s Game of Life')
    game.start()

    pg.quit()
Ejemplo n.º 2
0
    def __init__(self):
        pg.key.set_repeat(500, 100)
        self.main_clock = pg.time.Clock()
        self.clock = pg.time.Clock()
        self.playing = False
        self.started_game = False
        self.game_surf = None  # only used to draw static game screen when fading into game_stop screens
        self.black_alpha_surf = pg.Surface(
            (SAVE_DATA["width"], SAVE_DATA["height"]))

        self.display = MainDisplay()

        self.start_menu = StartMenu(self.clock)
        self.menu = Menu()
        self.game = Game(self.clock)
        self.game_over = GameOver()
        self.pause = Pause()
        self.tower_preview = TowerPreviewMenu(self.clock)
        self.enemy_preview = EnemyPreviewMenu(self.clock)
        self.upgrades_menu = UpgradesMenu()
        self.purchase_menu = PurchaseMenu()
        self.tower_select = TowerSelectMenu()
        self.options = Options()

        self.display_keys = {
            "menu": self.menu,
            "resume": self.game,
            "game": self.game,
            "game_over": self.game_over,
            "pause": self.pause,
            "tower_preview": self.tower_preview,
            "enemy_preview": self.enemy_preview,
            "upgrades_menu": self.upgrades_menu,
            "purchase_menu": self.purchase_menu,
            "tower_select": self.tower_select,
            "options": self.options
        }

        self.display_keys_reverse = {
            self.menu: "menu",
            self.pause: "pause",
            self.game_over: "game_over",
            self.start_menu: "start_menu"
        }

        self.set_display(self.start_menu, [self.menu, False])

        self.result = None

        self.fading_out = False
        self.fading_in = False
        self.black_alpha = 0
        self.fade_out_speed = [10, 40]
        self.fade_in_speed = [30, 50]
        self.fade_ind = 0

        self.game_surf = None
Ejemplo n.º 3
0
 def __init__(self, game: Game):
     self.balls = game.balls()
     self.strikes = game.strikes()
     last_pitch = game.last_pitch()
     if last_pitch is None:
         self.last_pitch_speed = "0"
         self.last_pitch_type = "UK"
         self.last_pitch_type_long = "Unknown"
     else:
         self.last_pitch_speed = f"{round(last_pitch[0])}"
         self.last_pitch_type = data.pitches.PITCH_SHORT[last_pitch[1]]
         self.last_pitch_type_long = data.pitches.PITCH_LONG[last_pitch[1]]
Ejemplo n.º 4
0
 def menu():
     while True:
         print("Хотите начать игру? ")
         choice = input("--->>>  ")
         if choice == "1":
             game.start(start_game())
         elif choice == "2":
             print(helps)
         elif choice == "3":
             print("Всего самого найлучшего")
             sys.exit()
         else:
             print("Пожалуйста, введите нужною команду")
Ejemplo n.º 5
0
 def put(self, *args):
     path_elements = [x for x in self.request.path.split("/") if x]
     game = Game(self.request.body)
     game.id = path_elements[0]
     game.save()
     self.set_header('Content-Type', 'application/json')
     self.finish(game.toJSON())
Ejemplo n.º 6
0
 def get(self, *args):
     # Get ID and make sure the file exists
     path_elements = [x for x in self.request.path.split("/") if x]
     if len(path_elements) == 2 and path_elements[1] == 'game':
         game = Game.load(path_elements[0])
         if game is None:
             self.set_header('Content-Type', 'application/json')
             self.set_status(404)
             self.finish({"message": "Le jeu n'existe pas"})
         else:
             self.set_header('Content-Type', 'application/json')
             self.finish(game.toJSON())
     else:
         loader = tornado.template.Loader("./server/pages")
         self.finish(loader.load("home.html").generate())
Ejemplo n.º 7
0
def add_game():
    form = GameForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        if db_sess.query(Game).filter(Game.title == form.title.data).all():
            return render_template(
                'add_game.html',
                title='Дбавление Игры',
                form=form,
                message="Игра с таким названием уже существует")
        print(form.image_url.data, ":",
              form.image.check_validators([DataRequired()]))
        if form.image_url.data == "" and form.image.check_validators(
            [DataRequired()]):
            return render_template('add_game.html',
                                   title='Добавление Игры',
                                   form=form,
                                   message="Нет картинки")
        game = Game(title=form.title.data,
                    short_description=form.short_description.data,
                    version=form.version.data,
                    description=form.description.data,
                    need_premium=form.need_premium.data,
                    category_id=form.category.data)
        if form.image_url.data:
            game.image = form.image_url.data
        else:
            f = form.image.data
            filename = secure_filename(f.filename)
            img_path = os.path.join(UPLOAD_PATH, 'img', filename)
            f.save(img_path)
            game.image = '\\' + img_path

        f = form.url.data
        filename = secure_filename(f.filename)
        torrent_path = os.path.join(UPLOAD_PATH, 'torrent', filename)
        f.save(torrent_path)
        game.url = '\\' + torrent_path
        game.user_id = current_user.id
        db_sess = db_session.create_session()
        db_sess.add(game)
        db_sess.commit()
        return redirect('/addgame')
    return render_template('add_game.html',
                           title='Регистрация Работы',
                           form=form)
Ejemplo n.º 8
0
"""
HOKEY
"""

from data.game import Game

if __name__ == '__main__':
    with Game():
        Game().main()
Ejemplo n.º 9
0
    def __init__(self, game: Game, time_format):
        self.home_team = game.home_abbreviation()
        self.away_team = game.away_abbreviation()
        self.pregame_weather = game.pregame_weather()
        self.time_format = time_format

        try:
            self.start_time = self.__convert_time(game.datetime())
        except:
            self.start_time = "TBD"

        self.status = game.status()

        away_id = game.probable_pitcher_id("away")
        if away_id is not None:
            name = game.full_name(away_id)
            wins = game.pitcher_stat(away_id, "wins", "away")
            losses = game.pitcher_stat(away_id, "losses", "away")
            era = game.pitcher_stat(away_id, "era", "away")
            self.away_starter = "{} ({}-{} {} ERA)".format(
                name, wins, losses, era)
        else:
            self.away_starter = PITCHER_TBD

        home_id = game.probable_pitcher_id("home")
        if home_id is not None:
            name = game.full_name(home_id)
            wins = game.pitcher_stat(home_id, "wins", "home")
            losses = game.pitcher_stat(home_id, "losses", "home")
            era = game.pitcher_stat(home_id, "era", "home")
            self.home_starter = "{} ({}-{} {} ERA)".format(
                name, wins, losses, era)
        else:
            self.home_starter = PITCHER_TBD
Ejemplo n.º 10
0
    def __getattr__(self, item):
        if DEBUG:
            return getattr(self.client, item)
        return lambda *args: None


manager = Manager()
times = []

while True:
    start = time.time()

    data = json.loads(input())

    if data['type'] != 'tick':
        continue

    game = Game(data['params'])
    debug = Debug(game.me)

    manager.new_tick(game, debug)
    manager.make_move()

    end = time.time()
    times.append(end - start)
    debug.message(f'Time: {end - start}')
    debug.message(f'Time avg: {sum(times) / len(times)}\n\n')

    game.end_tick()
Ejemplo n.º 11
0
 def post(self):
     g = Game(self.request.body)
     g.id = id_generator()
     g.save()
     self.set_header('Content-Type', 'application/json')
     self.finish(g.toJSON())
Ejemplo n.º 12
0
""" This module runs the game Tomb of the Lizard King, my entry for the 11th Alakajam. """

import pygame as pg

from data.game import Game

if __name__ == "__main__":
    pg.init()
    Game().run()
    pg.quit()
Ejemplo n.º 13
0
 def __init__(self, game: Game):
     self.number = game.outs()
Ejemplo n.º 14
0
    def __init__(self, game: Game):
        b1 = game.man_on("first")
        b2 = game.man_on("second")
        b3 = game.man_on("third")

        self.runners = [b1, b2, b3]
Ejemplo n.º 15
0
from data.game import Game
import csv

if __name__ == "__main__":
    peli = Game()
Ejemplo n.º 16
0
def main():
    pg.init()
    pg.font.init()
    Game()
Ejemplo n.º 17
0
import json
import uuid

from flask import Flask, request

from data.game import Game

game = Game()

server = Flask(__name__)


def validation(data):
    if not data.get('id'):
        return return_json('STOP PLEASE')
    if data['id'] not in game.players.values():
        return return_json('Unrecognized identification')


def return_json(message):
    return json.dumps({'message': message})


@server.route('/')
def info():
    information = """
	Welcome 

	GET /stats --> get game stats
	POST /take --> take pieces
Ejemplo n.º 18
0
                       )
        rows = cursor.fetchall()
        for row in rows:
            print('{0} : {1} - {2} - {3} - {4} - {5} - {6} - {7} - {8}'.format(
                row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7],
                row[8]))
    except sqlite3.OperationalError:
        print('Erreur print impossible')
    except Exception as e:
        print("Erreur")
        # raise e


create_table_game()

game_test = Game()
game_test.date = "08/07/2019 22:50:25"
game_test.buy_in = 23
game_test.rake = 2
game_test.prizePool = 50
game_test.nbPlayer = 3
game_test.gameFormat = "Hold'em No Limit"
game_test.position = 1
game_test.earning = 50

insert_game_to_table_game(game_test)

game_test.date = "08/07/2019 23:53:25"
game_test.buy_in = 23
game_test.rake = 2
game_test.prizePool = 50
Ejemplo n.º 19
0
class Main:
    def __init__(self):
        pg.key.set_repeat(500, 100)
        self.main_clock = pg.time.Clock()
        self.clock = pg.time.Clock()
        self.playing = False
        self.started_game = False
        self.game_surf = None  # only used to draw static game screen when fading into game_stop screens
        self.black_alpha_surf = pg.Surface(
            (SAVE_DATA["width"], SAVE_DATA["height"]))

        self.display = MainDisplay()

        self.start_menu = StartMenu(self.clock)
        self.menu = Menu()
        self.game = Game(self.clock)
        self.game_over = GameOver()
        self.pause = Pause()
        self.tower_preview = TowerPreviewMenu(self.clock)
        self.enemy_preview = EnemyPreviewMenu(self.clock)
        self.upgrades_menu = UpgradesMenu()
        self.purchase_menu = PurchaseMenu()
        self.tower_select = TowerSelectMenu()
        self.options = Options()

        self.display_keys = {
            "menu": self.menu,
            "resume": self.game,
            "game": self.game,
            "game_over": self.game_over,
            "pause": self.pause,
            "tower_preview": self.tower_preview,
            "enemy_preview": self.enemy_preview,
            "upgrades_menu": self.upgrades_menu,
            "purchase_menu": self.purchase_menu,
            "tower_select": self.tower_select,
            "options": self.options
        }

        self.display_keys_reverse = {
            self.menu: "menu",
            self.pause: "pause",
            self.game_over: "game_over",
            self.start_menu: "start_menu"
        }

        self.set_display(self.start_menu, [self.menu, False])

        self.result = None

        self.fading_out = False
        self.fading_in = False
        self.black_alpha = 0
        self.fade_out_speed = [10, 40]
        self.fade_in_speed = [30, 50]
        self.fade_ind = 0

        self.game_surf = None

    def run(self):
        self.main_clock.tick(FPS)
        self.clock.tick()
        self.events()
        self.update()
        self.clock.tick()
        self.draw()

    def update(self):
        self.current_display.update()

    def draw(self):
        pg.display.set_caption("FPS: {:.2f}".format(self.main_clock.get_fps()))

        self.display.display.fill((0, 0, 0))
        if self.current_display is self.game_over or self.current_display is self.pause:
            self.display.display.blit(self.game_surf, (0, 0))

        if self.current_display is self.game or self.current_display is self.menu:
            surf = self.current_display.draw()
        else:
            surf = pg.transform.scale(
                self.current_display.draw(),
                (SAVE_DATA["width"], SAVE_DATA["height"]))
        self.display.display.blit(surf, (0, 0))

        if self.fading_out:
            if self.black_alpha == 255:
                self.fading_out = False
                self.fading_in = True
                self.set_display(self.display_keys[self.result], self.args)
            else:
                self.black_alpha = min(
                    255, self.black_alpha + self.fade_out_speed[self.fade_ind])

            self.black_alpha_surf.fill((0, 0, 0))
            self.black_alpha_surf.set_alpha(self.black_alpha)
            self.display.display.blit(self.black_alpha_surf, (0, 0))

        elif self.fading_in:
            if self.black_alpha == 0:
                self.fading_in = False
            else:
                self.black_alpha = max(
                    0, self.black_alpha - self.fade_in_speed[self.fade_ind])

            self.black_alpha_surf.fill((0, 0, 0))
            self.black_alpha_surf.set_alpha(self.black_alpha)
            self.display.display.blit(self.black_alpha_surf, (0, 0))

        pg.display.flip()

    def events(self):
        if self.fading_in or self.fading_out:
            return

        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
                break

            elif event.type == pg.USEREVENT + 4:  # Detects if graphics option changed
                self.black_alpha_surf = pg.Surface(
                    (SAVE_DATA["width"], SAVE_DATA["height"]))
                self.game.event(event)
                self.menu.event(event)

            else:
                if event.type == pg.MOUSEBUTTONDOWN or event.type == pg.MOUSEBUTTONUP or event.type == pg.MOUSEMOTION:
                    event.pos = (round(event.pos[0] /
                                       self.display.screen_ratio),
                                 round(event.pos[1] /
                                       self.display.screen_ratio))
                temp_result = self.current_display.event(event)

                if temp_result != -1:
                    self.result = temp_result
                    self.args = []

                    if self.result == "game" or self.result == "resume":
                        self.args.extend([
                            (self.menu.get_over_level(),
                             self.tower_select.get_difficulty()),
                            self.result == "resume",
                            self.tower_select.get_selected_towers()
                        ])
                    elif self.result == "tower_select":
                        self.args.extend([
                            self.menu.get_over_level(),
                            self.menu.get_difficulty()
                        ])
                    elif self.result == "options":
                        self.args.extend(
                            [self.display_keys_reverse[self.current_display]])
                    elif self.result == "game_over":
                        self.game_surf = self.game.draw()
                        self.args.extend([
                            self.game.draw(),
                            self.current_display == self.options,
                            self.game.get_lives() == 0,
                            self.game.get_cause_of_death(),
                            (self.game.level, self.game.difficulty,
                             self.game.protein)
                        ])
                    elif self.result == "pause":
                        self.game_surf = self.game.draw()
                        self.args.extend([
                            self.game.draw(),
                            self.current_display == self.options
                        ])
                    elif self.result == "menu":
                        self.args.append(
                            self.current_display in self.display_keys_reverse)

                    # don't do fade out for the following transitions:
                    # transitioning from game --> pause/game_over
                    # transitioning from pause --> game (resuming, not restarting)
                    if (self.current_display == self.game and
                        (self.result == "pause" or self.result == "game_over")
                        ) or (self.current_display == self.pause
                              and self.result == "resume"):
                        self.set_display(self.display_keys[self.result],
                                         self.args)
                    else:
                        self.fade_ind = 1
                        if self.current_display == self.game_over:  # transitioning from game_over has a slower fade speed
                            self.fade_ind = 0

                        self.fading_out = True

    def set_display(self, display, args):
        display.new(args)
        self.current_display = display

    def quit(self):
        with open(path.join(GAME_FOLDER, "save.json"), 'w') as out_file:
            json.dump(SAVE_DATA, out_file, indent=4)
        pg.quit()
        sys.exit()
Ejemplo n.º 20
0
def handle_dialog(res, req, restart=False):
    session = db_session.create_session()
    sp = [i.name for i in session.query(View).all()]
    if req['session']['new'] or restart:
        res['response'][
            'text'] = 'Привет! Меня зовут Алиса, давай сыграем в разные викторины. С чего начнём?'
        res['response']['buttons'] = get_suggests(sp)
        game = Game()
        game.round = 1
        game.set = 0
        game.end = False
        game.contin = True
        session.add(game)
        session.commit()
        return
    game = session.query(Game).all()
    game = game[-1]
    players = session.query(Player).filter(Player.match == game.id)
    if req['request']['original_utterance'] in sp:
        view = session.query(View).filter(
            View.name == req['request']['original_utterance']).first()
        game = session.query(Game)[-1]
        game.type = view.id
        session.commit()
        if players.first() is None:
            res['response'][
                'text'] = 'С игрой определились, теперь, сколько раундов будем играть?'
            return
    if req['request']['original_utterance'] == 'Выйти из матча':
        game.end = True
        session.commit()
    if req['request']['original_utterance'] == 'Начать матч' and game.end:
        game.end = False
        session.commit()
        handle_dialog(res, req, restart=True)
        return
    elif game.end:
        res['response']['text'] = 'Игра завершена.'
        res['response']['buttons'] = get_suggests(['Начать матч'])
        return
    if game.type is None:
        res['response']['text'] = 'Повторите, пожалуйста, во что играем?'
        if game.contin:
            res['response']['buttons'] = get_suggests(sp)
        else:
            sp.append('Выйти из матча')
            res['response']['buttons'] = get_suggests(sp)
        return
    if game.view.rounds is None:
        if get_number(req) is None:
            res['response'][
                'text'] = 'Повторите, пожалуйста, сколько будет раундов?'
            return
        else:
            game.view.rounds = int(get_number(req))
            session.commit()
            if players.first() is None:
                res['response'][
                    'text'] = 'С этим определились, теперь, все игроки, назовите, пожалуйста, ' \
                              'своё имя без фамилии и отчества.'
                return

    if players.first() is None:
        gamers = get_players(req)
        if not bool(gamers):
            res['response']['text'] = \
                'Повторите, пожалуйста, кто будет играть?'
        else:
            for name in gamers:
                player = Player()
                player.name = name
                player.round = 0
                player.match = game.id
                player.points = 0
                player.kush = 0
                player.win = 0
                player.now = False
                session.add(player)
                session.commit()
    if players.first() is not None:
        game.contin = True
        session.commit()
        if req['request'][
                'original_utterance'] == 'Закончить игру' or game.round > game.view.rounds:
            quit(res, req, players, session)
        else:
            res['response']['buttons'] = get_suggests(['Закончить игру'])
            if game.view.name == 'Towns':
                play_towns(res, req)
Ejemplo n.º 21
0
 def __init__(self, game: Game):
     self.number = game.inning_number()
     self.state = game.inning_state()
     self.ordinal = game.inning_ordinal()
Ejemplo n.º 22
0
    def __init__(self, game: Game):

        self.batter = game.batter()
        self.onDeck = game.on_deck()
        self.inHole = game.in_hole()
        self.pitcher = game.pitcher()
Ejemplo n.º 23
0
    def __init__(self, game: Game):

        winner_side = game.winning_team()

        winner = game.decision_pitcher_id("winner")
        if winner is not None:
            self.winning_pitcher = game.full_name(winner)
            self.winning_pitcher_wins = game.pitcher_stat(
                winner, "wins", winner_side)
            self.winning_pitcher_losses = game.pitcher_stat(
                winner, "losses", winner_side)
        else:
            self.winning_pitcher = PITCHER_UNKNOWN
            self.winning_pitcher_wins = 0
            self.winning_pitcher_losses = 0

        save = game.decision_pitcher_id("save")
        if save is not None:
            self.save_pitcher = game.full_name(save)
            self.save_pitcher_saves = game.pitcher_stat(
                save, "saves", winner_side)
        else:
            self.save_pitcher = None
            self.save_pitcher_saves = None

        loser = game.decision_pitcher_id("loser")
        if loser is not None:
            loser_side = game.losing_team()
            self.losing_pitcher = game.full_name(loser)
            self.losing_pitcher_wins = game.pitcher_stat(
                loser, "wins", loser_side)
            self.losing_pitcher_losses = game.pitcher_stat(
                loser, "losses", loser_side)
        else:
            self.losing_pitcher = PITCHER_UNKNOWN
            self.losing_pitcher_wins = 0
            self.losing_pitcher_losses = 0
Ejemplo n.º 24
0
"""
Root file, calls the main from Game class
"""

import sys
import pygame
from data.game import Game

pygame.init()
game = Game()
game.main()
pygame.quit()
sys.exit()

Ejemplo n.º 25
0
    def __init__(self, game: Game):
        self.away_team = Team(game.away_abbreviation(), game.away_score(),
                              game.away_name(), game.away_hits(),
                              game.away_errors())
        self.home_team = Team(game.home_abbreviation(), game.home_score(),
                              game.home_name(), game.home_hits(),
                              game.home_errors())
        self.inning = Inning(game)
        self.bases = Bases(game)
        self.pitches = Pitches(game)
        self.outs = Outs(game)
        self.game_status = game.status()
        self.atbat = AtBat(game)

        self.note = game.note()

        self.reason = game.reason()

        self.play_result = game.current_play_result()