def __init__(self, place): def set_target_x(ev): print(self.x, self.target_x) self.x = self.target_x self.x = 0 it = self.it = svg.g(id="theblogguy", transform="translate(0,600)", className="hander") self.lleg = svg.image(href=RLEG, x= "50px", y="85px", width=RLX, height=RLX) self.rleg = svg.image(href=RLEG, x= "20px", y="85px", width=RLX, height=RLX) self.img = svg.image(href=BLOG, x= "0px", y="0px", width="100px", height="100px") self.go = svg.rect(id="theblog", x="0px", y="700px", width="1024px", height="40px") self.go.style.fillOpacity = 0.3 self.go.onclick = self.goer self.tlk = svg.image(href=SPEECH, x= "40px", y="-90px", width="100px", height="100px") self.tlk.style.opacity = 0 self.talk() place <= self.go place <= self.it it <= self.lleg it <= self.rleg it <= self.img it <= self.tlk it.onanimationend = set_target_x #it.onclick = self.walk self.ax = self.anim() self.ar = self.walk()
def drawBoard(tiles): margin = 20 tileSide = 120 border = 20 panel = document["board"] panel.clear() panelSide = 620 for x in range(0, 4): xpos = margin + (margin * x) + (tileSide * x) + border for y in range(0, 4): ypos = margin + (margin * y) + (tileSide * y) + border rect = svg.rect(x=xpos, y=ypos, rx="5", ry="5", width=tileSide, height=tileSide, fill="#444444") panel <= rect if(tiles[x][y] != 0): textX = xpos + (tileSide/2) textY = ypos + (tileSide/2) + (margin/2) tile = svg.text(str(tiles[x][y]), x=textX, y=textY, font_size=40, text_anchor="middle", fill="white") panel <= tile
def drawBG(): pane = document["background"] #pane.clear() panelSide = 620 bg = svg.rect(x=0, y=0, rx=5, ry=5, width=panelSide, height=panelSide, fill="#EEEEEE") pane <= bg halfWay = 300 triangleHalfWidth = 30 triangleTop = 5 triangleBottom = 28 upTriangle = svg.polygon(points = str(halfWay)+","+str(triangleTop)+" "+ str(halfWay+triangleHalfWidth)+","+str(triangleBottom)+" "+ str(halfWay-triangleHalfWidth)+","+str(triangleBottom), fill = "blue", id="upButton") downTriangle = svg.polygon(points = str(halfWay)+","+str(panelSide-triangleTop)+" "+ str(halfWay+triangleHalfWidth)+","+str(panelSide-triangleBottom)+" "+ str(halfWay-triangleHalfWidth)+","+str(panelSide-triangleBottom), fill = "blue", id="downButton") leftTriangle = svg.polygon(points = str(triangleTop)+","+str(halfWay)+" "+ str(triangleBottom)+","+str(halfWay+triangleHalfWidth)+" "+ str(triangleBottom)+","+str(halfWay-triangleHalfWidth), fill="blue", id="leftButton") rightTriangle = svg.polygon(points = str(panelSide-triangleTop)+","+str(halfWay)+" "+ str(panelSide-triangleBottom)+","+str(halfWay+triangleHalfWidth)+" "+ str(panelSide-triangleBottom)+","+str(halfWay-triangleHalfWidth), fill="blue", id="rightButton") pane <= upTriangle pane <= downTriangle pane <= leftTriangle pane <= rightTriangle
def __init__(self, image_url=None, center=(0, 0), width=25, height=25): """ The constructor. @param image_url str: the URL of the image on the web @param center tuple(int, int): the location of the center. @param width: the display width of the image (image will be scaled to this value) @param height: the display height of the image (image will be scaled to this value) """ GraphicalObject.__init__(self) # mwb - disable the width and height stuff for now # width, height = shared.get_image_size(image_url) x = center[0]-width/2 y = center[1]-height/2 self._center = center self._pivot = center self._clip_square = svg.rect(width=width, height=height, x=x, y=y, transform="rotate(0)") self._clip_path = svg.clipPath(self._clip_square, Id="clip-path") self._svgGraphic = svg.image(width=width, height=height, x=x, y=y, href=image_url, transform="rotate(0)") self._svgGraphic.setAttribute("preserveAspectRatio", "none") self._svgGraphic.setAttribute("clip-path", "url(#clip-path)")
def draw(self): self.layer = svg.g(id='buildlayer') self.catcher = svg.rect( x=0, y=0, width=WIDTH, height=HEIGHT, style={'fill': '#fff'} ) self.layer <= self.catcher return self.layer
def create_hud_content(node): # As 0,0 is the start position Hud.hud_bounding = svg.rect(x=0, y=0, width=100, height=100, stroke="black", fill="white") Hud.hud_info = svg.text("", x=0, y=0, font_size=20,text_anchor="start") Hud.panel <= Hud.hud_bounding Hud.panel <= Hud.hud_info name = node.converter.name if node.converter.unstoppable: name += " - [Unstoppable]" Hud.hud_info <= Hud.create_tspan(name,x=Hud.border,dy=Hud.border,bold=True) Hud.create_converter_elements('Needs:',node.converter.needs,0,True) Hud.create_converter_elements('Produces:',node.converter.makes,0,True) # Hud.create_converter_elements('Upgrades:',node.converter.upgrades) hasUpgrade = False for u in node.converter.upgrades: if not u.bought: hasUpgrade = True if hasUpgrade: Hud.hud_info <= Hud.create_tspan('Upgrades:',x=Hud.border+10,dy=25,bold=True) for upgrade in node.converter.upgrades: if upgrade.bought: continue Hud.hud_info <= Hud.create_tspan(upgrade.name,x=Hud.border+30) button = svg.rect(x=0, y=0, width=Hud.upgrade_button_size, height=Hud.upgrade_button_size, stroke="black", fill="white") hsx, hsy = Hud.hud_size() button.attrs['x'] = int(Hud.border + 15) button.attrs['y'] = int(hsy - Hud.upgrade_button_size) func = lambda ev, upgrade=upgrade: Hud.hud_upgrade_buy(ev,upgrade,node) button.bind("click", func) buy_icon_appearance_func = lambda upgrade=upgrade, button=button: Hud.upgrade_button_appearance(upgrade, button) Hud.upgrade_button_appearance(upgrade, button) # init Hud.upgrades.append(buy_icon_appearance_func) # refresh icon updater Hud.panel <= button if upgrade.all_requirements_bought(): Hud.create_converter_elements('Costs:',upgrade.costs,offset=30) if upgrade is not upgrade_final: Hud.create_converter_elements('Changes:',upgrade.changes,offset=30) else: Hud.create_converter_elements('Requires:',upgrade.requires,offset=30)
def __init__(self): from browser import svg, document # cena = Cena(WHITE).vai() base = document["pydiv"] base.html = '' tela = svg.svg(width=1200, height=700) base <= tela bar = svg.rect(width="300", height="100", style={"fill": 'rgb(255,0,0)'}) tela <= bar [ tela <= svg.rect(x=ix * 40, width="40", height=600 - ix * 30, style={ "fill": 'rgb(255,0,0)', 'filter': f'hue-rotate({ix*18}deg)' }) for ix in range(20) ]
def centered_rect(width, height, x=0, y=0, color='black', id=None, classes=[]): rect = svg.rect( x=(x - width / 2), y=(y - height / 2), width=width, height=height, id=id, ) rect.style.fill = color for c in classes: rect.classList.add(c) return rect
def render_state_svg_graphics(state): global APANEL, LINE_WIDTH, board # Clear out any graphic elements from a previous state display: # Note: This method doesn't work correctly, due to possible automatic # restructuring of part of the DOM, and subsequent failure to remove # all of the graphic elements consistently: #for idx, child in enumerate(APANEL): APANEL.removeChild(APANEL.lastChild) # The following line was used for testing: #print("Removed "+str(idx)+" elements") # The following method works fine: while APANEL.lastChild: APANEL.removeChild(APANEL.lastChild) # Draw all the boxes. for box in state['boxes']: (X1, Y1) = mapCoordsToDIV(box.x1, box.y1) (X2, Y2) = mapCoordsToDIV(box.x2, box.y2) rect_style = {"stroke":"black", "stroke-width": LINE_WIDTH} rect = svg.rect(x=X1,y=Y1, width=X2-X1, height=Y2-Y1, fill=box.color, style=rect_style) APANEL <= rect # Highlight selected box if that option is on. global SHOWING_SELECTION if SHOWING_SELECTION: selected_box = state['boxes'][state['selected']] b = selected_box (X1, Y1) = mapCoordsToDIV(b.x1, b.y1) (X2, Y2) = mapCoordsToDIV(b.x2, b.y2) selected_rect_style = {"stroke": "#8800CC", "stroke-width": LINE_WIDTH/2} selected_rect = svg.rect(x=X1,y=Y1, width=X2-X1, height=Y2-Y1, fill=b.color, style=selected_rect_style) APANEL <= selected_rect diagline_style = {"stroke": "green", "stroke-width": LINE_WIDTH} diagline = svg.line(x1=X1,y1=Y1, x2=X2, y2=Y2, style=diagline_style) APANEL <= diagline global LAST_STATE LAST_STATE = state window.makeNeededPNGs(board)
def __init__(self, sideLength=40, center=(0, 0)): """ @param sideLength int: the length of a side (in pixels). @param center tuple(int, int): the location of the center. """ Fillable.__init__(self) x = center[0]-sideLength/2 y = center[1]-sideLength/2 self._center = center self._pivot = center self._svgGraphic = svg.rect(height=sideLength, width=sideLength, x=x, y=y, stroke="black", stroke_width=1, fill=None, transform="rotate(0)")
def block(dd): nx, ny = rosa.pop(0) ox, oy = self.last nx, ny = ox + nx * 20, oy - ny * 20 self.last = (nx, ny) return svg.rect(width=400 - dd * 20, height=400 - dd * 20, x=nx, y=ny, style={ "fill": 'rgb(255,0,0)', 'filter': f'hue-rotate({dd*48}deg)', 'opacity': 0.2 })
def __init__(self, width=40, height=40, center=(0, 0)): """ @param width int: width of the rectangle (in pixels). @param height int: height of the rectangle (in pixels). @param center tuple(int, int): the center of the rectangle. """ Fillable.__init__(self) x = center[0]-width/2 y = center[1]-height/2 self._center = center self._pivot = center self._svgGraphic = svg.rect(height=height, width=width, x=x, y=y, stroke="black", stroke_width=1, fill=None, transform="rotate(0)")
def make_rects(self, maxX, maxY): for rect in range(1000): r = svg.rect(x=randint(0, maxX + 50) - 50, y=randint(0, maxY + 50) - 50, width=randint(0, 200) + 20, height=randint(0, 200) + 20, opacity=0.8 * randint(0, 10), fill=colorPalette[randint(0, 4)], transform=f"rotate({3*randint(0, 30)})") self.tela <= r transform = svg.animateTransform(attributeName="transform", begin="0s", dur="20s", to="360 60 60", repeatCount="indefinite") transform.setAttribute("type", "rotate") transform.setAttribute("from", "0 60 60") r <= transform
def test_browser_svg(): from browser import document, svg line = svg.line(x1="40", y1="50", x2="40", y2="150", stroke="brown", stroke_width="2") panel = document['panel3'] panel <= line from browser import document, svg star = svg.polygon(fill="red", stroke="blue", stroke_width="10", points=""" 75,38 90,80 135,80 98,107 111,150 75,125 38,150 51,107 15,80 60,80""") panel = document['panel4'] panel <= star from browser import document, svg, timer rect = svg.rect(x=10, y=10, width=100, height=100) def move_rect(): # the attributes of the SVG element are strings, they must be explicitely # converted into integers rect.attrs["y"] = int(rect.attrs["y"]) + 1 # ends animation when the rectangle reaches its target if int(rect.attrs["y"]) > 50: timer.clear_interval(loop) panel = document['panel5'] panel <= rect # initialise the animation loop loop = timer.set_interval(move_rect, 30)
def cbclick(ev): global selectedtile, cboard, redsturn if cboard: if redsturn: row = int(ev.clientY / 64) - 1 col = int(ev.clientX / 64) tile = gettilenumber(row, col) if tile == 'error': # alert(tile) return # alert(tile) if tile == selectedtile: # unhighlight selected tile doc['panel2'].remove(doc['panel2'].children[-1]) selectedtile = -1 elif selectedtile == -1: if cboard[tile] == RED or cboard[tile] == REDKING: selectedtile = tile # highlight selected tile scircle = svg.rect(x=(getcolnumber(tile) * 64), y=(getrownumber(tile) * 64), width=64, height=64, stroke='orange', stroke_width=3, fill_opacity=0) scircle.setAttributeNS(None, 'pointer-events', 'none') doc['panel2'] <= scircle elif selectedtile != -1 and tile != selectedtile: moves = getgapmoves(cboard, RED) for move in moves: if move[0] == selectedtile and move[1] == tile: # unhighlight selected tile doc['panel2'].remove(doc['panel2'].children[-1]) selectedtile = -1 cboard = domakemove(cboard, move) # alert(move) # print board printboard(cboard) redsturn = False return
class Hud: # Add g to the hud panel = document['hud'] rect = panel.parent.getBoundingClientRect() width,height = rect.width,rect.height hud_info = svg.text("", x=0, y=0, font_size=20,text_anchor="start") hud_bounding = svg.rect(x=0, y=0, width=100, height=100, stroke="black", fill="white") upgrades = [] # add to panel manually later active = False border = 10 upgrade_button_size = 10 def create_tspan(text,x,dy='1em',bold=False): if bold: id = "bold_text" else: id = "normal_text" return svg.tspan(text,id=f'{id}',x=x,dy=dy) def hud_clicked(event): event.stopPropagation() def clear_hud(): Hud.panel.clear() Hud.hud_info.clear() Hud.upgrades.clear() Hud.panel.attrs["visibility"] = "hidden" def hud_size(): brect = Hud.hud_info.getBBox() return int(brect.width), int(brect.height) def hud_upgrade_buy(event, upgrade, node): if upgrade.buy(): Hud.show_info(node) # CHECK ENDING if upgrade is upgrade_final: trigger_ending_scene() event.stopPropagation() def create_converter_elements(title,elements,offset=0,boldTitle=False): if elements: Hud.hud_info <= Hud.create_tspan(title,x=Hud.border+10+offset,dy=25,bold=boldTitle) for element in elements: text = str(element) Hud.hud_info <= Hud.create_tspan(text,x=Hud.border+20+offset) def create_hud_content(node): # As 0,0 is the start position Hud.hud_bounding = svg.rect(x=0, y=0, width=100, height=100, stroke="black", fill="white") Hud.hud_info = svg.text("", x=0, y=0, font_size=20,text_anchor="start") Hud.panel <= Hud.hud_bounding Hud.panel <= Hud.hud_info name = node.converter.name if node.converter.unstoppable: name += " - [Unstoppable]" Hud.hud_info <= Hud.create_tspan(name,x=Hud.border,dy=Hud.border,bold=True) Hud.create_converter_elements('Needs:',node.converter.needs,0,True) Hud.create_converter_elements('Produces:',node.converter.makes,0,True) # Hud.create_converter_elements('Upgrades:',node.converter.upgrades) hasUpgrade = False for u in node.converter.upgrades: if not u.bought: hasUpgrade = True if hasUpgrade: Hud.hud_info <= Hud.create_tspan('Upgrades:',x=Hud.border+10,dy=25,bold=True) for upgrade in node.converter.upgrades: if upgrade.bought: continue Hud.hud_info <= Hud.create_tspan(upgrade.name,x=Hud.border+30) button = svg.rect(x=0, y=0, width=Hud.upgrade_button_size, height=Hud.upgrade_button_size, stroke="black", fill="white") hsx, hsy = Hud.hud_size() button.attrs['x'] = int(Hud.border + 15) button.attrs['y'] = int(hsy - Hud.upgrade_button_size) func = lambda ev, upgrade=upgrade: Hud.hud_upgrade_buy(ev,upgrade,node) button.bind("click", func) buy_icon_appearance_func = lambda upgrade=upgrade, button=button: Hud.upgrade_button_appearance(upgrade, button) Hud.upgrade_button_appearance(upgrade, button) # init Hud.upgrades.append(buy_icon_appearance_func) # refresh icon updater Hud.panel <= button if upgrade.all_requirements_bought(): Hud.create_converter_elements('Costs:',upgrade.costs,offset=30) if upgrade is not upgrade_final: Hud.create_converter_elements('Changes:',upgrade.changes,offset=30) else: Hud.create_converter_elements('Requires:',upgrade.requires,offset=30) def show_info(node): Hud.clear_hud() # clear Hud.create_hud_content(node) # Create bounding rect hsx, hsy = Hud.hud_size() Hud.hud_bounding.attrs["width"] = hsx + Hud.border*2 Hud.hud_bounding.attrs["height"] = hsy + Hud.border*2 # Set text start Hud.hud_info.attrs["y"] = 0 # Translate all element tx = node.position[0] + node.radius + 5 ty = node.position[1] - node.radius Hud.panel.attrs["transform"] = f'translate({tx},{ty})' # Visibility Hud.panel.attrs["visibility"] = "visible" def upgrade_button_appearance(upgrade, button): color = "red" if upgrade.isBuyable(): color = "LawnGreen" button.style["stroke"] = "black" button.style["fill"] = color def refresh_buy_icon(): for fn in Hud.upgrades: fn()
def render_state(state): global roleCanvas, ctx, APANEL, selected_image, musicDisplay, ruleDisplay # Clear svg panel while APANEL.lastChild is not None: APANEL.removeChild(APANEL.elt.lastChild) # Clear the roleCanvas ctx.clearRect(0,0, GAME_WIDTH, GAME_HEIGHT) # Clear the ruleDisplay while ruleDisplay.lastChild is not None: ruleDisplay.removeChild(ruleDisplay.childNodes[0]) if(state['Role'] == "Architect"): # Display the SVG prepareSVG() # Remove old puzzle list if it exists # Append new puzzle list to Architect role remove_puzzle_list() create_puzzle_list(state) # Create the puzzle list so architect can tell which puzzles are which # Draw all the rooms. for room_num, room in enumerate(state['Rooms']): drawRoom(room,room_num) #add outline to selected room THICKNESS = 1.5 selected_room = state['Rooms'][state['Selected_Room']] (x1, y1) = mapCoordsToDIV(selected_room.x1, selected_room.y1) (x2, y2) = mapCoordsToDIV(selected_room.x2, selected_room.y2) outline = svg.rect(x = x1, y = y1, width = x2 - x1, height = y2 - y1, fill = "none", style = {"stroke": "gold", "stroke-width": THICKNESS}) APANEL <= outline elif(state['Role'] == "Image Puzzle"): prepareCanvas() if(state["Selected_Image"] is not None): puzzle = state["Image_Puzzles"][state["Selected_Image"]] canMan.setURL(puzzle.url) drawImagePuzzle(puzzle) elif(state['Role'] == "Music Puzzle"): prepareMusicDisplay() songName = state["Selected_Music"] songSelected = document.getElementById("songSelected") playButton = document.getElementById("playButton") if(songName is not None): songSelected.innerHTML = "Song: \"" + songName + "\" selected" # Bind the correct play song button to the button. playButton.unbind('click') playButton.bind('click', handlePlayButtonClick(state)) playButton.disabled = False else: songSelected.innerHTML = "No song selected" playButton.disabled = True elif(state['Role'] == "Rules"): prepareRuleDisplay() # Draw all the rooms in architect view. for room_num, room in enumerate(state['Rooms']): drawRoom(room,room_num) rulesTitle = html.P(id="rulesTitle", style = {'margin' : 0, 'border-bottom' : '5px solid white'}) # If no rules then display message if(len(state["Rules"]) == 0): rulesTitle.innerHTML = "There are no Rules." ruleDisplay <= rulesTitle # Otherwise display all rules with delete buttons else: rulesTitle.innerHTML = "Rules:" ruleDisplay <= rulesTitle populateRuleDisplay(state) else: pass
def drawRoom(room,room_num): # thickness of a room's walls. THICKNESS = .3 #(x3,y3) and (x4,y4) make up the shorter end of the trapezoid # draws north wall wall = room.walls['N'] x3 = wall.x2 - THICKNESS/pow(2,1/2) y3 = wall.y1 + THICKNESS/pow(2,1/2) x4 = wall.x1 + THICKNESS/pow(2,1/2) y4 = y3 drawWall(wall,x3,y3,x4,y4,room_num) # for ambient rect ax1 = x4 ay1 = y4 ax2 = x3 # draws south wall wall = room.walls['S'] x3 = wall.x2 - THICKNESS/pow(2,1/2) y3 = wall.y1 - THICKNESS/pow(2,1/2) x4 = wall.x1 + THICKNESS/pow(2,1/2) y4 = y3 drawWall(wall,x3,y3,x4,y4,room_num) # for ambient rect ay2 = y3 # draws west wall wall = room.walls['W'] x3 = wall.x2 + THICKNESS/pow(2,1/2) y3 = wall.y2 - THICKNESS/pow(2,1/2) x4 = x3 y4 = wall.y1 + THICKNESS/pow(2,1/2) drawWall(wall,x3,y3,x4,y4,room_num) # draws east wall wall = room.walls['E'] x3 = wall.x2 - THICKNESS/pow(2,1/2) y3 = wall.y2 - THICKNESS/pow(2,1/2) x4 = x3 y4 = wall.y1 + THICKNESS/pow(2,1/2) drawWall(wall,x3,y3,x4,y4,room_num) if(room.aAudio is not None): # Create a pattern for image representation of note and note playing. pattern = svg.pattern(id="ambientAudio",width = "100%",height = "100%") window.addAttribute(pattern,"patternContentUnits","objectBoundingBox") pattern2 = svg.pattern(id="ambientAudioPlaying",width = "100%",height = "100%") window.addAttribute(pattern2,"patternContentUnits","objectBoundingBox") img = svg.image(xlink_href="images/note.png", x= "0" ,y = "0", width = '1', height = '1') window.addAttribute(img,"preserveAspectRatio","none") img2 = svg.image(xlink_href="images/notePlaying.png", x= "0" ,y = "0", width = '1', height = '1') window.addAttribute(img2,"preserveAspectRatio","none") (x1,y1) = mapCoordsToDIV(ax1,ay1) (x2,y2) = mapCoordsToDIV(ax2,ay2) ambientDiv = svg.rect(x = x1, y = y1, width = x2 - x1, height = y2 - y1, fill = "url(#ambientAudio)") ambientDiv.onclick = ambientAudioTrigger(room,ambientDiv) # Append pattern <= img pattern2 <= img2 APANEL <= pattern APANEL <= pattern2 APANEL <= ambientDiv
def __init__(self, resource, line_height, line_width): self.graphic_container = svg.g() self.resource = resource self.item_height = line_height voffset = 5 # Name string HACK:dominant-baseline self.text = svg.text(resource.name, x=10, y=voffset, font_size=20, text_anchor='start') self.text.attrs['dominant-baseline'] = "hanging" # Progress rectangle self.rect_width = 100 rect_right_margin = 5 rect_x_start = line_width - self.rect_width - rect_right_margin rect_y_start = voffset rect_height = 15 rect_rx = 5 self.rect = svg.rect(x=rect_x_start, y=rect_y_start, width=self.rect_width, height=rect_height, rx=0) self.number_text = svg.text("", x=line_width - rect_right_margin - (self.rect_width / 2), y=voffset + 2, font_size=16, text_anchor="middle", font_weight="bold") self.number_text.attrs['dominant-baseline'] = "hanging" # Contour rectangle id_str = ('contour_' + resource.name).replace(" ", "_") clip_id_str = ('clip_rect_' + resource.name).replace(" ", "_") clip_rect = svg.rect(x=rect_x_start, y=rect_y_start, width=self.rect_width, height=rect_height, rx=rect_rx, stroke="black", style={ "fill-opacity": "0", "stroke-opacity": "1" }, id=clip_id_str) # 'use' structure clip = svg.clipPath(id=id_str) clip <= clip_rect g = svg.g(style={"clip-path": "url(#" + id_str + ")"}) g <= self.rect g <= svg.use(href="#" + clip_id_str) self.border = svg.rect(id="itemContainer_rect", x=0, y=0, width=line_width, height=line_height, rx=rect_rx, fill="grey", style={"fill-opacity": "0.5"}) self.border.attrs['visibility'] = 'hidden' self.graphic_container <= self.border # SVG elements self.graphic_container <= clip self.graphic_container <= g self.graphic_container <= self.text self.graphic_container <= self.number_text self.graphic_container.attrs['visibility'] = 'hidden' # Visible self.hidden = True