Beispiel #1
0
def setup(sk):
    # Load image originals
    fldr = resolvePath("img", __file__)
    sk.imgs = [
        Image("{}/{}.png".format(fldr, f))
        for f in ("target", "paper", "scissors")
    ]

    # Create button controls and add images to buttons
    w, h = sk.size
    x = w / 4 - 44
    for img in sk.imgs:
        btn = Button((40, 40), 2).config(anchor=BOTTOM, pos=(x, h - 4))
        btn += Image(img).config(pos=btn.center, height=32)
        sk += btn.bind(onclick)  # Bind event handlers
        x += 44

    # Initialize scores to zero
    font = {"font": Font.mono(), "fontSize": 40, "fontStyle": BOLD}
    sk["Score1"] = Text(0).config(color="red",
                                  anchor=TOPLEFT,
                                  pos=(4, 4),
                                  **font)
    sk["Score2"] = Text(0).config(color="blue",
                                  anchor=TOPRIGHT,
                                  pos=(w - 4, 4),
                                  **font)

    # Create status text
    sk["Status"] = Text("Make a choice!").config(pos=(0.75 * w, h - 24),
                                                 font=Font.sans(),
                                                 fontSize=32,
                                                 color="red")
Beispiel #2
0
def setup(sk):
    "Add all content to the sketch"

    # Add text to the sketch
    font = {"font": Font.mono(), "fontStyle": BOLD}
    sk["Score"] = Text(0).config(anchor=TOPLEFT, color="red", **font)
    text = "Pummel the Chimp, and Win $$$"
    sk += Text(text).config(pos=(sk.width - 1, 0), anchor=TOPRIGHT,
                            **font).config(width=0.75 * sk.width)

    # Add fist
    folder = resolvePath("examples/data", pygame.__file__) + "/"
    img = loadImage(folder + "fist.bmp")
    sk += Image(img).config(pos=sk.center, anchor=TOP).bind(ondraw)

    # Add chimp sprite
    img = loadImage(folder + "chimp.bmp")
    sk["Chimp"] = Sprite(img).config(pos=(48, 48), vel=(10, 0),
                                     bounce=BOTH).bind(ondraw=chimpDraw)

    # Load audio files
    audio = "punch.wav", "whiff.wav"
    sk.sounds = [pygame.mixer.Sound(folder + f) for f in audio]

    # Bind click event handler; hide cursor
    sk.bind(onmousedown)
    sk.cursor = False
Beispiel #3
0
    def __init__(self,
                 text,
                 userInput=None,
                 buttons=None,
                 title=None,
                 size=(1, 1),
                 inputWidth=None,
                 **kwargs):
        super().__init__(size)
        self.command = None

        # Text options
        txtConfig = {"font": Font.sans(), "fontSize": 15}
        txtConfig.update(kwargs)

        # Compose button text
        if buttons is None:
            buttons = ["Okay", "Cancel"]
        elif type(buttons) is str:
            buttons = buttons,
        if len(buttons) > 2: buttons = buttons[:2]

        # Add buttons
        bSize = None
        icon = True
        for t in buttons:
            t = Text(t).config(**txtConfig)
            if not bSize: bSize = 0, t.height + 12
            name = "Button_{}".format(t.data)
            self[name] = Button(bSize, 2).textIcon(t,
                                                   icon).config(anchor=BOTTOM)
            icon = not icon
        self.buttons = self[:len(buttons)]
        for b in self.buttons:
            b.bind(onaction=_btnClick)

        # Add text label and text input
        self["Text"] = text = Text(text).config(anchor=TOP, **txtConfig)
        if userInput is None and isinstance(self, NumInputBox):
            userInput = ""
        if userInput is not None:
            if inputWidth and inputWidth < text.width:
                inputWidth = text.width
            self["Input"] = TextInputCanvas(inputWidth, userInput,
                                            "Click to enter your response",
                                            **txtConfig).config(anchor=TOP,
                                                                bg="white")
            self["Input"].ti.config(blurAction=False,
                                    mb=self).bind(onaction=_tiAction)

        # Position controls and add title bar
        self._arrange().config(bg="#f0f0f0", weight=2, border="blue")
        if title: self.title(title, **txtConfig)
Beispiel #4
0
def _title(cv, title, font, folders):
    "Add graph or axis titles"
    if "text" in title:
        gr = Text(title["text"]).config(**font)
    else:  # TODO: Pass image rather than text
        gr = Image(title["image"].format(**folders))
    if gr:
        gr.setCanvas(cv).config(role="title", **title.get("config", {}))
    return gr
Beispiel #5
0
 def setup(self):
     self.caption = "sc8pr Video Converter"
     self.menu()
     attr = dict(anchor=BOTTOMRIGHT,
                 color="red",
                 bg="#a0a0a080",
                 font=Font.mono(),
                 fontSize=18)
     self["Text"] = Text().config(pos=(self.width - 4, self.height - 4),
                                  **attr)
