示例#1
0
def make_walls():
    # get data from google spreadsheet table
    print('Getting data...')
    gst = GoogleSheetTable()
    data = gst.aslist(config['input_table']['spreadsheetid'],
                      config['input_table']['named_range'])

    # filter by scenename in config
    filtered = list(
        filter(lambda v: v['scene'] == config['arena']['scenename'], data))

    # get layout coordinates
    t = Layout(getattr(Layout, config[config['arena']['scenename']]['layout']),
               filtered).get_transforms(
                   **(config[config['arena']['scenename']]['layout_args']))

    # create a lanmarks object; we will add a landmark for each wall
    landmarks = Landmarks()

    for i in range(len(filtered)):
        ldmrk_obj_id = make_wall(
            filtered[i]
            ['id'],  # use id as a suffix for the objects of each wall
            Position(t[i]['x'], t[i]['y'],
                     t[i]['z']),  # position as given by the layout
            Rotation(t[i]['rx'], t[i]['ry'],
                     t[i]['rz']),  # rotation as given by layout
            filtered[i],
            config,
        )
        lbl = f'{filtered[i]["title"][0:50]}'  # cut title if too big and use a landmark label
        if len(filtered[i]["title"]) > 50: lbl = lbl + '...'
        landmarks.push_landmark(ldmrk_obj_id, lbl)  # push landmark to the list

    # add landmark list to scene
    landmarks.add_object(config['arena']['scenename'])

    print('\nDone. Press Ctrl+C to disconnect.')
def min_pin_assignment(layout):
    n_keys = len(layout.keys)

    rows = []

    n_cols = n = int(ceil(sqrt(n_keys)))
    n_rows = m = int(floor(sqrt(n_keys)))

    assert n * m >= n_keys

    keys_by_y = sorted(layout.keys, key=lambda key: key.position.y)

    for i in range(0, n_keys, n_cols):
        rows.append(keys_by_y[i:i + n_cols])

    new_keys = []
    for i, row in enumerate(rows):
        for j, key in enumerate(sorted(row, key=lambda key: key.position.x)):
            new_keys.append(Key(i, j, key.position))

    assert len(new_keys) == n_keys

    return Layout(n_rows, n_cols, new_keys)
示例#3
0
def make_walls():
    # remove old file
    os.remove('comsenter-review-data.json')

    # download data file
    gdd.download_file_from_google_drive(
        file_id='1br58rf4OwvfqQAU3wooncg2kmmsx6QHd',
        dest_path='./comsenter-review-data.json',
        unzip=False)

    with open('./comsenter-review-data.json') as f:
        data = json.load(f)

    p_to_add = []
    for p in data:
        print(p)
        if p['theme'] == theme:
            p_to_add.append(p)

    t = Layout(Layout.ROWCOL, p_to_add).get_transforms(row_dist=20,
                                                       col_dist=20,
                                                       row_off=20,
                                                       col_off=-50)
    #t = Layout(Layout.CIRCLE, p_to_add).get_transforms(radius=50)
    #t = Layout(Layout.SQUARE, p_to_add).get_transforms(length=100)
    #t = Layout(Layout.LINE, p_to_add).get_transforms(length=200)

    landmarks = Landmarks()
    for i in range(len(p_to_add)):
        make_wall(p_to_add[i]['lname'],
                  Position(t[i]['x'], t[i]['y'], t[i]['z']),
                  Rotation(t[i]['rx'], t[i]['ry'], t[i]['rz']), p_to_add[i])
        lbl = f'{p_to_add[i]["lname"]}: {p_to_add[i]["title"]}'
        lbl_cut = f'{lbl[0:50]}...'
        landmarks.push_landmark(f'{p_to_add[i]["lname"]}_img', lbl_cut)

    landmarks.add_object(theme)
示例#4
0
    def __init__(self):
        '''
            Explanation: The initialisation function (constructor). It is called when object of the class is created. Clears the screen and initialises the class variables and creates required objects of other classes

            Class Variables:
                H, W: Height and Width of the terminal
                T: Stores the size of the upper wall
                P_T: Stores the thickness of the paddle
                pattern: Stores the terminal as 2D array, storing each pixel as a character
                tiles: Stores the required relation between HP of bricks and character associated
                release: Stores information regarding whether ball has been released or not from the paddle
                time: Stores the time passed since the game began
                score: Stores the score since the game began
                life: Stores the number of life a player has
        '''
        os.system('clear')
        self.H, self.W = os.popen('stty size', 'r').read().split()
        self.H = int(self.H)
        self.W = int(self.W)
        self.T = Y_WALL
        self.P_T = PADDLE_THICKNESS
        self._layout = Layout(self.H, self.W)
        self.pattern = self._layout.layout()
        self.tiles = self._layout.getTiles()
        self.brick = Brick(self.tiles)
        self.paddle = Paddle(self.H, self.W, self.pattern)
        self.ball = Ball(self.H, self.W, self.pattern)
        self.release = False
        self.one = One(self.tiles)
        self.two = Two(self.tiles)
        self.three = Three(self.tiles)
        self.four = Four(self.tiles)
        self.five = Five(self.tiles)
        self.time = 0
        self.score = 0
        self.life = 1
