예제 #1
0
def title_handler(self, event):
    """event handler of title"""

    #moves cursor up
    if event.type == KEYDOWN and event.key == K_UP:
        self.title.menu -= 1
        if self.title.menu < 0:
            self.title.menu = 0
    #moves cursor down
    elif event.type == KEYDOWN and event.key == K_DOWN:
        self.title.menu += 1
        if self.title.menu > 2:
            self.title.menu = 2
    #select menu item
    if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_z
                                  or event.key == K_RETURN):
        self.title.music = 0

        if self.title.menu == Title.START:
            self.game_state = CITY
            self.title = None
            self.city = city.City()
            self.new_game = True
        elif self.title.menu == Title.CONTINUE:
            save.load(self, self)
            self.game_state = CITY
            self.title = None
            self.city = city.City()
        elif self.title.menu == Title.END:
            pygame.quit()
            sys.exit()
예제 #2
0
def title_handler(self, event):
    """event handler of title"""

    #moves cursor up
    if event.type == KEYDOWN and event.key == K_UP:
        self.title.menu -= 1
        if self.title.menu < 0:
            self.title.menu = 0
    #moves cursor down
    elif event.type == KEYDOWN and event.key == K_DOWN:
        self.title.menu += 1
        if self.title.menu > 2:
            self.title.menu = 2
    #select menu item
    if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_z
                                  or event.key == K_RETURN):
        self.title.music = 0

        if self.title.menu == Title.START:
            self.game_state = CITY
            self.title = None
            self.city = city.City()
            self.new_game = True
        elif self.title.menu == Title.CONTINUE:
            save.load(self, self)
            self.game_state = CITY
            self.title = None
            self.city = city.City()
        elif self.title.menu == Title.END:
            pygame.quit()
            sys.exit()
예제 #3
0
def load():
    variables['Player'] = ssave.load(s, 'player')
    world.load(ssave.load(s, 'world'))  #load the world
    variables['World'] = world._world
    data = ssave.load(s, 'game')  # retrieve game data
    variables['Game variables']['Current turn'] = data[
        'turn']  # set current turn
    variables['Game variables']['Previous turn'] = data[
        'prev. turn']  # set previous turn
예제 #4
0
    def __load__(cls, d):
        g = cls()

        g.map = load(Map, d['map'], game=g)
        g.players = map(partial(load, Player, game=g), d['players'])
        g.turn = d['turn']
        g.playerIndex = d['playerIndex']
        g.currentPlayer = load(Player, d['currentPlayer'], game=g)
        g.numUnits = len(g.map.units)
        g.numPlayers = len(g.players)

        return g
예제 #5
0
파일: menu.py 프로젝트: amoulis/YATA
def menu(player):
	os.system('cls')
	choice = ""
	while choice != "load" or choice != "play" or choice != "quit":
		choice = input("What do you want to do ?\n play \n load \n rules \n quit \n >>> ")
		player = character.Character()
		if choice == "load":
			save.load(player)
		if choice == "play":
			return;
		elif choice == "quit":
			sys.exit("good bye")
		elif choice == "rules":
			os.system('cls')
			utils.printFile("text/rules")