Beispiel #6
0
 def _item(btn, data, padding):
     h = btn.height - 2 * padding
     y = padding + h / 2
     x = h + padding * (2 if h else 1)
     if type(data) is str: data = data, None, None
     text, left, right = [Text(d) if type(d) is str else d for d in data]
     if text: btn += text.config(anchor=LEFT, pos=(x, y))
     if left: btn += left.config(pos=(y, y), height=h)
     x = btn.width - padding
     if right:
         if right == R_TRIANGLE: right = Menu.triangle()
         btn += right.config(anchor=RIGHT, pos=(x, y), height=h)
Beispiel #7
0
 def click(cv, ev):
     m = modKeys()
     if m & 4:
         font = dict(font=Font.sans(), color="red", fontSize=18)
         i = 0
         fn = "vector{}.png"
         while os.path.exists(fn.format(i)): i += 1
         fn = fn.format(i)
         cv.save(fn).removeItems("Saved")
         cv["Saved"] = Text("Saved as '{}'".format(fn)).config(anchor=TOP, pos=(cv.center[0], 8), **font)
     elif m & 1: cv.remove()
     else: cv.config(layer=-1)
Beispiel #8
0
 def __init__(self, scale=10, size=50, step=5, unit=("cm", 2), **cfg):
     if "bg" not in cfg: cfg["bg"] = Image(bg="#e0e0f0a0")
     if "weight" not in cfg: cfg["weight"] = 1
     coord = lambda x: (x + 1) * scale
     h = 3.5 * scale
     super().__init__((coord(size + 1), h))
     self.config(**cfg)
     x = 0
     cfg = dict(anchor=BOTTOM, font=MONO, fontStyle=BOLD, color="#000000a0")
     while x <= size:
         self += Text(x).config(pos=(coord(x), h - 1), **cfg)
         x += step
     if unit:
         self += Text(unit[0]).config(pos=(coord(unit[1]), h - 1), **cfg)
     x = 0
     while x <= size:
         s = coord(x)
         self += Line((s, 0), (s, scale / (2 if x % step else 1)))
         x += 1
     for t in self:
         if isinstance(t, Text): t.config(height=h / 2)
     self.bind(ondrag)
Beispiel #9
0
 def title(self, title, padding=4, **kwargs):
     "Add a title bar"
     txtConfig = dict(font=Font.sans(),
                      fontSize=15,
                      fontStyle=BOLD,
                      color="white",
                      padding=padding)
     txtConfig.update(kwargs)
     title = Text(title).config(**txtConfig)
     cv = Canvas((self.width, title.height + self.weight), self.border)
     cv += title.config(pos=(cv.center[0], self.weight), anchor=TOP)
     self.insertTop(cv, 0, "TitleBar")
     return self
Beispiel #10
0
 def textIcon(self, text, icon=None, padding=6):
     "Add text and icon to button"
     if type(text) is str: text = Text(text)
     if type(icon) is bool: icon = Image(self._yesNoImg(icon))
     if icon:
         w = self._icon(icon, padding)
         x = (w + padding) / 2
     else: x = w = 0
     cx, cy = self.center
     if cx <= 0:
         self._size = (w + text.width + (3 if w else 2) * padding), self._size[1]
         cx = self.center[0]
     self += text.config(pos=(x + cx, cy))
     return self
Beispiel #11
0
 def _tick(param, marker=9, y=False, **kwargs):
     if type(marker) is int: marker = ((9, 1) if y else (1, 9), "black")
     label = type(marker) is str
     if not (label or isinstance(marker, Graphic)):
         marker = Image(*marker)
     s = list(Series._lattice(0, param) if y else Series._lattice(param, 0))
     if label:
         isZero = (lambda x: _isZero(x, marker)) if kwargs.get("omitZero")\
             else (lambda x: False)
         i = 1 if y else 0
         text = list(marker.format(x[i]) for x in s)
         marker = [
             Text("" if isZero(x) else x).config(**kwargs) for x in text
         ]
     return Series(s).config(marker=marker)
Beispiel #12
0
    def drawHighScores(self, score):
        "Draw the Top 10 scores on the screen"
        w, h = self.size
        x = w / 6
        y = h / 5
        attr = dict(color="blue", font=FONT, fontSize=self.height / 15)
        for i in range(len(score)):
            if i == 5:
                x += 0.5 * w
                y = h / 5
            s = score[i]
            s, name = s
            if len(name) > 12: name = name[:12]
            self += Text(data=s).config(anchor=RIGHT, pos=(x - 20, y), **attr)
            self += Text(data=name).config(anchor=LEFT, pos=(x, y), **attr)
            y += self[-1].height + 8

        icon = Sprite(Asteroid.original).config(spin=0.4)
        okay = Text("Okay").config(font=FONT)
        self += Button((w / 7, h / 10)).bind(onclick=restart).textIcon(
            okay, icon, 10).config(pos=(self.center[0], 0.9 * h),
                                   anchor=BOTTOM,
                                   border="blue",
                                   weight=3)