示例#5
0
def run_game():
    pygame.init()

    FPS = pygame.time.Clock()

    bs_settings = Settings()
    screen = pygame.display.set_mode(
        (bs_settings.screen_width, bs_settings.screen_height))
    pygame.display.set_caption('Battleship')
    #Make the Play button
    #play_button = Button(bs_settings, screen, "Play")
    #Initialize player's field list
    fields = []
    gf.create_game_field_1(bs_settings, screen, fields)
    #Initialize ai's field group
    ai_fields = []
    gf.create_game_field_2(bs_settings, screen, ai_fields)

    buttons = gf.create_buttons(bs_settings, screen)
    ai_gf.draw_ai_ship(bs_settings, screen, ai_fields, buttons)

    layout = Layout(bs_settings, screen, '')

    # Start the main loop for the game
    while True:
        gf.end_game_check(bs_settings, screen, buttons, layout)
        #Player's turn
        if bs_settings.order == 1:
            gf.check_events(bs_settings, screen, fields, ai_fields, buttons)
        #AI's turn
        elif bs_settings.order == -1:
            ai_gf.ai_shoot_action(bs_settings, screen, fields, ai_fields)
        gf.update_screen(bs_settings, screen, fields, ai_fields, buttons,
                         layout)
        #Make FPS = 15
        FPS.tick(15)
 def load(self, url):
     header, body = request.request(url)
     self.tree = HTMLParser(body).parse()
     self.displaylist = Layout(self, self.tree).displaylist
     self.update()
 def update(self, layout=True):
     if layout:
         self.displaylist = Layout(self, self.tree).displaylist
     self.render()
示例#8
0
文件: main.py 项目: UbuntuBudgie/UBpi
Gio.resources_register(resource)
builder = Gtk.Builder.new_from_resource('/org/ubuntubudgie/armconfig/config.ui')
window = builder.get_object("ConfigWindow")
window.show_all()

standardradiobutton = builder.get_object("StandardRadioButton")
compactradiobutton = builder.get_object("CompactRadioButton")
miniradiobutton = builder.get_object("MiniRadioButton")

startlogincheckbutton = builder.get_object("StartLoginCheckButton")
gsettings = Gio.Settings.new('org.ubuntubudgie.armconfig')
startlogincheckbutton.set_active(gsettings.get_boolean('runarmconfig'))
notebook = builder.get_object('ConfigNotebook')
notebook.set_current_page(gsettings.get_int('lastpage'))

layoutstyle = Layout(builder)
overclock = Overclock(builder, args.force_model, model_list)

builder.connect_signals(Handler)
app_statuslabel = builder.get_object("AppStatusLabel")
hint.add(startlogincheckbutton, app_statuslabel, hint.AUTOSTART)

if ((overclock.pi_model is None and not args.force_arm_mode)
        or args.force_findpi_mode):
    findmypi = FindMyPi(builder)
else:
    remote = Remote(builder, overclock)
    display = Display(builder, overclock)