예제 #6
0
def load_background(resource_path):
    global background
    try:
        background = save.load("str", "logic", 1, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic1.str", resource_path("saves/settings/"), get_language())
        background = "space"
예제 #7
0
def RT_CNN():
    print("Loading model weights from [{}]....".format(c.WEIGHTS_FILE))
    model = vggvox_model()  # Creates a VGGVox model
    model.load_weights(
        c.WEIGHTS_FILE)  # Load the weights of the trained models
    model.summary()  # Print a summary of the loaded model

    print("Loading embeddings from enroll")
    toLoad = load("data/model/RTSP_CNN.out")
    enroll_embs = []
    speakers = []
    for spk, embs in toLoad.items():
        for e in embs:
            enroll_embs.append(e)
            speakers.append(spk)
        print(spk)

    count = 0
    buffer = AudioBuffer()

    start_time = time.time()
    while count < 3:
        count += 1
        buffer.record(chunk_size=c.SAMPLE_RATE)
        data = buffer.get_data()
        data = np.frombuffer(data, 'int16')
    buckets = build_buckets(c.MAX_SEC, c.BUCKET_STEP, c.FRAME_STEP)

    data *= 2**15

    while (len(data) / (c.FRAME_STEP * c.SAMPLE_RATE) < 101):
        data = np.append(data, 0)

    # get FFT spectrum
    data = remove_dc_and_dither(data, c.SAMPLE_RATE)
    data = sigproc.preemphasis(data, coeff=c.PREEMPHASIS_ALPHA)
    frames = sigproc.framesig(data,
                              frame_len=c.FRAME_LEN * c.SAMPLE_RATE,
                              frame_step=c.FRAME_STEP * c.SAMPLE_RATE,
                              winfunc=np.hamming)
    fft = abs(np.fft.fft(frames, n=c.NUM_FFT))
    fft_norm = normalize_frames(fft.T)

    # truncate to max bucket sizes
    rsize = max(k for k in buckets if k <= len(fft_norm.T))
    rstart = int((len(fft_norm.T) - rsize) / 2)
    x = fft_norm[:, rstart:rstart + rsize]

    test_embs = np.squeeze(model.predict(x.reshape(1, *x.shape, 1)))
    distances = []

    for embs in enroll_embs:
        distances.append(euclidean(test_embs, embs))

    print(len(speakers))

    idx = np.argmin(distances)

    print(speakers[idx])
    print("Ok, ", time.time() - start_time - 3, " seconds")
예제 #8
0
def set_writing_color_start(resource_path, number):
    global writing_color_start
    try:
        writing_color_start = save.load("tup", "logiccol", number, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logiccol" + str(number) + ".tup", resource_path("saves/settings/"), get_language())
        writing_color_start = (0, 0, 0)
예제 #9
0
def set_background_color_start(resource_path, number):
    global writing_color_bg
    try:
        writing_color_bg = save.load("tup", "logicbac", number, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logicbac" + str(number) + ".tup", resource_path("saves/settings/"), get_language())
        writing_color_bg = (255, 255, 255)
예제 #10
0
def load_difficulty(resource_path):
    global difficulty
    try:
        difficulty = save.load("str", "logic", 4, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic4.str", resource_path("saves/settings/"), get_language())
        difficulty = "medium"
예제 #11
0
def load_sound_volume(resource_path):
    global sound_volume
    try:
        sound_volume = save.load("flo", "logic", 3, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic3.flo", resource_path("saves/settings/"), get_language())
        sound_volume = 0.4
예제 #12
0
def load_rule(resource_path):
    global rule
    try:
        rule = save.load("int", "logic", 6, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic6.int", resource_path("saves/settings/"), get_language())
        rule = 1
예제 #13
0
def load_language(resource_path):
    global language
    try:
        language = save.load("str", "logic", 5, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic5.str", resource_path("saves/settings/"), "english")
        language = "english"
예제 #14
0
    def load(cls, filename):
        Player.loadedPlayers = {}

        with open(filename) as f:
            d = json.load(f)

        print 'Game loaded.'
        return load(cls, d)
예제 #15
0
def get_stat_val(column, row):
    """
    returns stats value
    :param column: int; column the spot is in
    :param row: int; row the spot is in
    :return: int; stat's value
    """
    if column == 1:  # sum of all values for all difficulties
        value = 0
        for difficulty in DIFFICULTIES:  # goes through difficulties
            value += save.load("int", STATS[row], 1, resource_path,
                               "stats/" + difficulty)  # calculates stat
    else:  # one value
        dif_i = column - 2  # calculates difficulties index
        value = save.load("int", STATS[row], 1, resource_path,
                          "stats/" + DIFFICULTIES[dif_i])  # loads stat
    return value  # returns stat's value
예제 #16
0
def load(save): # load a game
    import traceback
    try:
        global i
        global previ
        global player
        player = s.load(save, 'player') # load the player
        world.load(s.load(save, 'world')) #load the world
        data = s.load(save, 'game') # retrieve game data
        i = data['turn'] # set current turn
        previ = data['prev. turn'] # set previous turn
    except Exception as e:
        print(f''' Something went wrong :(
=========================
Please report this at https://github.com/TBBYT/Turn-Based-Game/issues
Error:''')
        traceback.print_exc()
        input('Press ENTER to quit to title')
예제 #17
0
    def __load__(cls, d, game, tile):
        if d['id'] == 'tank':
            u = Tank()

        u.tile = tile
        u.moves = d['moves']
        u.hp = d['hp']
        u.owner = load(Player, d['owner'], game=game)

        return u
예제 #18
0
 def set_default_pos(self, field_size, resource_path):
     """
     sets ship's position back to default positions not on the board
     """
     # loads default positions
     self.positions = save.load("lis", "ship",
                                self.identification_number - 1,
                                resource_path, "placement/")
     self.direction = DIRECTIONS[0]  # "horizonatlright", default direction
     self.update_rects(field_size)  # updates ship's pygame.Rect objects
예제 #19
0
    def __load__(cls, d, game):
        m = cls()
        game.map = m

        m.tiles = map(lambda x: map(partial(load, Tile, game=game), x), d['tiles'])
        m.metrics = load(Hexagon, d['metrics'])

        for t in m.tiles:
            for r in t:
                for u in r.units:
                    m.units.append(u)

        return m
예제 #20
0
def __init__playfield(load, language, orienation, field_size, field_count_x,
                      field_count_y, resource_path, add_dir):
    """
    creates boards and their tiles as well as writing on boards' side

    when game is loaded, loads boards and their tiles instead

    :param load: bool; game is loaded insted of being newly created
    :param language: str; language all texts are currently displayed in
    :param orienation: str; width/height, depending on what is bigger
    :param field_size: float; size of a virtual field that is determined by the size of the window that inhabits the GUI
    :param field_count_x: int; quantity of tiles on one board in horizontal direction
    :param field_count_y: int; quantity of tiles on one board in vertical direction
    :param resource_path: Func; returns the resource path to a relative path
    :param add_dir: str; additional directory where loaded game is found
    """
    if load:  # saved game is loaded
        global big_fields
        global small_fields
        try:
            big_fields = save.load('lis', 'playfield', 1, resource_path,
                                   add_dir)  # loads both boards
        except FileNotFoundError:
            chat.add_missing_message("playfield1.lis", resource_path("saves/"),
                                     language)
            return True
        try:
            small_fields = save.load('lis', 'playfield', 2, resource_path,
                                     add_dir)  # loads boards' tiles
        except FileNotFoundError:
            chat.add_missing_message("playfield2.lis", resource_path("saves/"),
                                     language)
            return True
    else:  # new game is created
        _create_big_fields(field_size, field_count_x, field_count_y,
                           orienation)  # creates both boards
        _create_small_fields(field_size, orienation)  # creates boards' tiles
    _create_writings(field_size)  # creates writings on the side of the boards
예제 #21
0
def start():
    parser = argparse.ArgumentParser('satori-alarm')
    parser.add_argument('--config', help='Config file')
    parser.add_argument('--log', type=str, default="INFO", help='Config file')
    options = parser.parse_args()

    State.options = options
    State.config = yaml.load(open(options.config).read())

    init_logging(options.log)

    config.refresh()
    config.start_watch()

    State.alarms = main.AlarmDFA()

    save.load()
    save.start_periodically_dump()

    spawn_autorestart(main.process_events)
    spawn_autorestart(main.alarm_tick)

    import restapi
    restapi.serve()
예제 #22
0
def __init__enemy(load,
                  language,
                  resource_path,
                  length_x,
                  length_y,
                  ship_coordinates=[[[0]]],
                  difficulty="easy",
                  ships=[[[0]]],
                  add_dir=""):
    """
    initializes enemy module and enemy's move

    :param load: bool; game is loaded and not newly created
    :param language: str; language all texts are currently displayed in
    :param resource_path: Func; returns a resoucre path to a relative path
    :param length_x: int; board size in x direction
    :param length_y: int; board size in y direction
    :param ship_coordinates: list[list[int, int], ...]; list with all coordiantes inhabiting a ship
    :param difficulty: str; easy/medium/hard/impossible
    :param ships: list[list[list[Ship, ...], ...], ...]; list containing all ships
    :param add_dir: str; additional directory used to save game sfrom different difficulties
    :return: bool or None; loading failed
    """
    global shots
    if load:  # game is laoded
        try:
            shots = save.load('lis', 'enemy', 1, resource_path,
                              add_dir)  # shots are loaded
        except FileNotFoundError:
            chat.add_missing_message("enemy1.lis", resource_path("saves/"),
                                     language)  # adds message to chat
            return True  # interrupts loading and creates new game

    else:  # game is newly created

        shots = [
            [2, 2]
        ]  # sets a start value so that in game function can be more easily readable

        _create_moves_enemy(difficulty=difficulty,
                            field_count=(length_x, length_y),
                            ship_coordinates=ship_coordinates,
                            ships=ships)  # creates enemy's moves
예제 #23
0
def __init__logic(resource_path):
    global win_type
    global aufgabe
    global zustand
    load_language(resource_path)
    try:
        theme_num = save.load('int', 'logic', 7, resource_path, 'settings/')
    except FileNotFoundError:
        chat.add_missing_message("logic7.int", resource_path("saves/settings/"), get_language())
        theme_num = 1
    load_theme(resource_path, theme_num)
    load_background(resource_path)
    load_music_volume(resource_path)
    load_sound_volume(resource_path)
    load_difficulty(resource_path)
    load_rule(resource_path)
    aufgabe = "main"
    zustand = "start"
    win_type = "fullscreen"
    ip.__init__input()
예제 #24
0
    def __load__(cls, d, game):
        t = cls(0, 0, 0, None, loading=True)
        Hexagon.__load__(d, t)

        t.map = game.map
        t.terrain = load(Terrain, d['terrain'])
        t.units = []
        t.unitImages = []
        units = map(partial(load, Unit, game=game, tile=t), d['units'])
        
        poly = QPolygon()
        for p in t.corners:
            poly << QPoint(*p)
        QGraphicsPolygonItem.__init__(t, poly)

        t.setBrush(QBrush(t.terrain.image))
        t.setPen(QPen())

        for unit in units:
            t.addUnit(unit)

        return t
예제 #25
0
def update_stats(games, won, lost, moves, hit, destroyed, time_spent):
    """
    updates stats when stats are looked up ore game is closed

    :param games: int; games played since stats have been updated
    :param won: int; games won since stats have been updated
    :param lost: int; games lost since stats have been updated
    :param moves: int; moves done since stats have been updated
    :param hit: int; ships hit since stats have been updated
    :param destroyed: int; ships destroyed since stats have been updated
    :param time_spent: int; time spent since stats have been updated in minutes
    """
    stat_vals = [games, won, lost, time_spent, moves, hit,
                 destroyed]  # new stats
    count = 0
    for difficulty in DIFFICULTIES:  # goes through all difficulties
        for i in range(7):  # goes through all stats
            stat_val = save.load("int", STATS[i], 1, resource_path,
                                 "stats/" + difficulty)  # loads stat's value
            stat_val += stat_vals[i][count]  # adds new value
            save.save(stat_val, "int", STATS[i], 1, resource_path,
                      "stats/" + difficulty)  # saves updated value
        count += 1
예제 #26
0
def __init__player(load, resource_path, language, add_dir):
    """
    initializes player and its required lists to check for doublicating inputs

    :param load: bool; whether the game is loaded or newly created
    :param resource_path: Func; returns the resource path to a relative path
    :param language: str; lnguage all texts are currently displayed in
    :param add_dir: str; additional directory where loaded game is found
    """
    global hit_list
    global feld
    global done_clicks
    feld = [-1, -1]  # creates a list that contains the currently clicked field with a control value
    done_clicks = [[0, 0]]  # creates control to undo clicks when another field is clicked instead
    if load:
        # loads control for already targeted fields
        try:
            hit_list = save.load('lis', 'player', 1, resource_path, add_dir)
        except FileNotFoundError:
            chat.add_missing_message("player1.lis", resource_path("saves/"), language)
            return True
    else:
        # creates control for already targeted fields
        hit_list = [[0 for _ in range(10)] for _ in range(10)]
예제 #27
0
import time

try:
    import colorama
except:
    print("You need the colorama module! (python -m pip install colorama)")
    sysModule.exit()

sysModule.path.insert(1, './imports')
import utils, terminal, system, commands, save
system.init(system)
colorama.init()

from colorama import Fore

sysCont = save.load()
if not sysCont:
    sysCont = system.SystemsController()
#If user broke their system then quit
bootPath = system.FilePath('/sys/boot.sys', sysCont.userSystem.fileSystem,
                           True, system.sysFileHashes['boot.sys'])
if bootPath.status != system.PathStatuses.PATH_VALID:
    sysCont.userSystem.status = system.Statuses.UNBOOTABLE
comCont = commands.CommandController()

terminal = terminal.Terminal(comCont)
terminal.out(colorama.Style.BRIGHT, colorama.Fore.GREEN, False, False)

if 'idlelib.run' in sysModule.modules:
    print("You probably want to run this from the command line.")
else:
예제 #28
0
"""
예제 #29
0
def set_ships(load,
              resource_path,
              language,
              add_dir,
              field_size,
              random_placement=True,
              normal=False):
    """
    creates ships as Ship, in a way that the player's ships are in ship[0] and the enemy's ships are in ship[1]
    and places all ships on random locations on the playfield

    Ship is a ship that can be hit, located on the playfield and shown in the GUI

    used once in the beginning of the game

    :param load: bool; whether game is loaded or a new one is created
    :param resource_path: Func; returns the resource_path to a relative_path
    :param language: str; language all texts are currently displayed in
    :param add_dir: str; additional directory where loaded game is found
    :param field_size: float; size of one virtual field
    :param normal: ships are set by the player
    :param random_placement: bool; ships are placed randomly and not by the player
    """
    global ship
    if load:  # game is loaded
        try:
            ship = save.load('lis', 'ship', 1, resource_path,
                             add_dir)  # loads ships
        except FileNotFoundError:  # ships file has not been found
            chat.add_missing_message("ship1.lis", resource_path("saves/"),
                                     language)  # adds message to chat
            return True  # interrupts loading and creates new game
    elif normal:
        _set_rand_pos(True)
    else:  # game is newly created
        ship = []  # creates list later holding all ships
        for i in range(2):  # creates individual list for each palyer
            ship.append([])
            for j in range(ship_count):  # goes through number of ships
                ship[i].append(0)
            # creates ten ships for each player that are intact, but are not yet located anywhere on the playfield
            for j in range(
                    4
            ):  # creates four ships as FisherShip2, a Ship with two segments
                ship[i][j] = Ship([[-1, -1, 3], [-1, -1, 3]],
                                  identification_number=j + 1,
                                  player=i,
                                  color=(255, 50 * j, 255),
                                  length=2,
                                  field_size=field_size)
            for j in range(
                    3
            ):  # creates three ships as FisherShip2, a Ship with three segments
                d = j + 4
                ship[i][d] = Ship([[-1, -1, 3], [-1, -1, 3], [-1, -1, 3]],
                                  identification_number=d + 1,
                                  player=i,
                                  color=(50 * j, 100, 255),
                                  length=3,
                                  field_size=field_size)
            # creates two ships as ContainerShip4, a Ship with four segments
            ship[i][7] = Ship(
                [[-1, -1, 3], [-1, -1, 3], [-1, -1, 3], [-1, -1, 3]],
                identification_number=8,
                player=i,
                color=(100, 255, 50),
                length=4,
                field_size=field_size)
            ship[i][8] = Ship(
                [[-1, -1, 3], [-1, -1, 3], [-1, -1, 3], [-1, -1, 3]],
                identification_number=9,
                player=i,
                color=(100, 255, 100),
                length=4,
                field_size=field_size)
            # creates one ship as Kreuzer5, a ship wih five segments
            ship[i][9] = Ship([[-1, -1, 3], [-1, -1, 3], [-1, -1, 3],
                               [-1, -1, 3], [-1, -1, 3]],
                              identification_number=10,
                              player=i,
                              color=(255, 100, 0),
                              length=5,
                              field_size=field_size)
        if random_placement:
            _set_rand_pos()  # sets all ships to random positions
        else:
            _set_default_pos(field_size, resource_path)
예제 #30
0
파일: match.py 프로젝트: kuitang/topicmatch
    G = nx.complete_graph(N)
    for i, j in G.edges():
        # Negate the distance, since we are solving maximum-weight problem.
        G[i][j]['weight'] = -symmetric_smooth_kl(vecs[i], vecs[j])

    return G


def compute_weight(G, match):
    return sum(G[i][j]['weight'] for i, j in match.iteritems())


if __name__ == "__main__":
    args = docopt(__doc__)

    d = save.load(args['<datafile>'])
    lda = gensim.models.ldamodel.LdaModel.load(args['<modelfile>'])
    K = lda.num_topics

    # Obtain the posterior topic distribution for each document.
    sparse_vecs = [lda[doc] for doc in d['corpus']]
    # Convert to dense vectors so that we can compute KL divergences.
    dense_vecs = [densify(v, K) for v in sparse_vecs]

    G = make_matching_graph(dense_vecs)

    # Find the maximum-weight (minimum-distance) matching
    # *among the max-cardinality matchings*. This ensures that as many
    # papers are matched as possible.

    print("About the run matching. This could take a while.")
예제 #31
0
파일: match.py 프로젝트: kuitang/topicmatch
def make_matching_graph(vecs):
    N = len(vecs)
    G = nx.complete_graph(N)
    for i, j in G.edges():
        # Negate the distance, since we are solving maximum-weight problem.
        G[i][j]['weight'] = -symmetric_smooth_kl(vecs[i], vecs[j])

    return G

def compute_weight(G, match):
    return sum(G[i][j]['weight'] for i, j in match.iteritems())

if __name__ == "__main__":
    args = docopt(__doc__)

    d = save.load(args['<datafile>'])
    lda = gensim.models.ldamodel.LdaModel.load(args['<modelfile>'])
    K = lda.num_topics

    # Obtain the posterior topic distribution for each document.
    sparse_vecs   = [ lda[doc] for doc in d['corpus'] ]
    # Convert to dense vectors so that we can compute KL divergences.
    dense_vecs    = [ densify(v, K) for v in sparse_vecs ]

    G = make_matching_graph(dense_vecs)

    # Find the maximum-weight (minimum-distance) matching
    # *among the max-cardinality matchings*. This ensures that as many
    # papers are matched as possible.

    print("About the run matching. This could take a while.")
예제 #32
0
def main():

    #Init the variables
    game = Board.game()
    black = game.P2
    white = game.P1
    current = white

    turn = 0
    G = save.load()

    mat = False
    pat = False

    while (not mat and not pat):

        Board.display_board(game.board)
        position = []
        piece = None
        eaten_piece = None

        #tour de l 'ia
        if (turn == black):

            (_, a) = G[turn].linked_black[0]
            maxi = a
            for ut in range(1, len(G[turn].linked_black)):
                (_, a) = G[turn].linked_black[ut]
                test = a
                if (test > maxi):
                    maxi = test

            game.board = G[maxi].board

            current += 1

        #tour du joueur
        else:

            #Prends la nom de la pièce que l'on veut bouger. Recommence tant que le nom n'est pas valide
            while position == []:
                piece_name = input("Which piece you wanna move?")
                for p in current.pieces:
                    if (p.name == piece_name):
                        position = p.possible_moves(game)
                        piece = p
                        break
                if (position == []):
                    print(
                        "This piece doesn't exist or had been lost or it can't move. Please enter a correct name !"
                    )

            print("Here is your possible moves")
            for e in position:

                f = chr(65 + e // 8) + str(e % 8 + 1)
                print(f)

            isinputmove = False
            while not isinputmove:
                strpos = input("Please enter the move that you want !")
                indexpos = (((ord(strpos[0])) - 65) * 8) + int(strpos[1]) - 1

                for e in position:
                    if e == indexpos:
                        isinputmove = True
                        break

                if isinputmove == False:
                    print(
                        "This position doesn't exist, please enter a good one !"
                    )
                    for e in position:
                        f = chr(65 + e // 8) + str(e % 8 + 1)
                        print(f)

            #find out if there is any pieceto eat
            if (game.board[indexpos]):
                eaten_piece = game.board[indexpos]

            #Move the current piece
            game.board[piece.position] = None
            piece.position = indexpos
            game.board[piece.position] = piece

            if (current == white):
                current = black
            else:
                current = white
            if (eaten_piece):
                current.pieces.remove(eaten_piece)

        # check mat
        if (game.P1.pieces == [] or game.P2.pieces == []):
            mat = True
예제 #33
0
import urllib.request, json
import datetime
from item import item
from save import save
from save import load
from userInterface import userInterface
import threading
from watchingItems import watchingItems

import os
clear = lambda: os.system('cls')

clear()
print('starting up')
#watchingItems = ['Dragon hunter crossbow', "Zulrah's scales", 'Twisted bow']
watchingItemsPrice = load()
if watchingItemsPrice == []:
    for thing in watchingItems:
        tempItem = item(thing)
        watchingItemsPrice.append(tempItem)
if len(watchingItemsPrice) < len(watchingItems):
    for item1 in watchingItems:
        foundItem = False
        for item2 in watchingItemsPrice:
            if item2.name == item1:
                foundItem = True
                break
        if not (foundItem):
            watchingItemsPrice.append(item(item1))

completeItemList = []
예제 #34
0
def game_loop():
    screen = settings.screen
    b_surf = screen.subsurface((5, 200), (400, 275))
    p_surf = screen.subsurface((5, 5), (350, 190))
    m_surf = screen.subsurface((360, 5), (240, 120))
    pet_surf = screen.subsurface((360, 130), (240, 65))
    fashu_surf = screen.subsurface((410, 200), (190, 100))
    count_surf = screen.subsurface((410, 305), (190, 170))
    toolbar_surf = screen.subsurface((605, 5), (190, 470))
    cangku_surf = screen.subsurface((5, 5), (595, 470))
    pet_cangku_surf = screen.subsurface((5, 5), (595, 470))
    hecheng_surf = screen.subsurface((5, 5), (595, 470))
    ronghe_surf = screen.subsurface((5, 5), (595, 470))
    fuwen_surf = screen.subsurface((5, 5), (595, 470))
    lianbao_surf = screen.subsurface((5, 5), (595, 470))
    xiulian_surf = screen.subsurface((5, 5), (790, 470))
    set_surf = screen.subsurface((5, 5), (790, 470))
    show_equip_surf = screen.subsurface((5, 5), (790, 470))
    player_detail_surf = screen.subsurface((5, 5), (790, 470))
    login_surf = screen.subsurface((5, 5), (790, 470))
    ditu = settings.ditu
    if settings.use_load:
        if settings.link_load:
            screen.blit(waiting_pic, (0, 0))
            pygame.display.update()
            url_data = link.load_online()
            if url_data:
                a_p, time_n, battle_n, use_money = url_data
                p = a_p
            else:
                settings.game_stage = 'start'
                settings.use_load = False
                settings.link_load = False
                return
        else:
            p = save.load()
        settings.battle_set = p.battle_set.copy()
        p.game_version = settings.VERSION
        p.enemys = []
        p.attack_all = []
        p.attacking = None
        p.defending = None
        p.jisuan_shuxin()
        if str(p.place.__class__) == 'codes.place.Fuben':
            place.change_place(place.changan, p)
            settings.in_fuben = False
        if p.place.name == u'\u901a\u5929\u5854':
            place.change_place(place.changan, p)
            settings.in_ttt = False
        if settings.link_load:
            if p.place.name != u'\u957f\u5b89':
                for i in range(battle_n):
                    battle.battle(p)

            functions.msg(u'\u53d6\u56de\u6210\u529f\uff0c\u6302\u673a\u65f6\u957f' + link.count_guaji_time(time_n), settings.FPS * 10)
            functions.msg(u'\u6263\u9664\u70b9\u6570\uff1a%s \u70b9' % unicode(use_money), settings.FPS * 10)
            settings.bc_base_time -= time_n
    else:
        if settings.rw_select[3] == u'\u4eba\u65cf':
            p = player.Zhongzu_Ren(settings.rw_select)
        elif settings.rw_select[3] == u'\u9b54\u65cf':
            p = player.Zhongzu_Mo(settings.rw_select)
        else:
            p = player.Zhongzu_Xian(settings.rw_select)
        with file('yourname.txt', 'r') as f:
            name = unicode(f.readline(), 'gbk')[:10].strip()
            if name != u'':
                p.name = name
        p.place = place.Place(place.place_data_list[0])
        w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)])
        while w.type not in p.adept_weapons:
            w = equip.Weapon(equip.weapon_list_0[random.randint(0, 11)])

        w.get_pr()
        w.get(p)
        w.equip()
        for i in range(15):
            ch = random.choice(random.choice(p.place.spoils))
            exec 'e = equip.%s(ch)' % settings.equip_list[ch[1]]
            e.get_pr()
            e.get(p)
            e.equip()

        cl_list = ['shuiyuezhi',
         'liuyanhuo',
         'xuanminshi',
         'honglianshengquan',
         'zichengtie',
         'xuanyebin',
         'cangleijinshi',
         'bixinsha']
        random.shuffle(cl_list)
        cl_use = cl_list[:4]
        for i in cl_use:
            cl = fabao.Fabao_Cailiao(i)
            cl.get(p)

        pet = monster.Pet(monster.monsters_dict['yefendanqi'], p)
        p.pet_bag.append(pet)
        pet = monster.Pet(monster.monsters_dict['boji'], p)
        p.pet_bag.append(pet)
        p.add_kucun_exp(10000)
        if settings.TEST:
            p.add_exp(5000000000L)
            p.money = enc.en(5000000000L)
            p.shengli = enc.en(100000)
            p.get_skill('weiguanzhidao')
            p.get_skill('xunshouzhidao')
            for i in range(4):
                g = goods.BB_Skill_Forget_Book()
                g.get(p)

            g = goods.MoonStone()
            g.get(p)
            for i in range(2):
                fw = goods.Fuwen_suipian()
                fw.get(p)

            for i in range(60):
                pet = monster.Pet(monster.monsters_dict[random.choice(p.place.monsters)], p)
                p.pet_bag.append(pet)

    draw_init.draw_init(p)
    if settings.battle_set['4beijiasu']:
        pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE_SHORT)
    else:
        pygame.time.set_timer(settings.EVT_BATTLE, settings.TIME_BATTLE)
    pygame.time.set_timer(EVT_SAVE, TIME_SAVE)
    pygame.time.set_timer(EVT_SAVE_2, TIME_SAVE_2)
    b_surf.blit(settings.b_surf_init, (0, 0))
    settings.bt_surf = b_surf.copy()
    while settings.game_stage == 'game':
        for event in gui.setEvents(pygame.event.get()):
            if event.type == QUIT:
                pygame.quit()
                exit()
            if event.type == MOUSEBUTTONUP:
                settings.mouse.click = True
                settings.mouse.button = event.button
            if event.type == EVT_BATTLE:
                check = [settings.map_open,
                 settings.cangku_open,
                 settings.hecheng_open,
                 settings.xiulian_open,
                 settings.ronghe_open,
                 settings.set_open,
                 settings.fuwen_open,
                 settings.lianbao_open]
                if True not in check:
                    if p.place.name != u'\u957f\u5b89':
                        battle.battle(p)
                    else:
                        battle.stay_in_changan(p)
                    if pygame.display.get_active():
                        draw.b_draw_surf(b_surf)
            if event.type == EVT_SAVE:
                save.save(p)
            if event.type == EVT_SAVE_2:
                save.save_2(p)

        screen.fill(GRAY)
        if pygame.display.get_active():
            if settings.map_open:
                draw.map_open(ditu, p)
            elif settings.cangku_open:
                draw.cangku_open(p, cangku_surf)
                draw.cangku_bag_draw_surf(p, toolbar_surf)
            elif settings.pet_cangku_open:
                draw.pet_cangku_open(p, pet_cangku_surf)
                draw.pet_cangku_bag_draw_surf(p, toolbar_surf)
            elif settings.hecheng_open:
                draw.hecheng_open(p, hecheng_surf)
                draw.hecheng_bag_draw_surf(p, toolbar_surf)
            elif settings.ronghe_open:
                draw.ronghe_open(p, ronghe_surf)
                draw.ronghe_pet_bag_draw_surf(p, toolbar_surf)
            elif settings.xiulian_open:
                draw.xiulian_open(p, xiulian_surf)
            elif settings.fuwen_open:
                draw.fuwen_open(p, fuwen_surf)
                draw.fuwen_bag_draw_surf(p, toolbar_surf)
            elif settings.lianbao_open:
                draw.lianbao_open(p, lianbao_surf)
                draw.lianbao_bag_draw_surf(p, toolbar_surf)
            elif settings.set_open:
                draw.set_open(p, set_surf)
            elif settings.show_equip_open:
                draw.show_equip_open(p, show_equip_surf)
            elif settings.player_detail_open:
                draw.player_detail_open(p, login_surf)
            elif settings.login_open:
                draw.login_open(p, login_surf)
            else:
                draw.bt_draw_surf(b_surf)
                draw.p_draw_surf(p, p_surf)
                draw.m_draw_surf(p, m_surf, settings.font_14)
                draw.pet_draw_surf(p, pet_surf, settings.font_14)
                draw.fashu_draw_surf(p, fashu_surf)
                draw.count_draw_surf(p, count_surf)
                draw.toolbar_draw_surf(p, toolbar_surf)
                draw.detect_mouse(p)
            draw.message_draw_surf()
            settings.mouse.fresh()
        settings.clock.tick(settings.FPS)
        pygame.display.update()

    return
예제 #35
0
                G2, boundary_nodes_out, boundary_nodes_in, boundary_edges)
    Sv.save_config(dirname + '/' + 'config', n, geo, nettype, F0, F1, z0, z1,
                   F_mult, dt, c1, c2, l, mu, qin, presout, D, Dv, k, dth,
                   F0_ox, F1_ox, z0_ox, z1_ox, F_mult_ox, dt_ox,
                   length_wiggle_param, noise)

elif load == 1:
    from config import nettype, geo, load_name
    #dirname = nettype + geo + str(n)+"/"+load_name
    dirname = load_name
    (G, boundary_edges, n, F0, F1, z0, z1, F_mult, dt, c1, c2, l, mu, qin,
     presout, D, Dv, k, dth, F0_ox, F1_ox, z0_ox, z1_ox, F_mult_ox, dt_ox,
     old_iters, in_nodes, out_nodes, reg_nodes, other_nodes,
     boundary_nodes_out, boundary_nodes_in, in_nodes_ox, out_nodes_ox,
     oxresult, in_edges, reg_reg_edges, reg_something_edges,
     other_edges) = Sv.load(dirname + "/save")
    nkw = n**2

else:
    from config import (F0, F1, z0, z1, F_mult, dt, c1, c2, mu, qin, presout,
                        D, Dv, k, dth, F0_ox, F1_ox, z0_ox, z1_ox, F_mult_ox,
                        dt_ox, load_name)
    (G, boundary_edges, n, _, _, _, _, _, _, _, _, l, _, _, _, _, _, _, _, _,
     _, _, _, _, _, _, in_nodes, out_nodes, reg_nodes, other_nodes,
     boundary_nodes_out, boundary_nodes_in, in_nodes_ox, out_nodes_ox,
     oxresult, in_edges, reg_reg_edges, reg_something_edges,
     other_edges) = Sv.load('templatki/' + load_name)

    dirname = nettype + geo + str(n) + load_name
    if not os.path.isdir(dirname):
        os.makedirs(dirname)
예제 #36
0
def game_loop(file, state):
    # 게임을 플레이
    if not state:
        quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check, score = initGame()
    else:
        quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check = load(file)
        times,score=get_game_info()
        print ('Start game')
        print ('Length of word is', length)
        print("Score: " + str(score))
        word_bool(length, slice_word, check)

        print("||", end='')
        for i in range(0,mistake):
            print(mistake_sign[i], end="")
        print("\n" + 'Already input Alphabet: ', already_input_alph)
        print("Already input Words: ", already_input_word)

        state=False
    Bool=True

    while Bool:
        print("1. Main Menu")
        input_alph = input("Alphabet or Word(No a capital letter): ")
        if len(input_alph) > 1:
            already_input_word.append(input_alph)
            if quiz_word==input_alph:
                print("Congratulations! You Win! ")
                Bool=False
            else:
                print("Sorry. That's wrong. ")
                print("Score: " + str(score))
                mistake = mistake+1
                check, check_bool = checkExistence(slice_word, input_alph, check)
                word_bool(length,slice_word,check)

        elif input_alph == "1":
            save(quiz_word, mistake, check, already_input_word, already_input_alph)
            break

        else:
            already_input_alph.append(input_alph)
            print("Score: " + str(score))
            check, check_bool = checkExistence(slice_word, input_alph, check)
            word_bool(length,slice_word,check)
            if not check_bool:
                mistake += 1

        if np.sum(check==1) == length:
            print("Congratulations! You Win! ")
            Bool=False

        if mistake==6:
            print("Sorry. You lose. Answer is " + quiz_word)
            Bool=False

        if Bool==True:
            print("||", end='')
            for i in range(0,mistake):
                print(mistake_sign[i], end="")
            print("\n" + 'Already input Alphabet: ', already_input_alph)
            print("Already input Words: ", already_input_word)

        if Bool==False:
            # 게임 정보 불러오기.
            times, score = get_game_info()
            new_score = count_score(score, mistake, quiz_word, already_input_alph)


            # 게임 정보 쓰기.
            set_game_info(times, new_score)

            print("Countiune:1    Menu:2     End:3")
            user_choice=int(input("Choice: "))

            if user_choice==1:
                Bool=True
                quiz_word, slice_word, length, life, mistake, already_input_alph, already_input_word, check, score = initGame()
            elif user_choice==3:
                print("Bye~")
                time.sleep(2)
                sys.exit()
예제 #37
0
 def load(self):
     save.load(self.mainLayout)