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")
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(onclick) sk.cursor = False
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
def __init__(self, text, userInput=None, buttons=None, title=None, size=(1,1), **kwargs): super().__init__(size) self.command = None # Collect 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 if userInput is not None: self["Input"] = TextInput(userInput, "Click to enter your response").config(anchor=TOP, bg="white", **txtConfig).bind(onaction=_tiAction) self["Text"] = Text(text).config(anchor=TOP, **txtConfig) # Position controls and add title bar self._arrange().config(bg="#f0f0f0", weight=2, border="blue") if title: self.title(title, **txtConfig)
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)
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
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)
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)
def setup(self): x, y = self.center attr = dict(font=Font.mono(), fontSize=18, fontStyle=BOLD, weight=1, padding=4, border="#c0c0c0", promptColor="#c0c0c0") self["Param"] = TextInput("", "fps w h x y").config(pos=(x + 16, y), **attr) self["Record"] = self.recordButton(y) self.grab = None
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")
def render(self): "Render the text as an Image" font = Font.get(self.font, self.fontSize, self.fontStyle) try: focus = self is self.sketch.evMgr.focus except: focus = False prompt = self.prompt and not self.data and not focus if prompt: color = self.promptColor text = self.prompt else: color = self.color text = self.data try: srf = font.render(text, True, color) except: text = "[Unable to render!]" srf = font.render(text, True, color) if prompt: self.prompt = text else: self.data = text self.cursor = 0 srf = style(srf, self.bg, self.border, self.weight, self.padding) # Highlight selection and draw cursor c = self.cursor if self.data: p0 = text[c - 1:c] if c else text[0] p1 = text[c:c + 1] if c < len(self.data) else text[-1] self._scrollPad = [font.size(p)[0] for p in (p0, p1)] else: self._scrollPad = 0, 0 x = font.size(text[:c])[0] p = self.padding x += p self._cursorX = x h = srf.get_height() s = self._selection if s not in (None, self.cursor): x0 = font.size(text[:s])[0] + p w = abs(x - x0) s = pygame.Surface((w, h - 2 * p), pygame.SRCALPHA) s.fill(self.highlight) srf.blit(s, (min(x, x0), p)) if self.cursorStatus: pygame.draw.line(srf, self.color, (x, p), (x, h - 1 - p), 2) return srf
def __init__(self, size, buttons=(("Okay", True), ("Cancel", False)), text={}, **kwargs): py = p = self.padding super().__init__((size, 128)) self.config(vectors=None, **kwargs) if self.drawTitle: self.title("Vector Diagram") # Text options txtConfig = {"font":Font.sans(), "fontSize":15} txtConfig.update(text) # Text inputs w = self.width - 2 * p try: y = py + self[0].height except: y = py ti = TextInputCanvas(w, "", "Vector Expression", **txtConfig) self["Vectors"] = ti.config(anchor=TOPLEFT, pos=(p, y), weight=1).bind(onaction=self.parse) y += py + ti.height self["Grid"] = TextInputCanvas(w // 2 - p, "", "Grid Settings", **txtConfig).config(anchor=TOPLEFT, pos=(p, y), weight=1) self["Step"] = TextInputCanvas(w // 4 - p // 2, "", "Step", **txtConfig).config(anchor=TOPLEFT, pos=(p + w // 2, y), weight=1) self["Size"] = TextInputCanvas(w // 4 - p // 2, "", "Width", **txtConfig).config(anchor=TOPLEFT, pos=(3 * (2 * p + w) // 4, y), weight=1) for gr in self[-3:]: gr.bind(onaction=nothing) # Options y += py + self[-1].height text = "Resultant", "Components", "Draggable" opt = Options(text, txtConfig=txtConfig).config(pos=(p, y), anchor=TOPLEFT) self["Options"] = opt x = (self.width - opt.width - p - w) / 2 x = self.width - x - w / 2 y += p y0 = y + opt.height opt[0].selected = True for gr in opt[:3]: gr.bind(onaction=nothing) # Buttons w = self.buttonWidth for btn in buttons: name = btn if type(btn) is str else btn[0] gr = Button((w, 32), 2).textIcon(*btn).setCanvas(self, name).config(anchor=TOPRIGHT, pos=(self.width - p, y)) #, pos=(x - 64, y)) y += 32 + py gr[-1].config(color="blue", align=CENTER, **txtConfig) # Resize self._size = size, max(y, y0)
try: from sc8pr import Sketch, Canvas, Image, BOTTOM, TOPRIGHT, TOPLEFT from sc8pr.shape import QCircle, Line from sc8pr.text import Text, Font, BOLD from sc8pr.geom import delta from sc8pr.util import ondrag from sc8pr.misc.cursors import hand from sc8pr.gui.dialog import MessageBox except Exception as e: print(e) print("Try running 'pip3 install sc8pr' on command line") exit() from math import hypot, asin, degrees from random import uniform MONO = Font.mono() class Simulation(Sketch): @property def scale(self): return 10 * self.width / 640 def __init__(self): self.mass = uniform(1, 4) self.q1 = uniform(0.1, 0.4) self.q2 = uniform(0.1, 0.4) super().__init__((640, 256)) def setup(self): self.caption = "Electric Force Simulation"
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. "A demonstration of some of sc8pr 2.0's GUI controls" from sc8pr import Sketch, Canvas, Image, TOPLEFT, TOPRIGHT, CENTER, TOP from sc8pr.util import rgba, nothing, sc8prData from sc8pr.text import BOLD, Font from sc8pr.gui.textinput import TextInput from sc8pr.gui.radio import Radio, Options from sc8pr.gui.slider import Slider from sc8pr.gui.button import Button from sc8pr.gui.menu import Menu, R_TRIANGLE GREY, BLUE = rgba("#ececec", "blue") FONT = Font.sans() def buttons(cfg): "Create a canvas containing two buttons" cv = Canvas((256, 48)) # Selectable button btn1 = Button((120, 48)).textIcon("Selectable\nButton", True) cv["Selectable"] = btn1.config(anchor=TOPLEFT).bind(onaction=buttonClick) # Non-selectable button btn2 = Button(btn1.size, 2).textIcon("Popup Menu").bind(onaction=buttonClick) cv["Popup"] = btn2.config(pos=(255, 0), anchor=TOPRIGHT) # Configure button text btn1[-1].config(color=BLUE, align=CENTER, **cfg)
def _widthTo(self, i): font = Font.get(self.font, self.fontSize, self.fontStyle) d = self.data return (font.size(d[:i])[0] + font.size(d[:i+1])[0]) // 2
from sc8pr.geom import vec2d, delta from sc8pr.gui.textinput import TextInput from sc8pr.gui.button import Button from sc8pr.misc.video import Video except Exception as e: print(e) print("Try running 'pip3 install sc8pr' on command line") exit() from pygame.constants import K_UP, K_DOWN, K_LEFT, K_RIGHT import json from time import time from math import pow from random import uniform, randint JSON = "asterShield_scores.json" FONT = Font.mono() class Ship(Sprite): "The spaceship is controlled by the player using the keyboard" def reset(self, sk): "Configure to start game" return self.config(width=sk.width / 15, fired=0, hits=0, pos=sk.center, vel=(0, 0), angle=270, spin=0)
robot.bind(brain=brain) def start(self): "Robots take the field" yellow = SoccerRobot(["#ffd428", "#ff5050"]) red = SoccerRobot(["#ff5050", "#ffd428"]) self.bindBrain(red, self.brains[0]) self.bindBrain(yellow, self.brains[1]) x, y = self.center x += (2 * randint(0, 1) - 1) * 16 self["Yellow"] = yellow.config(pos=(1.5 * x, y), width=y/4, angle=90) self["Red"] = red.config(pos=(0.5 * x, y), width=y/4, angle=270) ondraw = physics def goal(self, player): "Change the scoreboard" score = self.score[player] score.config(data=score.data+1) def play(*brains, **kwargs): sk = SoccerGame((640,480)).config(font=kwargs.get("font")) if len(brains) == 1: sk.brains = [brains[0], followBall] elif len(brains) == 2: sk.brains = brains sk.play("Robot Soccer") main = play if __name__ == "__main__": play(font=Font.mono())
from sc8pr import Sketch, Canvas, Image, TOPLEFT, TOPRIGHT, CENTER, TOP from sc8pr.util import rgba, nothing, sc8prData from sc8pr.text import BOLD, Font from sc8pr.gui.textinput import TextInput from sc8pr.gui.radio import Radio, Options from sc8pr.gui.slider import Slider from sc8pr.gui.button import Button from sc8pr.gui.menu import Menu, R_TRIANGLE try: # v2.2 from sc8pr.gui.textinput import TextInputCanvas except: # v2.0-2.1 TextInputCanvas = None GREY, BLUE = rgba("#ececec", "blue") FONT = Font.sans() def setup(sk): # Create a Canvas as a GUI dialog cv = Canvas((384, 256)).config(bg="#f0f0ff", weight=1) # Vertical positioning 16 pixels below last item added down = lambda cv: 16 + cv[-1].height text = dict(color=BLUE, font=FONT, fontStyle=BOLD, padding=4) if TextInputCanvas: # v2.2.dev ti = TextInputCanvas(336, "", "Type Some Text...", **text) else: # v2.0-2.1 ti = TextInput("", "Type Some Text...").config(**text) x, y = cv.center[0] - 8, 16
def _font(f): "Find a requested font" found = Font.find(*f["font"].split(",")) f["font"] = found if found else Font.sans()
if brain is remote: self.bind(onkeydown=Robot.remoteControl).config(remoteRobot=robot) robot.bind(brain=brain) def start(self): "Robots take the field" yellow = SoccerRobot(["#ffd428", "#ff5050"]) red = SoccerRobot(["#ff5050", "#ffd428"]) self.bindBrain(red, self.brains[0]) self.bindBrain(yellow, self.brains[1]) x, y = self.center x += (2 * randint(0, 1) - 1) * 16 self["Yellow"] = yellow.config(pos=(1.5 * x, y), width=y/4, angle=90) self["Red"] = red.config(pos=(0.5 * x, y), width=y/4, angle=270) ondraw = physics def goal(self, player): "Change the scoreboard" score = self.score[player] score.config(data=score.data+1) def main(*brains, **kwargs): sk = SoccerGame((640,480)).config(font=kwargs.get("font")) if len(brains) == 1: sk.brains = [brains[0], followBall] elif len(brains) == 2: sk.brains = brains sk.play("Robot Soccer") if __name__ == "__main__": main(font=Font.mono())
# along with "sc8pr". If not, see <http://www.gnu.org/licenses/>. "A simulation of the electric force (Coulomb's Law) between two spheres" if __name__ == "__main__": import depends from math import hypot, asin, degrees from random import uniform from sc8pr import Sketch, Canvas, Image, BOTTOM, TOPRIGHT, TOPLEFT from sc8pr.shape import Circle, Line from sc8pr.text import Text, Font, BOLD from sc8pr.geom import delta from sc8pr.util import ondrag from sc8pr.misc.cursors import hand from sc8pr.gui.dialog import MessageBox MONO = Font.mono() class Simulation(Sketch): @property def scale(self): return 10 * self.width / 640 def __init__(self): self.mass = uniform(1, 4) self.q1 = uniform(0.1, 0.4) self.q2 = uniform(0.1, 0.4) super().__init__((640,256)) def setup(self): self.caption = "Electric Force Simulation" w, h = self.size