Gtk.main()
示例#9
0
 def setLayout(self,app,ordre):
     self.layout = Layout(app,ordre)
     self.setCentralWidget(self.layout)
 def __init__(self, game_state, logger, server_api):
     """Initialise display surface."""
     self._server_api = server_api
     pygame.init()
     pygame.font.init()
     civ_borders = [
         "civ1_border", "civ2_border", "civ3_border", "civ4_border"
     ]
     self._shutdown = False
     self._threads = []
     self._game_state = game_state
     self._civ_colours = dict(
         (civ, colour)
         for (civ,
              colour) in zip(sorted(self._game_state.civs), civ_borders))
     self._flags = (pygame.DOUBLEBUF | pygame.HWSURFACE)
     self.infoObject = pygame.display.Info()
     self._window_size = (self.infoObject.current_w,
                          self.infoObject.current_h)
     self._camera_position = (self._window_size[0] / 2,
                              self._window_size[1] / 2)
     self._screen = pygame.display.set_mode(self._window_size, self._flags,
                                            0)
     hud_flags = (pygame.HWSURFACE | pygame.SRCALPHA)
     self._hud_surface = pygame.Surface(self._window_size, hud_flags)
     self._hud_quick_surface = pygame.Surface(self._window_size, hud_flags)
     self._font = 'freesansbold.ttf'
     self._font_size = 115
     self._zoom = 30
     self._zoom_interval = 5
     self._min_zoom = 1
     self._max_zoom = 40
     self._hex_size = lambda x: (self.infoObject.current_w // x)
     self._select_menu = SelectMenu(self._screen)
     self._menu_displayed = False
     self._music_player = Music(
         "../resources/music/Egmont_Overture_Op_84.mp3")
     self._music_playing = True
     self._main_menu_options = [("Resume", self.close_main_menu),
                                ("Toggle Music", self.toggle_music),
                                ("Exit", self.quit)]
     self._main_menu = Menu(self._screen, self._main_menu_options)
     self._main_menu_displayed = False
     self._grid = self._game_state.grid
     self._layout = Layout(self._hex_size(
         self._zoom), (self._window_size[0] / 2, self._window_size[1] / 2))
     self._hud = HudOverlay(self._game_state, self._hud_surface,
                            self._hud_quick_surface, self._window_size,
                            self._layout)
     self._load_images = LoadImages()
     self._scaled_terrain_images = \
         self._load_images.load_terrain_images().copy()
     self._scaled_sprite_images = \
         self._load_images.load_sprite_images().copy()
     self._scaled_building_images = \
         self._load_images.load_building_images().copy()
     self._scaled_health_bar_images = \
         self._load_images.load_health_bar_images().copy()
     self._scaled_resource_images = \
         self._load_images.load_resource_images().copy()
     self._currently_selected_object = None
     self._currently_selected_tile = None
     self._current_available_moves = {}
示例#11
0
from layout import Layout

pygame.init()
infoObject = pygame.display.Info()
window = pygame.display.set_mode((infoObject.current_w, infoObject.current_h))


#window = pygame.display.set_mode((800, 600), HWSURFACE | DOUBLEBUF | RESIZABLE)
def calculuteAbsoluteSize(size):
    return ((infoObject.current_w * size[0]) / 100,
            (infoObject.current_w * size[1]) / 100)


running = True
objlist = []
layout = Layout(UPLEFT, window)
objlist.append(
    pnlc.ObjectListBox(0, 10, layout, size=calculuteAbsoluteSize((20, 90))))
selectorArea = pnlc.ObjectListBox(80,
                                  10,
                                  layout,
                                  size=calculuteAbsoluteSize((20, 90)))
objlist.append(selectorArea)
objlist.append(
    pnlc.ObjectListBox(0, 0, layout, size=calculuteAbsoluteSize((100, 5))))

for img in glob.glob("./img/*.png"):
    selectorArea.addImg(img, "text")

print(selectorArea is objlist[1])
print(selectorArea.getobjlist() == objlist[1].getobjlist())
def generateAllStates(
        length,
        ghostNum=1):  #length of all possible spaces. Do not set the ghost num
    allStatesWithoutP = []
    for k in range(0, 4**length):
        layout = util.base10toN(k, 4, length)
        allStatesWithoutP.append(layout)

    allValidStates = []

    for k in allStatesWithoutP:
        zerocount = 0
        for x in range(0, len(k)):
            if k[x] == "0":
                zerocount += 1
        if zerocount == (ghostNum + 1):
            allValidStates.append(k)

    allLayouts = []

    for k in allValidStates:  #hardcoded for only ONE GHOST!!
        tempstring1 = ""
        tempstring2 = ""
        switcher = True
        for x in range(0, len(k)):
            if k[x] == "0":
                if switcher:
                    tempstring1 += "4"
                    tempstring2 += "5"
                else:
                    tempstring1 += "5"
                    tempstring2 += "4"
                switcher = False
            else:
                tempstring1 += k[x]
                tempstring2 += k[x]
        allLayouts.append(tempstring1)
        allLayouts.append(tempstring2)
    for k in range(0, len(allLayouts)):
        state = allLayouts[k]
        newstate = "%"
        for x in range(0, len(state)):
            if state[x] == "1":
                newstate += " "
            elif state[x] == "2":
                newstate += "."
            elif state[x] == "3":
                newstate += "o"
            elif state[x] == "4":
                newstate += "P"
            elif state[x] == "5":
                newstate += "G"
        newstate += "%"
        layouttext = []
        layouttext.append("%" * (length + 2))  #HARDCODE
        layouttext.append(newstate)
        layouttext.append("%" * (length + 2))  #HARDCODE
        allLayouts[k] = layouttext
        #print layouttext

    allStates = []
    for k in range(0, len(allLayouts)):
        layout = Layout(allLayouts[k])
        gameState = GameState()
        gameState.initialize(layout, 1)  #ghost hardcoded
        allStates.append(gameState)
    return allStates
示例#13
0
from turtle import Turtle, Screen
from layout import Layout

import random

is_race_on = False

screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(
    title="Make your bet",
    prompt="Which turtle will win the race? Enter a color: ")

# Create layout
layout = Layout()
layout.draw_end_flag()

# Create Turtles
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
all_turtle = []
y_position = -100

for turtle_index in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.penup()
    new_turtle.goto(x=-230, y=y_position)
    new_turtle.color(colors[turtle_index])

    all_turtle.append(new_turtle)

    y_position += 40
示例#14
0
def test_idempotent_json():
    key = Key(0, 0, Position(1, 1, 1, 1))
    layout = Layout(1, 1, [key])

    assert Layout.from_json(layout.to_json()) == layout
示例#15
0
def main():
    """
    This is a demonstration of global shuffling
    """

    # Sample layouts
    before_layout = xy_slab_layout = Layout(8, (128, 128, 16), GBL_SHAPE)
    after_layout = z_pencil_layout = Layout(8, (64, 32, 128), GBL_SHAPE)

    # MPI initialization
    comm = MPI.COMM_WORLD
    nranks = comm.Get_size()
    assert nranks == before_layout.nranks, "before_layout has the wrong number of ranks"
    assert nranks == after_layout.nranks, "after_layout has the wrong number of ranks"
    rank = comm.Get_rank()

    # We are going to write two sets of BOV files
    sent_writer = BOVWriter('sent', 'sent', rank, nranks,
                            before_layout.gbl_shape, before_layout.shape,
                            GBL_LLF, GBL_TRB)
    received_writer = BOVWriter('received', 'received', rank, nranks,
                                after_layout.gbl_shape, after_layout.shape,
                                GBL_LLF, GBL_TRB)
    expected_writer = BOVWriter('expected', 'expected', rank, nranks,
                                after_layout.gbl_shape, after_layout.shape,
                                GBL_LLF, GBL_TRB)
    returned_writer = BOVWriter('returned', 'returned', rank, nranks,
                                before_layout.gbl_shape, before_layout.shape,
                                GBL_LLF, GBL_TRB)

    # Figure out where this rank is in space, grid-wise and spatially
    before_rank_indices = before_layout.get_rank_indices(rank)
    print(f'{rank}: before_rank_indices: {before_rank_indices}')
    after_rank_indices = after_layout.get_rank_indices(rank)
    print(f'{rank}: after_rank_indices: {after_rank_indices}')
    before_lcl_llf, before_lcl_trb = get_corners(rank, before_layout, GBL_LLF,
                                                 GBL_TRB)
    print(f'{rank}: corners before shuffle: {before_lcl_llf} {before_lcl_trb}')
    after_lcl_llf, after_lcl_trb = get_corners(rank, after_layout, GBL_LLF,
                                               GBL_TRB)
    print(f'{rank}: corners after shuffle: {after_lcl_llf} {after_lcl_trb}')

    # First test: all senders send their own rank.  Do the results go to the right place?
    sendbuf = np.zeros(before_layout.shape, dtype=np.int32)
    sendbuf[:, :, :] = rank
    sent_writer.writeBOV(sendbuf)
    # Perform the swap, and verify that everything ended up on the correct rank
    rcvbuf = shuffle_and_swap(comm, sendbuf, before_layout, after_layout)
    received_writer.writeBOV(rcvbuf)
    expected = np.empty(after_layout.shape, dtype=np.int32)
    for i in range(after_layout.shape[0]):
        for j in range(after_layout.shape[1]):
            for k in range(after_layout.shape[2]):
                gbl_idx = after_layout.lcl_to_gbl(rank, (i, j, k))
                before_rank, before_idx = before_layout.gbl_to_lcl(gbl_idx)
                expected[i, j, k] = before_rank
    print(f'{rank}: done building comparison rank array')
    expected_writer.writeBOV(expected)
    if np.all(rcvbuf == expected):
        print(f'{rank}: source-side rank comparison succeeded')
    else:
        print(f'{rank}: source-side rank comparison failed')
    returnbuf = reverse_shuffle_and_swap(comm, rcvbuf, after_layout,
                                         before_layout)
    if np.all(returnbuf == sendbuf):
        print(f'{rank}: source-side rank return comparison succeeded')
    else:
        print(f'{rank}: source-side rank return comparison failed')
    returned_writer.writeBOV(returnbuf)

    # Second test: for X, Y, and Z in turn, have each sender send the global index of
    # each cell.
    for axis, axisname in enumerate("XYZ"):
        sendbuf = np.empty(before_layout.shape, dtype=np.int32)
        for i in range(before_layout.shape[0]):
            for j in range(before_layout.shape[1]):
                for k in range(before_layout.shape[2]):
                    gbl_idx = before_layout.lcl_to_gbl(rank, (i, j, k))
                    sendbuf[i, j, k] = gbl_idx[axis]
        expected = np.empty(after_layout.shape, dtype=np.int32)
        for i in range(after_layout.shape[0]):
            for j in range(after_layout.shape[1]):
                for k in range(after_layout.shape[2]):
                    gbl_idx = after_layout.lcl_to_gbl(rank, (i, j, k))
                    expected[i, j, k] = gbl_idx[axis]
        rcvbuf = shuffle_and_swap(comm, sendbuf, before_layout, after_layout)
        sent_writer.writeBOV(sendbuf)
        received_writer.writeBOV(rcvbuf)
        expected_writer.writeBOV(expected)
        if np.all(rcvbuf == expected):
            print(f'{rank}: index {axisname} comparison succeeded')
        else:
            print(f'{rank}: index {axisname} comparison failed')
        returnbuf = reverse_shuffle_and_swap(comm, rcvbuf, after_layout,
                                             before_layout)
        if np.all(returnbuf == sendbuf):
            print(f'{rank}: index {axisname} return comparison succeeded')
        else:
            print(f'{rank}: index {axisname} return comparison failed')
        returned_writer.writeBOV(returnbuf)

    # Use a feature in the Layout class that uniquely numbers each cell, and make sure all of the cells
    # end up where expected.  There's no point plotting these because the global addresses don't make
    # much visual sense.
    sendbuf = np.zeros(before_layout.shape, dtype=np.int32)
    sendbuf = before_layout.fill_with_gbl_addr(rank, sendbuf)
    print(f'{rank}: done building global address array')
    rcvbuf = shuffle_and_swap(comm, sendbuf, before_layout, after_layout)
    for_comparison = np.empty(after_layout.shape, dtype=np.int32)
    for_comparison = after_layout.fill_with_gbl_addr(rank, for_comparison)
    if np.all(rcvbuf == for_comparison):
        print(f'{rank}: Global address comparison succeeded')
    else:
        print(f'{rank}: Global address comparison failed :-(')
    returnbuf = reverse_shuffle_and_swap(comm, rcvbuf, after_layout,
                                         before_layout)
    if np.all(returnbuf == sendbuf):
        print(f'{rank}: Global address return comparison succeeded')
    else:
        print(f'{rank}: Global address return comparison failed')
示例#16
0
def test_layout_to_json():
    key = Key(0, 0, Position(1, 1, 1, 1))
    layout = Layout(1, 1, [key])
    assert layout.to_json(sort_keys=True) \
            == '{"cols": 1, "keys": [{"col": 0, "position": {"angle": 1, "width": 1, "x": 1, "y": 1}, "row": 0}], "rows": 1}'
示例#17
0
def build_chart():

    # LAYOUT
    layout = Layout()
    layout.configure(plot_width=1200)

    # TIME WINDOW
    today = date.toordinal(date.today())
    duration = 21
    end = today + duration

    # PLOT
    plot = Plot()
    plot.x = layout.plot.x
    plot.y = layout.plot.y
    plot.width = layout.plot.width
    plot.height = layout.plot.height
    plot.start = today
    plot.finish = end
    plot.clean_dates()
    plot.calculate_resolution()

    # SCALES
    scale = Scale()
    scale.x = layout.scales_top.x
    scale.y = layout.scales_top.y
    scale.width = layout.scales_top.width
    scale.height = layout.scales_top.height / 4
    scale.start = plot.start
    scale.finish = plot.finish
    scale.resolution = plot.resolution
    scale.interval_type = 'days'
    scale.week_start = 0
    scale.min_label_width = 20
    scale.box_fill = 'pink'
    scale.ends = 'yellow'
    scale.label_type = 'd'
    scale.date_format = 'a w'
    scale.separator = '-'
    scale.font_size = 10
    scale.text_x = 10
    scale.text_y = scale.height * 0.65

    # GRID
    grid = Grid()
    grid.interval_type = 'WEEKS'
    grid.week_start = 0
    grid.x = layout.plot.x
    grid.y = layout.plot.y
    grid.height = plot.height
    grid.start = plot.start
    grid.finish = plot.finish
    grid.resolution = plot.resolution
    grid.line_width = 0.5

    # VIEWPORT
    viewport = ViewPort()
    viewport.width = layout.chart.width
    viewport.height = layout.chart.height
    viewport.child_elements = [layout, scale, grid]
    viewport.order_child_elements()
    viewport.render_child_elements()

    return viewport.svg
示例#18
0
ESC_KEY = 27
FRAME_RATE = 5
SLEEP_TIME = 1 / FRAME_RATE

run = True
mode = "tree"

if len(sys.argv) == 1:
    layout_mode = "qwerty"
else:
    if sys.argv[1] == "azerty" or sys.argv[1] == "qwerty":
        layout_mode = sys.argv[1]
    else:
        raise Exception("argument should be 'azerty' or 'qwerty'")

l = Layout(layout_mode)

capture = windowcapture.WindowCapture("Unrailed!", FRAME_RATE, True)
p = printer.Printer(40, l)
p_bot = bot.Bot(l)

print(Fore.WHITE +
      f"""> This project has been made by Flowtter! Thanks for using it !
    keybind:
    F1: Quit
    F2: Pause Bot  
    {l.change}: Change Mode
    {l.ok}: Positive Confirmation
    {l.no}: Negative Confirmation
    {l.random}: Randomize movements
    {l.drop}: Emergency drop Item
示例#19
0
 def build_default_layout(self, form):
     return Layout(*form.fields.keys())
    def __init__(self, filename_base, width, height):
        json = self.__get_config(filename_base)

        # Preferred Teams/Divisions
        self.preferred_teams = json["preferred"]["teams"]
        self.preferred_divisions = json["preferred"]["divisions"]

        # News Ticker
        self.news_ticker_team_offday = json["news_ticker"]["team_offday"]
        self.news_ticker_always_display = json["news_ticker"]["always_display"]
        self.news_ticker_preferred_teams = json["news_ticker"][
            "preferred_teams"]
        self.news_ticker_traderumors = json["news_ticker"]["traderumors"]
        self.news_ticker_mlb_news = json["news_ticker"]["mlb_news"]
        self.news_ticker_countdowns = json["news_ticker"]["countdowns"]
        self.news_ticker_date = json["news_ticker"]["date"]
        self.news_ticker_date_format = json["news_ticker"]["date_format"]

        # Display Standings
        self.standings_team_offday = json["standings"]["team_offday"]
        self.standings_mlb_offday = json["standings"]["mlb_offday"]
        self.standings_always_display = json["standings"]["always_display"]
        self.standings_display_offday = False

        # Rotation
        self.rotation_enabled = json["rotation"]["enabled"]
        self.rotation_scroll_until_finished = json["rotation"][
            "scroll_until_finished"]
        self.rotation_avoid_scrolling_partial_messages = json["rotation"][
            "avoid_scrolling_partial_messages"]
        self.rotation_only_preferred = json["rotation"]["only_preferred"]
        self.rotation_rates = json["rotation"]["rates"]
        self.rotation_preferred_team_live_enabled = json["rotation"][
            "while_preferred_team_live"]["enabled"]
        self.rotation_preferred_team_live_mid_inning = json["rotation"][
            "while_preferred_team_live"]["during_inning_breaks"]

        # Weather
        self.weather_apikey = json["weather"]["apikey"]
        self.weather_location = json["weather"]["location"]
        self.weather_metric_units = json["weather"]["metric_units"]

        # Misc config options
        self.time_format = json["time_format"]
        self.end_of_day = json["end_of_day"]
        self.full_team_names = json["full_team_names"]
        self.debug = json["debug"]
        self.demo_date = json["demo_date"]

        # Make sure the scrolling speed setting is in range so we don't crash
        try:
            self.scrolling_speed = SCROLLING_SPEEDS[json["scrolling_speed"]]
        except:
            debug.warning(
                "Scrolling speed should be an integer between 0 and 6. Using default value of {}"
                .format(DEFAULT_SCROLLING_SPEED))
            self.scrolling_speed = SCROLLING_SPEEDS[DEFAULT_SCROLLING_SPEED]

        # Get the layout info
        json = self.__get_layout(width, height)
        self.layout = Layout(json, width, height)

        # Store color information
        json = self.__get_colors("teams")
        self.team_colors = Color(json)
        json = self.__get_colors("scoreboard")
        self.scoreboard_colors = Color(json)

        # Check the preferred teams and divisions are a list or a string
        self.check_time_format()
        self.check_preferred_teams()
        self.check_preferred_divisions()

        #Check the rotation_rates to make sure it's valid and not silly
        self.check_rotate_rates()
示例#21
0
文件: game.py 项目: DasHache/Pacman
class Game:
    def __init__(self, display):
        self.state = GameState()
        self.display = display

    def run(self):
        self.display.initialize(self.state.data)
        self.display.mainloop()


class GameRules:
    def __init__(self):
        pass

    def newGame(self, layout, display):
        initState = GameState()
        initState.initialize(layout)

        game = Game(display)
        game.state = initState

        return game


layout = Layout('layout/dasha.lay')  #Layout('layout/big.lay')
#layout = Layout('layout/small.lay') #Layout('layout/big.lay')
display = PacmanGraphics()

rules = GameRules()
game = rules.newGame(layout, display)
game.run()
示例#22
0
文件: game.py 项目: ramroll/pacman
    def refresh(self, rnd):
        # rnd = 1000
        state = self.state
        p_set = set()
        RND_NUM = 2000
        if rnd % RND_NUM == 0:

            # 模拟旋转
            # rotate = (random.random())
            layoutText = state.layout.layoutText

            height = len(layoutText)
            width = len(layoutText[0])
            newLayout = []

            # flip-x
            if (rnd // RND_NUM) % 10 in [1, 2, 6, 7]:
                print('flip-x')
                for i in range(height):
                    row = ['' for x in range(width)]
                    for j in range(width):
                        # print(layoutText[i], j)
                        row.append(layoutText[i][-1 - j])
                    newLayout.append(row)
                newLayoutText = [''.join(p) for p in newLayout]
            # flip-y
            if (rnd // RND_NUM) % 10 in [3, 4, 8, 9]:
                print('flip-y')
                for i in range(height):
                    row = ['' for x in range(width)]
                    for j in range(width):
                        row.append(layoutText[-1 - i][j])
                    newLayout.append(row)
                newLayoutText = [''.join(p) for p in newLayout]
            # rotate
            if (rnd // RND_NUM) % 10 in [5, 0]:
                print('rotate')
                for i in range(width):
                    row = ['' for x in range(height)]
                    for j in range(height):
                        row.append(layoutText[j][i])
                    newLayout.append(row)
                newLayoutText = [''.join(p) for p in newLayout]

            # 随机生成pacman和Ghost
            # 豆子和空位置的比例
            ratio = 0.2 + 0.8 * random.random()

            for i in range(len(newLayoutText)):
                for j in range(len(newLayoutText[i])):
                    c = newLayoutText[i][j]
                    r = random.random()
                    if c == '.' or c == ' ' or c == 'o' or c == 'P' or c == 'G':
                        if r < ratio:
                            newLayoutText[i] = newLayoutText[
                                i][:j] + '.' + newLayoutText[i][j + 1:]
                        else:
                            newLayoutText[i] = newLayoutText[
                                i][:j] + ' ' + newLayoutText[i][j + 1:]

            posList = []
            for i in range(len(newLayoutText)):
                for j in range(len(newLayoutText[i])):
                    c = newLayoutText[i][j]
                    if c != '%':
                        posList.append((i, j))

            # print(len(posList), len(self.players))
            capsuleNum = round(random.random() * 2)
            smp = random.sample(posList, len(self.players) + capsuleNum)
            agents = []
            for i in range(len(smp)):
                y, x = smp[i]
                c = ''
                if i < len(self.players):
                    self.players[i].setInitialPos(
                        (x, len(newLayoutText) - y - 1))
                    self.players[i].refresh()

                    if 'refresh' in dir(self.players[i].agent):
                        self.players[i].agent.refresh()
                    c = 'P' if self.players[i].isPacman else 'G'
                    # agents.append(self.players)
                else:
                    c = 'o'

                newLayoutText[
                    y] = newLayoutText[y][:x] + c + newLayoutText[y][x + 1:]
            newLayout = Layout(newLayoutText)
            state.layout = newLayout
            state.refresh()
            print(state)
            # self.initialize(Layout(newLayoutText))

        else:
            for player in self.players:
                player.refresh()
            state.refresh()
示例#23
0
文件: figure.py 项目: jeradf/pyxley
 def __init__(self, url, chart_id):
     self.url = url
     self.chart_id = chart_id
     self.axes = Axes()
     self.graphics = Graphic()
     self.layout = Layout()
示例#24
0
def main(args):
    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)
        
    # Initialize main transport
    transport = get_transport(args.transport, args.path)
    
    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    wallet = Wallet(args.wallet)
    print wallet.struct
    
    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()
    
    # Initialize layout driver
    layout = Layout(buff)
    
    # Startup state machine and switch it to default state
    machine = StateMachine(wallet, layout)

    #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000)
    #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400)
    #layout.show_transactions([tx1, tx2 ], False)
        
    display.refresh()  

    # Main cycle
    while True:
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False
        
        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break
            
        # Handle debug link connection
        msg = debug_transport.read()
        if msg != None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_debug_message(msg)
                if resp != None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True            
                
            '''
            elif isinstance(msg, proto.DebugLinkGetState):
                # Report device state                
                resp = machine.get_state(msg)
                print "Sending debuglink", resp.__class__.__name__, resp
                debug_transport.write(resp)    
            else:
                raise Exception("Got unexpected object %s" % msg.__class__.__name__)
            '''
                
        if button != None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp != None:
                print "Sending", resp
                transport.write(resp)
                
        '''
        if button == True:
            layout.show_transactions([tx1, tx2 ], False)
            layout.show_question_dummy()
            
        if button == False:
            layout.show_logo(logo)
        '''

        # Handle main connection
        msg = transport.read()
        if msg != None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp != None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True            
                
        # Display scrolling
        is_active |= layout.update()
        
        if layout.need_refresh:
            # Update display
            display.refresh()
        
        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)
    
    # Save wallet file
    wallet.save()
    
    # Close transports
    transport.close()
    debug_transport.close()
示例#25
0
from my_keyboard import MyKeyboard
import multiprocessing
from data_manager import DataManager
from train import History
import pygame
from pynput.keyboard import Key, Controller
from layout import Layout

if __name__ == "__main__":
    board = Board()
    keyboard = MyKeyboard()
    history = History()
    [scalar, clf] = pickle.load(open('model/tap.model', 'rb'))
    labels = [None for i in range(20)]
    controller = Controller()
    qwerty = Layout()

    pygame.mixer.init(22050, -16, 2, 64)
    pygame.init()
    sound = pygame.mixer.Sound("sound/type.wav")
    sound.set_volume(1.0)

    while True:
        if keyboard.is_pressed_down('Esc'):
            break

        frame = board.getNewFrame()
        history.updateFrame(frame)
        
        # key_contacts = history.getKeyContact(frame)
        # for contact in key_contacts:
示例#26
0
    def __init__(self,
                 constraints=[],
                 infeasiblePoints=[],
                 feasiblePoints=[],
                 optimalPoint=None,
                 costVector=None,
                 zoom=1.0,
                 frameTime=0.0):
        """
        Create and dispaly a pacman plot figure.
        
        This will draw on the existing pacman window (clearing it first) or create a new one if no window exists.
        
        constraints: list of inequality constraints, where each constraint w1*x + w2*y <= b is represented as a tuple ((w1, w2), b)
        infeasiblePoints (food): list of points where each point is a tuple (x, y)
        feasiblePoints (power): list of points where each point is a tuple (x, y)
        optimalPoint (pacman): optimal point as a tuple (x, y)
        costVector (shading): cost vector represented as a tuple (c1, c2), where cost is c1*x + c2*x
        """
        super(PacmanPlotLP, self).__init__(zoom, frameTime)

        xmin = 100000
        ymin = 100000
        xmax = -100000
        ymax = -100000

        for point in feasiblePoints:
            if point[0] < xmin:
                xmin = point[0]
            if point[0] > xmax:
                xmax = point[0]
            if point[1] < ymin:
                ymin = point[1]
            if point[1] > ymax:
                ymax = point[1]

        if len(feasiblePoints) == 0:
            for point in infeasiblePoints:
                if point[0] < xmin:
                    xmin = point[0]
                if point[0] > xmax:
                    xmax = point[0]
                if point[1] < ymin:
                    ymin = point[1]
                if point[1] > ymax:
                    ymax = point[1]

        xmin = int(math.floor(xmin)) - 3
        ymin = int(math.floor(ymin)) - 3
        xmax = int(math.ceil(xmax)) + 3
        ymax = int(math.ceil(ymax)) + 3
        width = xmax - xmin + 1
        height = ymax - ymin + 1

        #        p = feasiblePoints[2]
        #        print("p={}".format(p))
        #        print("feasible={}".format(self.pointFeasible(p, constraints)))
        #        g = self.cartesianToLayout(xmin, ymin, xmax, ymax, p)
        #        print("g={}".format(g))
        #        gr = (int(round(g[0])), int(round(g[1])))
        #        p2 = self.layoutToCartesian(xmin, ymin, xmax, ymax, gr)
        #        print("p2={}".format(p2))
        #        print("p2 feasible={}".format(self.pointFeasible(p2, constraints)))

        layoutLists = self.blankLayoutLists(width, height)

        self.addInfeasibleGhosts(layoutLists, constraints, xmin, ymin, xmax,
                                 ymax)

        layoutLists = self.changeBorderGhostsToWall(layoutLists)

        for point in infeasiblePoints:
            self.addCartesianPointToLayout(layoutLists, point, '.', xmin, ymin,
                                           xmax, ymax)

        for point in feasiblePoints:
            self.addCartesianPointToLayout(layoutLists, point, 'o', xmin, ymin,
                                           xmax, ymax)

        if optimalPoint is not None:
            self.addCartesianPointToLayout(layoutLists, optimalPoint, 'P',
                                           xmin, ymin, xmax, ymax)

        if graphicsUtils._canvas is not None:
            graphicsUtils.clear_screen()

        # Initialize GameStateData with blank board with axes
        self.width = width
        self.height = height

        self.zoom = min(30.0 / self.width, 20.0 / self.height)
        self.gridSize = graphicsDisplay.DEFAULT_GRID_SIZE * self.zoom

        maxNumGhosts = 10000
        layout = Layout(layoutLists)
        self.blankGameState = GameStateData()
        self.blankGameState.initialize(layout, maxNumGhosts)
        self.initialize(self.blankGameState)
        title = 'Pacman Plot LP'
        graphicsUtils.changeText(self.infoPane.scoreText, title)
        graphicsUtils.refresh()

        if costVector is not None:
            self.shadeCost(layoutLists, constraints, costVector,
                           feasiblePoints, xmin, ymin, xmax, ymax)
示例#27
0
 def add_hex_core(self, r_max_m, theta0_deg=0.0):
     """Add hexagonal lattice to the core"""
     layout = Layout()
     layout.hex_lattice(self.station_diameter_m, r_max_m, theta0_deg)
     self.layouts['hex_core'] = dict(x=layout.x, y=layout.y)
# SNAKE HEALTH SET UP
snake_health = Snake(-40, -40, 0, 0, 10)
snakes_health = pygame.sprite.Group()
snakes_health.add(snake_health)

snake_body_collisions = []

# LEVEL / MENU SETUP (LIST OF LAYOUTS)
menus = (
    Layout("Menu", -40, -40, 1,
        (
            Entity("Panel", 80, 120, 400, 280, 400, 280, True, ("Normal", "Title")),
            Entity("Panel", 520, 40, 40, 40, 400, 440, True, ("Normal", "Normal")),
            Entity("Button", 560, 80, 80, 80, 80, 80, True, ("Level", 1)),
            Entity("Button", 680, 80, 80, 80, 80, 80, True, ("Level", 2)),
            Entity("Button", 800, 80, 80, 80, 80, 80, True, ("Level", 3)),
            Entity("Button", 560, 200, 80, 80, 80, 80, True, ("Level", 4)),
            Entity("Button", 680, 200, 80, 80, 80, 80, True, ("Level", 5)),
            Entity("Button", 800, 200, 80, 80, 80, 80, True, ("Level", 6)),
        )
    ),
    Layout("Menu", -40, -40, 1,
        (
            Entity("Panel", 320, 160, 360, 200, 360, 200, True, ("Normal", "Pause")),
            Entity("Button", 360, 200, 120, 40, 120, 40, True, ("Resume", "Normal")),
            Entity("Button", 360, 240, 120, 40, 120, 40, True, ("Restart", "Normal")),
            Entity("Button", 360, 280, 120, 40, 120, 40, True, ("Exit", "Normal"))
        )
    ),
    Layout("Menu", -40, -40, 1,
        (
示例#29
0
from layout import Layout
from tools import plot_layout, plot_energies

file_paths = ['star.txt', 'square.txt', 'star++.txt', 'dog.txt']

for file_path in file_paths:
    # read the file into your layout class
    layout = Layout(file_path)
    # run the normal layout for 1000 iterations and store the total energies
    energies_normal = layout.layout(1000)
    # plot the normal layout
    plot_layout(layout, '')
    # run the simulated annealing layout for 1000 iterations and store the total energies
    energiesSA = layout.simulated_annealing_layout(1000)
    # plot the simulated annealing layout
    plot_layout(layout, '')
    # plot the total energies of the normal layout and the simulated annealing layout
    plot_energies(energies_normal, '', '')
    plot_energies(energiesSA, '', '')
示例#30
0
def about():
    about = Layout("/static/img/8344_1920_1200.jpg", "Where am I?", "",
                   "site-heading", "span", "about.html", "header_category_box")
    return about.render()