Beispiel #13
0
    def setup(self):
        self.config(border="blue", weight=1, bg=self.field())
        
        # Display the score
        attr = {"font":self.font, "fontSize":48}
        self += Text(0).config(pos=(8,8), anchor=TOPLEFT, color="red", **attr)
        self += Text(0).config(pos=(631,8), anchor=TOPRIGHT, color="yellow", **attr)
        self.score = list(self)[-2:]

        # Paint the back of the nets so the robots can see them
        w, h = self.size
        d = h / 8
        r = 0.65 * boxSize(w, h)[1]
        h = (h - 1) / 2
        self += Sprite(Image((2,2), "red")).config(pos=(-d, h), wrap=0)
        self += Sprite(Image((2,2), "yellow")).config(pos=(w+d, h), wrap=0)
        for s in self[-2:]: s.radiusFactor *= r / s.radius

        # Get a soccer ball
        self += SoccerBall().config(pos=self.center)

        # Start the simulation
        if hasattr(self, "brains"): self.start()
        else: self += Dialog(self).config(pos=self.center)
Beispiel #14
0
    def __init__(self, sk):

        # Radio buttons
        text = self.options
        attr = {"font":sk.font, "fontSize":16}
        radio = [Radio(text, txtConfig=attr).config(anchor=TOPLEFT),
            Radio(text[1:], txtConfig=attr).config(anchor=TOPLEFT)]

        # Play button
        icon = Sprite(SoccerBall.ballImage).config(spin=1)
        play = Text("Play").config(**attr)
        play = Button((96,36), 2).textIcon(play, icon)
        x, y = icon.pos
        x += icon.width / 2
        icon.config(anchor=CENTER, pos=(x,y))

        # Titles
        attr.update(anchor=TOP)
        text = [Text(t + " Robot").config(color=t, **attr)
            for t in ("Red", "Yellow")]

        # Create canvas
        items = radio + text + [play]
        w = max(gr.width for gr in items) + 16
        h = sum(gr.height for gr in items) + 72
        super().__init__((w, h), "#d0d0d0")

        # Position controls
        xc = self.center[0]
        y = 8
        for gr in [text[0], radio[0], text[1], radio[1]]:
            x = xc if isinstance(gr, Text) else 8
            self += gr.config(pos=(x,y))
            y += gr.height + 8
            if gr is radio[0]: y += 16
        self += play.config(pos=(xc,h-8), anchor=BOTTOM)
Beispiel #15
0
 def setup(self):
     self.caption = "Electric Force Simulation"
     w, h = self.size
     y = h - 40
     x = w / 1.5
     pivot = x, y - 200
     self["string"] = Line(pivot, (x, y)).config(weight=3)
     self += Charge().config(pos=(x, y))
     self["blue"] = QCircle(60).config(
         fill="blue").snapshot().bind(ondrag).config(pos=(40, y), height=24)
     self["angle"] = Text().config(
         pos=pivot, anchor=TOPRIGHT, font=MONO,
         color="red").config(height=24).bind(ondrag)
     self += Ruler(self.scale).config(pos=self.center)
     msg = "Red Sphere\n m = {:.2f} g\n q = {:.0f} nC\n\nBlue Sphere\n q = {:.0f} nC"
     msg = msg.format(self.mass, 1000 * self.q1, 1000 * self.q2)
     self += MessageBox(msg, buttons="Close", fontSize=14,
                        font=MONO).bind(ondrag).config(pos=(8, 8),
                                                       anchor=TOPLEFT)
Beispiel #16
0
 def __init__(self, text, height=None, padding=4, imgs=None, txtConfig={}):
     text = [Text(t).config(**txtConfig) for t in text]
     check = []
     w = 0
     y = padding
     if not height:
         height = 1 + text[0].height // len(text[0].data.split("\n"))
     for t in text:
         cb = Button.checkbox(imgs).config(height=height)
         yc = y + t.height / 2
         check.append(
             cb.config(height=height, pos=(padding, yc), anchor=LEFT))
         t.config(pos=(cb.width + 2 * padding, yc),
                  anchor=LEFT,
                  **txtConfig)
         y += t.height + padding
         w1 = cb.width + t.width
         if w1 > w: w = w1
     super().__init__((w + 3 * padding, y))
     self += check + text
     self.boxes = check
     if hasattr(self, "selected"): self.selected = 0
Beispiel #17
0
 def labels(text, pos, **kwargs):
     "Create a Series of Text labels"
     text = [Text(t).config(**kwargs) for t in text]
     return Series(pos).config(marker=text)