def draw(self): # 上 pyxel.blt(self.x, self.y, 2, 96, 0, 160, -64, 3) # 中 # コア部分 if self.brokenState in (1, 2): Drawing.setBrightnessWithoutBlack(self.coreBrightness) BossLast1Core.drawCore(self.coreX, self.coreY, self.rad) pyxel.pal() if self.cnt & 3 == 0: if self.coreBrightState == 0: self.coreBrightness += 1 if self.coreBrightness >= 4: self.coreBrightState = 1 else: self.coreBrightness -= 1 if self.coreBrightness <= -3: self.coreBrightState = 0 pyxel.blt(self.x +32, self.y +64, 2, 0, 128, 96, 64, 3) if self.brokenState in (0,1): if self.hit: Drawing.setBrightnessWithoutBlack(1) pyxel.blt(self.x +32, self.y +64, 2, 0, self.brokenState* 64, 96, 64, 3) pyxel.pal() # 下 pyxel.blt(self.x, self.y +128, 2, 96, 0, 160, 64, 3)
def drawLineAngle(cls, cx, cy, r, angle): points = [] radius = 14 y = -radius * math.sin(r) y2 = -radius * math.sin(r - math.pi/2.0) if r <= math.pi*0.25: clr = 5 elif r <= math.pi*0.5: clr = 12 elif r <= math.pi*0.75: clr = 6 else: clr = 5 #pyxel.line(cx -32, cy, cx -8, y, clr) #pyxel.line(cx -8, y, cx +8, y, clr) #pyxel.line(cx +8, y, cx +32, cy, clr) points.append([-32, +0]) points.append([-8, +y]) points.append([+8, +y]) points.append([+32, +0]) xpoints = gcommon.getAnglePoints([cx, cy], points, [0,0], angle) Drawing.drawConnectedLines(xpoints, clr) if r >math.pi*0.75 and r <= math.pi * 1.75: pass else: #pyxel.line(cx -8, y, cx -8, y2, clr) #pyxel.line(cx +8, y, cx +8, y2, clr) points = [[-8, y], [-8, y2], [+8, y], [+8, y2]] xpoints = gcommon.getAnglePoints([cx, cy], points, [0,0], angle) Drawing.drawLines(xpoints, clr)
def draw100(self): self.drawStar() if self.state in (100, 200): self.drawTitleNormal() elif self.state == 102 or self.state == 103: pyxel.pal() # 文字枠 for c in TitleScene.colorTable1: pyxel.pal(c, 7) table = TitleScene.colorTable3[self.subState] for t in table: pyxel.pal(t[0], t[1]) pyxel.blt(0, __class__.title_y, 1, 0, 40, 256, 80, 0) # pyxel.pal() elif self.state == 104: self.drawTitleNormal() self.drawFlash(self.subCnt * 8, 32) self.drawMenu(self.state == 200, 1.0) pyxel.text(200, 188, "CREDIT(S) " + str(self.credits), 7) pyxel.blt(10, 186, 0, 88, 120, 8, 8, 0) pyxel.text(20, 188, "2021 ONTAKE44", 7) Drawing.showTextHCentor2(188, "VER " + gcommon.VERSION, 7) pyxel.pal() if self.mouseManager.visible: self.mouseManager.drawMenuCursor()
def draw(self): pyxel.cls(0) # 星 for i in range(0, 96): pyxel.pset(EndingScene.star_ary[i][0], i * 2, int(random.randrange(0, 2) + 5)) pyxel.blt(128 - 56 / 2, 40, 2, 128, 48, 56, 56, 2) if self.state == 0: Drawing.stretchBlt(self.px - self.sx * self.size/2, self.py - self.sy * self.size/2, \ self.sx * self.size, self.sy * self.size, \ 1, 0, 0, self.sx, self.sy) elif self.state == 2: px = 132 py = 60 if self.cnt < 18: self.drawShine(px, py, int(self.cnt / 6)) elif self.cnt < 60: if self.cnt & 2 == 0: self.drawShine(px, py, 2) elif self.cnt < 80: self.drawShine(px, py, int(2 - (self.cnt - 62) / 6)) elif self.cnt >= 150: l = int((self.cnt - 150) / 20) sl = len(self.message) if l > sl: l = sl Drawing.showText(128 - sl * 4, 120, self.message[:l]) for obj in self.objs: if obj.removeFlag == False: obj.draw()
def __init__(self, overlay, **kwargs): super().__init__(**kwargs) # creating an interface self.controller = overlay self.size_hint = (.8, .8) self.orientation = 'vertical' # starting the gameloop self.event = Clock.schedule_interval(self.mainloop, 0) # create main canvas self.GAME = Widget() self.GAME.canvas = Canvas() self.add_widget(self.GAME) # game classes self.player = Player() self.sprites = Sprites() self.drawing = Drawing(self.GAME.canvas, None) # draw borders with self.canvas.after: Color(.05, .05, .05) Rectangle(pos=(0, 0), size=(NULLX, REAL_SCREEN_Y)) Color(.01, .01, .01) Rectangle(pos=(NULLX, REAL_SCREEN_Y - NULLY), size=(REAL_SCREEN_X - NULLX, NULLY)) Color(.01, .01, .01) Rectangle(pos=(NULLX, 0), size=(REAL_SCREEN_X - NULLX, NULLY)) Color(.05, .05, .05) Rectangle(pos=(REAL_SCREEN_X - NULLX, 0), size=(REAL_SCREEN_X, REAL_SCREEN_Y))
def draw(self): # 本体のドーナツ部 pyxel.blt(self.x, self.y, 2, 64, 48, 80, 80, gcommon.TP_COLOR) # 中心の玉 for i in range(4): pyxel.blt( self.x + 39.5 + math.cos(self.rad + math.pi / 2 * i) * self.centerRadius - 7.5, self.y + 39.5 + math.sin(self.rad + math.pi / 2 * i) * self.centerRadius - 7.5, 2, 0, 32, 16, 16, gcommon.TP_COLOR) # Finに隠れた砲台 for i in range(8): if i & 1 == 0: pyxel.blt( self.x + 39.5 + math.cos(self.rad + math.pi / 4 * i) * 32 - 7.5, self.y + 39.5 + math.sin(self.rad + math.pi / 4 * i) * 32 - 7.5, 2, 16, 32, 16, 16, gcommon.TP_COLOR) else: pyxel.blt( self.x + 39.5 + math.cos(self.rad + math.pi / 4 * i) * 32 - 7.5, self.y + 39.5 + math.sin(self.rad + math.pi / 4 * i) * 32 - 7.5, 2, 32, 32, 16, 16, gcommon.TP_COLOR) for polygons in self.xpolygonsList: Drawing.drawPolygons(polygons)
def draw(self): pyxel.cls(0) #self.drawStar() gcommon.drawStar(self.star_pos) Drawing.showTextHCenter(20, "SELECT STAGE") stageInfo = self.stageManager.stageRoot stageInfo.setDrawFlag(False) highlight = True if self.state == 0: if self.cnt & 8 == 0: highlight = False elif self.state == 1: if self.cnt & 2 == 0: highlight = False self.drawNode(stageInfo, self.currentStageInfo, self.selectableStageMap, self.clearedMap, highlight) px = self.currentStageInfo.imageX * 64 py = self.currentStageInfo.imageY * 56 pyxel.blt(32, 108, 1, px, py, 64, 56) Drawing.showTextHCenter(180, "PUSH SHOT KEY") if self.mouseManager.visible: self.mouseManager.drawMenuCursor()
def __init__(self): self.trees = Drawing.getTexture('images/arboles.png') self.mountains = Drawing.getTexture('images/fondo.png') self.circuit = Drawing.getTexture('images/marioCircuit4.png') glBindTexture(GL_TEXTURE_2D, glGenTextures(1)) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glEnable(GL_TEXTURE_2D)
def drawFlash(self, x, y): pyxel.pal() for c in range(1, 15): pyxel.pal(c, 7) #pyxel.blt(self.subCnt*8, 24, 4, self.subCnt*8, 24, 40, 80, 0) Drawing.drawPolygonSystemImage( gcommon.getShitPoints([x, y], TitleScene.polyPoints)) pyxel.pal()
def __init__(self, r, n=20, edgetype=None): Drawing.__init__(self) pts = [] dt = 2 * pi / n for i in range(n): pt = (r * cos(i * dt), r * sin(i * dt)) pts.append(pt) Face.__init__(self, pts, edgetype=edgetype, origin=False)
def tensorboard_reconstruction(self, orig, recon): # self.tb_writer.add_text( # 'reconstruction/original', text_string="", global_step=self.epoch) self.tb_writer.add_image( "reconstruction/original", Drawing.from_tensor_prediction(orig).tensorboard_plot(), self.epoch) # self.tb_writer.add_text( # 'reconstruction/prediction', str(recon), self.epoch) self.tb_writer.add_image( "reconstruction/prediction", Drawing.from_tensor_prediction(recon).tensorboard_plot(), self.epoch) self.tb_writer.flush()
def save_reconstruction(self, orig, recon): original = Drawing.from_tensor_prediction(orig) reconstruct = Drawing.from_tensor_prediction(recon) plt.figure(figsize=(7, 4)) plt.suptitle(f"Epoch {self.epoch}") plt.subplot(1, 2, 1) plt.title("orig") original.render_image(show=False) plt.subplot(1, 2, 2) plt.title("recon") reconstruct.render_image(show=False) plt.savefig(self.plots_dir + f"reconstruction_{self.epoch}.png", bbox_inches='tight', dpi=150) plt.close()
def Main(): Read_Data() translatePoints() setPrincipalSign() DecideConvexConcavePoints() DecidePrincipalsPoints() PrintConvexesConcaves() PrintPrincipalsNotPrincipals() # A ramas partea grafica map_points() drawing = Drawing(drawing_points) drawing.draw()
def main(x=HALF_WIDTH // 4, y=HALF_HEIGHT - 50, heart=100, eat=100, energy=100, money=0, *inventory): player = Player(sprites, sc, x, y, heart, eat, energy, inventory, money) drawing = Drawing(sc, sc_map) pygame.mouse.set_visible(False) pygame.mixer.music.load('sound\\music\\Free Zen Spirit — Zen Spirit Music.mp3') pygame.mixer.music.play() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() player.movement() sc.fill(BLACK) drawing.background(player.angle) walls = ray_casting_walls(player, drawing.textures) drawing.world(walls + [obj.object_locate(player) for obj in sprites.list_of_objects]) drawing.fps(clock) pygame.draw.rect(sc, BLACK, (WIDTH - 400, 0, 700, HEIGHT)) pygame.draw.rect(sc, BLACK, (0, 0, WIDTH, 30)) pygame.draw.rect(sc, BLACK, (0, HEIGHT - 50, WIDTH, 100)) pygame.draw.rect(sc, WHITE, (WIDTH - 400, 0, 700, HEIGHT - 300), 3) pygame.draw.rect(sc, WHITE, (WIDTH - 400, HEIGHT - 300, 700, 300), 3) player.draw_hp() pygame.display.flip() clock.tick(FPS) '''
def drawContinueMenu(self): pyxel.rect(127 - 40, 192 / 2 - 32, 80, 48, 0) pyxel.rectb(127 - 39, 192 / 2 - 31, 78, 46, 7) pyxel.rect(127 - 37, 192 / 2 - 29, 74, 8, 1) Drawing.showTextHCentor2(192 / 2 - 32 + 4, "CONTINUE ?", 7) pyxel.rect(127 - 40 + 4, 192 / 2 - 32 + 15 + self.pauseMenuPos * 10, 80 - 8, 8, 2) pyxel.text(127 - 32 + 10, 192 / 2 - 32 + 16, "YES", 7) pyxel.text(127 - 32 + 10, 192 / 2 - 32 + 26, "NO", 7) pyxel.text(127 - 32 + 10, 192 / 2 - 32 + 38, "CREDITS " + str(GameSession.credits), 7)
def draw(self): if self.cnt & 4 == 0: if self.direction == 0: # 上 pyxel.blt(self.x - 7, self.y, 0, 0, 240, 15, 13, 0) else: # 下 pyxel.blt(self.x - 7, self.y - 13, 0, 0, 240, 15, -13, 0) if self.text != None and self.text != "": pyxel.pal(7, 8) if self.direction == 0: Drawing.showText(self.x + 10, self.y + 4, self.text) else: Drawing.showText(self.x + 10, self.y - 9, self.text) pyxel.pal()
def drawNode(cls, node: stage.StageInfo, currentStage, selectableStageMap, clearedMap, highlight:bool): if node.drawFlag: return node.drawFlag = True # 0 : 無効 # 1 : まだ未達 # 2 : クリア済み # 3 : 選択肢(選択中) # 4 : 選択肢(非選択) status = 1 # 状態種類 # 無効(実装されてない) enabled = False # 有効 # まだ未達 # クリア済 # 選択肢 選択中/非選択 if node == None or node.enabled == False: status = 0 else: # 有効 if node.stage in clearedMap: # クリア済みは色そのまま status = 2 pass else: if node.stage in selectableStageMap: if node.stage == currentStage.stage: # 選択中 status = 3 if highlight == False: status = 2 else: # 非選択 status = 4 else: status = 1 for t in __class__.imageColorTable[status]: pyxel.pal(t[0], t[1]) pyxel.blt(node.x +__class__.nodeBaseX, node.y + __class__.nodeBaseY, 0, 0, 224, 32, 16) pyxel.pal() for t in __class__.textColorTable[status]: pyxel.pal(t[0], t[1]) if node != None: Drawing.showText(node.x + 8 +__class__.nodeBaseX, node.y +4 + __class__.nodeBaseY, node.stage) pyxel.pal() if node != None and node.nextStageList != None: for childNode in node.nextStageList: StageSelect.drawNode(childNode, currentStage, selectableStageMap, clearedMap, highlight)
def draw(self): Drawing.setBrightnessWithoutBlack(self.coreBrightness) if self.cycleCount & 1 == 0: BossLast1Core.drawCoreAngle(self.x, self.y, self.rad, self.angle) else: BossLast1Core.drawCoreAngle(self.x, self.y, self.rad, -self.angle) pyxel.pal() if self.cnt & 3 == 0: if self.coreBrightState == 0: self.coreBrightness += 1 if self.coreBrightness >= 4: self.coreBrightState = 1 else: self.coreBrightness -= 1 if self.coreBrightness <= -3: self.coreBrightState = 0
def test_processing(): inp = 'raw_data/test.json' outp = "raw_data/test.npz" process_creativebirds_json(in_path=inp, out_path=outp) a = np.load(outp, allow_pickle=True, encoding='latin1') drawing = Drawing.from_npz_data(a['train'][1]) drawing.plot()
def __init__(self): self.programm = None self.drawing = Drawing() self.rainbowEffect = RainbowEffect(self.drawing, self.nextMode) self.runningLightEffect = RunningLightEfect(self.drawing, self.nextMode) self.waitEffect = WaitEffect(self.drawing, self.nextMode) self.appearEffect = AppearEffect(self.drawing, self.nextMode) self.cycleEffect = CycleEffect(self.drawing, self.nextMode) self.pendulumEffect = PendulumEffect(self.drawing, self.nextMode) self.waveEffect = WaveEffect(self.drawing, self.nextMode) self.clockEffect = ClockEffect(self.drawing, self.nextMode) self.debugEffect = DebugEffect(self.drawing, self.nextMode) self.mode = 0 self.showSingleEffect = False
def main_cam(gesture_lock): cap = cv2.VideoCapture(0) address = "http://192.168.1.193:8080/video" cap.open(address) fps = FPS().start() fps_count = 0.0 drawing = Drawing() while cap.isOpened(): ret, frame = cap.read() if not ret: print('Video file finished.') break frame = cv2.flip(frame, 1) gesture, action = gesture_lock.get_gesture() text = action + " (" + gesture + ")" cv2.putText(frame, text=text, org=(30, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=3, color=(0, 255, 20), thickness=5) frame = drawing.process_frame(frame, action) fps.update() if fps._numFrames == 25: fps.stop() fps_count = fps.fps() fps = FPS().start() cv2.putText(frame, text=str(round(fps_count, 1)), org=(1750, 50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2, color=(0, 255, 20), thickness=3) cv2.imshow('Cam', frame) if cv2.waitKey(1) & 0xFF == 27: break cap.release() cv2.destroyAllWindows()
def __init__(self, pts, edgetype=None, origin=True): Drawing.__init__(self) if origin: pts = list(pts) + [(0, 0)] else: pts = list(pts) lastpt = pts[-1] edgenum = 0 edgenames = [] for pt in pts: name = 'e%d' % edgenum self.edges[name] = Edge(name, lastpt, pt, edgetype) edgenames.append(name) lastpt = pt edgenum += 1 self.graph.addFace(GraphFace("", pts), faceEdges=edgenames)
def import_drawing(self): """Import the file and return structure containing all entities.""" try: # read and parse all lines with open(self.filename) as fin: lines = 0 for line in fin: self.parse_line(line) lines += 1 drawing = Drawing(self.entities, self.statistic, lines) drawing.rooms = self.rooms drawing.drawing_id = self.drawing_id # TODO this needs to be improved for deleted rooms drawing.room_counter = len(self.rooms) + 1 return drawing except Exception as e: print(e) return None
def draw(self): Drawing.loadScene(self.texture[self.turn]) height = 0.05 a = height * 230 print(a) p = [v / 3 + self.eye[i] for i, v in enumerate(self.vector)] glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex3f(p[0], p[1], 0) glTexCoord2f(0, 1) glVertex3f(p[0], p[1], height) glTexCoord2f(1, 1) glVertex3f(p[0] + self.normalVector[0] / a, p[1] + self.normalVector[1] / a, height) glTexCoord2f(1, 0) glVertex3f(p[0] + self.normalVector[0] / a, p[1] + self.normalVector[1] / a, 0) glEnd()
def __init__(self, eye): self.eye = eye self.axis = [0, 0, 1] self.speed = 0.0 self.acel = 0.0000005 self.throttle = False self.turnD = {'right': 1, 'left': -1, 'none': 0} self.texture = { 'right': Drawing.getTexture('images/yoshiRight.png'), 'left': Drawing.getTexture('images/yoshiLeft.png'), 'none': Drawing.getTexture('images/yoshiStraight.png') } self.turn = 'none' self.vector = 1, 0 self.prof = 60 self.lookat = [ v * self.prof + self.eye[i] for i, v in enumerate(self.vector) ] + [-1]
class GameField(BoxLayout): def __init__(self, overlay, **kwargs): super().__init__(**kwargs) # creating an interface self.controller = overlay self.size_hint = (.8, .8) self.orientation = 'vertical' # starting the gameloop self.event = Clock.schedule_interval(self.mainloop, 0) # create main canvas self.GAME = Widget() self.GAME.canvas = Canvas() self.add_widget(self.GAME) # game classes self.player = Player() self.sprites = Sprites() self.drawing = Drawing(self.GAME.canvas, None) # draw borders with self.canvas.after: Color(.05, .05, .05) Rectangle(pos=(0, 0), size=(NULLX, REAL_SCREEN_Y)) Color(.01, .01, .01) Rectangle(pos=(NULLX, REAL_SCREEN_Y - NULLY), size=(REAL_SCREEN_X - NULLX, NULLY)) Color(.01, .01, .01) Rectangle(pos=(NULLX, 0), size=(REAL_SCREEN_X - NULLX, NULLY)) Color(.05, .05, .05) Rectangle(pos=(REAL_SCREEN_X - NULLX, 0), size=(REAL_SCREEN_X, REAL_SCREEN_Y)) def mainloop(self, dt): self.controller.fps_label_update(dt) self.GAME.canvas.clear() # processing the movement for btn in self.controller.btns: if btn.state == 'down': self.player.lookbehind(btn.text) if self.controller.joystick.pad != [0.0, 0.0]: self.player.movement(self.controller.joystick) # draw self.drawing.background(self.player.angle) walls = ray_casting(self.player, self.drawing.textures) self.drawing.world(walls + [ obj.object_locate(self.player) for obj in self.sprites.list_of_objects ]) self.drawing.mini_map(self.player) # self.drawing.field(self.player) self.drawing.sight()
def draw(self, contours=False, lines=False, corners=False): if contours: Drawing.draw_contours(self._frame) if lines: Drawing.detect_lines(self._frame) if corners: Drawing.detect_corners(self._frame) Drawing.match_and_render(self._frame, self._img_marker, self._model, const.METHOD_ORB)
def ParseDrawingsFile(fileName): """ This function reads the input file and returns a list of drawings """ drawings = [] f = open(fileName) for line in f: lsplit = line.split() drawings.append(Drawing(datetime.strptime(lsplit[0], "%m/%d/%Y"), lsplit[1:6], lsplit[6])) f.close() return drawings
def serve_starting_page(s): file = s.path.replace('/start.html?f=', '') # Basic protection against evil fake file locations if ('http://' in file) or ('..' in file) or ('/' in file): s.serve_error_page(403) return file = './uploads/' + file # Todo: error handling here - what if the file isn't found? d = Drawing(filename=file) instructions = d.instructions() s.serve_headers(status=200, content_type='text/html') s.wfile.write(bytes(start_page, encoding='ISO-8859-1')) com = Communicator() for i in instructions: print("Sending instruction to drawbot: " + i) com.sendcommand(i) com.close()
def draw(self): Drawing.loadScene(self.circuit) self.placeScene() Drawing.loadScene(self.mountains) self.placeSceneArround(250, 8, 10) Drawing.loadScene(self.trees) self.placeSceneArround(18, 5, 0.8)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.drawing = Drawing() self.setCentralWidget(self.drawing) #sets up a drawing object as the central widget for the mainwindow self.createActions() #creates actions used in the mainwindow self.createMenus() #creates menus for the mainwindow #sets up the mainwindow's title and size self.setWindowTitle(self.tr("Drawing Program")) self.resize(800,600) self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
def __init__(self, fe, ourgame): random.seed() self.fe = fe self.ourgame = ourgame self.statesize = 0 self.statepos = 0 self.states = list() self.params = ourgame.default_params() self.game_id_change_notify_function = None self.game_id_change_notify_ctx = None # TODO: implement environment variable default settings self.curparams = None self.desc = None self.privdesc = None self.seedstr = None self.aux_info = None self.genmode = GOT_NOTHING self.drawstate = None self.oldstate = None self.presets = list() self.preset_names = list() self.preset_encodings = list() self.anim_time = float(0) self.anim_pos = float(0) self.flash_time = float(0) self.flash_pos = float(0) self.dir = 0 self.ui = None self.pressed_mouse_button = 0 self.laststatus = None self.timing = False self.elapsed = float(0) self.tilesize = 0 self.winwidth = 0 self.winheight = 0 self.drawing = Drawing(fe, self) self.reset_tilesize()
class MidEnd(object): def __init__(self, fe, ourgame): random.seed() self.fe = fe self.ourgame = ourgame self.statesize = 0 self.statepos = 0 self.states = list() self.params = ourgame.default_params() self.game_id_change_notify_function = None self.game_id_change_notify_ctx = None # TODO: implement environment variable default settings self.curparams = None self.desc = None self.privdesc = None self.seedstr = None self.aux_info = None self.genmode = GOT_NOTHING self.drawstate = None self.oldstate = None self.presets = list() self.preset_names = list() self.preset_encodings = list() self.anim_time = float(0) self.anim_pos = float(0) self.flash_time = float(0) self.flash_pos = float(0) self.dir = 0 self.ui = None self.pressed_mouse_button = 0 self.laststatus = None self.timing = False self.elapsed = float(0) self.tilesize = 0 self.winwidth = 0 self.winheight = 0 self.drawing = Drawing(fe, self) self.reset_tilesize() def reset_tilesize(self): self.preferred_tilesize = self.ourgame.preferred_tilesize def set_params(self, params): self.ourgame.free_params(self.params) self.params = self.ourgame.dup_params(params) def size_new_drawstate(self): if self.tilesize <= 0: return self.winwidth, self.winheight = self.ourgame.compute_size(self.params, self.tilesize) self.ourgame.set_size(self.drawing, self.drawstate, self.params, self.tilesize) def force_redraw(self): if self.drawstate: self.ourgame.free_drawstate(self.drawing, self.drawstate) self.drawstate = self.ourgame.new_drawstate(self.drawing, self.states[0].state) self.size_new_drawstate() self.redraw() def new_game(self): self.free_game() if self.curparams: self.ourgame.free_params(self.curparams) self.curparams = self.ourgame.dup_params(self.params) self.desc, self.aux_info = self.ourgame.new_desc(self.curparams, self.drawing) self.states.append( State(self.ourgame.new_game(self, self.params, self.desc), movetype=NEWGAME)) if self.ourgame.can_solve and self.aux_info: try: movestr = self.ourgame.solve(self.states[0].state, self.states[0].state, self.aux_info) except GameError as e: print e.message raise s = self.ourgame.execute_move(self.states[0].state, movestr) if not s: raise GameError('failed to execute solver in new game') self.statepos = 1 self.drawstate = self.ourgame.new_drawstate(self.drawing, self.states[0].state) self.elapsed = float(0) self.ourgame.free_ui(self.ui) self.ui = self.ourgame.new_ui(self.states[0].state) def restart_game(self): if self.statepos == 1: return self.ourgame.new_game(self, self.params, self.desc) # TODO: stop_anim # TODO: purge_states # TODO: setup first state # TODO: ourgame.changed_state # TODO: finish_move # TODO: redraw def really_process_key(x, y, button): game = self.ourgame oldstate = game.dup_game(self.states[self.statepos - 1].state) type = MOVE gottype = False ret = 1 movestr = game.interpret_move(self.states[self.statepos-1].state, self.ui, self.drawstate, x, y, button) return ret def process_key(x, y, button): ret = 1 if IS_MOUSE_DRAG(button) or IS_MOUSE_RELEASE(button): if self.pressed_mouse_button: if IS_MOUSE_DRAG(button): button = self.pressed_mouse_button + (LEFT_DRAG - LEFT_BUTTON) else: button = self.pressed_mouse_button + (LEFT_RELEASE - LEFT_BUTTON) else: return ret elif IS_MOUSE_DOWN(button) and self.pressed_mouse_button: if self.ourgame.flags & BUTTON_BEATS(self.pressed_mouse_button, button): return ret ret = 1 if ret and self.really_process_key(x, y, ( self.pressed_mouse_button + (LEFT_RELEASE - LEFT_BUTTON))) else 0 if button == ord('\n') or button == ord('\r'): button = CURSOR_SELECT if button == ord(' '): button = CURSOR_SELECT2 if button == 0177: button = ord('\b') ret = 1 if ret and self.really_process_key(x, y, button) else 0 if IS_MOUSE_RELEASE(button): self.pressed_mouse_button = 0 elif IS_MOUSE_DOWN(button): self.pressed_mouse_button = button return ret def redraw(self): assert(self.drawing) if self.statepos > 0 and self.drawstate != None: self.drawing.start_draw() if self.oldstate: assert(self.dir != 0) self.ourgame.redraw(self.drawing, self.drawstate, self.oldstate, self.states[self.statepos-1].state, self.dir, self.ui) else: self.ourgame.redraw(self.drawing, self.drawstate, None, self.states[self.statepos-1].state, +1, self.ui) self.drawing.end_draw() def free_game(self): while len(self.states) > 0: self.ourgame.free_game(len(self.states)) self.states.pop() def free(self): self.free_game() self.drawing = None self.ourgame.free_params(self.params) self.params = None self.presets = None self.preset_names = None self.preset_encodings = None self.ui = None self.curparams = None self.laststatus = None def colours(self): return self.ourgame.colours(self.fe) def num_presets(self): if len(self.presets) == 0: while True: preset, name = self.ourgame.fetch_preset(len(self.presets)) if not name and not preset: break self.presets.append(preset) self.preset_names.append(name) self.preset_encodings.append(self.ourgame.encode_params(preset, True)) # TODO: Load environment-based extensions to the preset list return len(self.presets) def fetch_preset(self, n): assert(n >=0 and n<len(self.presets)) return (self.presets[n], self.preset_names[n]) def which_preset(self): encoding = self.ourgame.encode_params(self.params, True) return self.preset_encodings.index(encoding) def wants_statusbar(self): return self.ourgame.wants_statusbar def size(self, x, y, user_size): if self.drawstate and self.tilesize > 0: self.ourgame.free_drawstate(self.drawing, self.drawstate) self.drawstate = self.ourgame.new_drawstate(self.drawing, self.states[0].state) if user_size: max = 1 while True: max *= 2 rx, ry = self.ourgame.compute_size(self.params, max) if rx > x or ry > y: break else: max = self.preferred_tilesize + 1 min = 1 while max - min > 1: mid = (max + min) / 2 rx, ry = self.ourgame.compute_size(self.params, mid) if rx <= x and ry <= y: min = mid else: max = mid self.tilesize = min if user_size: self.preferred_tilesize = self.tilesize self.size_new_drawstate() return (self.winwidth, self.winheight) def rewrite_statusbar(self, text): if self.laststatus != text: self.laststatus = text if self.ourgame.is_timed: return '00:00 {}'.format(text) else: return text
class Parse(object): def __init__(self): self._pen_style_list = ['b-', 'r-o', 'g-*'] self._draw = Drawing() pass def get_cur_x(self): return self._draw.get_cur_x() def get_cur_y(self): return self._draw.get_cur_y() def get_style(self): return self._draw.get_stype() def get_status(self): return self._draw.get_status() def show(self): return self._draw.show() def parse_one_line(self, line): line2 = line = line.strip() if line.find('#') != -1: line2 = line[0:line.find('#')] # remove comments words = line2.split() if len(words) == 0: return if words[0] == 'P': assert(len(words) == 2) self._draw.set_style(self._pen_style_list[int(words[1])]) elif words[0] == 'D': assert(len(words) == 1) self._draw.pen_down() elif words[0] == 'U': assert(len(words) == 1) self._draw.pen_up() elif words[0] == 'W': assert(len(words) == 2) self._draw.line_left(int(words[1])) elif words[0] == 'N': assert(len(words) == 2) self._draw.line_up(int(words[1])) elif words[0] == 'E': assert(len(words) == 2) self._draw.line_right(int(words[1])) elif words[0] == 'S': assert(len(words) == 2) self._draw.line_down(int(words[1])) else: print "Error: Un-supported Action!, in line \"" + line + "\"" assert(1)
def __init__(self): self._pen_style_list = ['b-', 'r-o', 'g-*'] self._draw = Drawing() pass
class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.drawing = Drawing() self.setCentralWidget(self.drawing) #sets up a drawing object as the central widget for the mainwindow self.createActions() #creates actions used in the mainwindow self.createMenus() #creates menus for the mainwindow #sets up the mainwindow's title and size self.setWindowTitle(self.tr("Drawing Program")) self.resize(800,600) self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) def closeEvent(self, event): ''' Creates an event that describes how to act when trying to close the window. If current drawing hasn't been saved, the program asks the user if they want to save the drawing or discard it, and then it can close the window. ''' if self.maybeSave(): event.accept() else: event.ignore() def open(self): ''' Creates an event that describes how to act when trying to open a file. If current drawing hasn't been saved, the program asks the user if they want to save the drawing or discard it, and then it can return to opening a file from the computer's file system. ''' if self.maybeSave(): fileName = QtGui.QFileDialog.getOpenFileName(self,self.tr("Open File"), QtCore.QDir.currentPath(), self.tr("Text files (*.txt)")) try: self.drawing.openText(fileName) except: raise IOError def new(self): ''' This method was created for the 'New'-action; it determines what happens when the user clicks 'New'; it calls the drawing's newImage-method. ''' if self.maybeSave(): self.drawing.newImage() def selectcolor(self): ''' This method enables the user to change the color they are drawing with, using QColorDIalog ''' color = QtGui.QColorDialog.getColor(self.drawing.penColor()) newColor = QtGui.QColor(color) if newColor.isValid(): self.drawing.setPenColor(newColor) def penWidth(self): ''' This method inables the user to change the width of the pen they are drawing with ''' newWidth, ok = QtGui.QInputDialog.getInteger(self, self.tr("Pen Width"),self.tr("Select pen width:"), self.drawing.penWidth(), 1, 50, 1) if ok: self.drawing.setPenWidth(newWidth) self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) def createActions(self): ''' Creates actions that the user can do in the mainwindow, and connects the actions to methods described elsewhere in the program ''' self.openAct = QtGui.QAction(self.tr("&Open..."), self) self.openAct.setShortcut(self.tr("Ctrl+O")) self.connect(self.openAct, QtCore.SIGNAL("triggered()"), self.open) self.saveAsAct = QtGui.QAction(self.tr("&Save As"), self) self.saveAsAct.setShortcut(self.tr("Ctrl+S")) self.connect(self.saveAsAct, QtCore.SIGNAL("triggered()"), self.save) self.exitAct = QtGui.QAction(self.tr("&Exit"), self) self.exitAct.setShortcut(self.tr("Ctrl+Q")) self.connect(self.exitAct, QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("close()")) self.clearScreenAct = QtGui.QAction("&Clear Screen", self) self.clearScreenAct.setShortcut(self.tr("Ctrl+L")) self.connect(self.clearScreenAct, QtCore.SIGNAL("triggered()"), self.drawing.clearImage) self.selectcolorAct = QtGui.QAction(self.tr("&Select Color..."), self) self.connect(self.selectcolorAct, QtCore.SIGNAL("triggered()"), self.selectcolor) self.penWidthAct = QtGui.QAction(self.tr("Pen &Width..."), self) self.connect(self.penWidthAct, QtCore.SIGNAL("triggered()"), self.penWidth) self.lineAct = QtGui.QAction(self.tr("Draw Line"),self) self.connect(self.lineAct,QtCore.SIGNAL("triggered()"), self.drawing.changeToLine) self.rectAct = QtGui.QAction(self.tr("Draw Rectangle"),self) self.connect(self.rectAct,QtCore.SIGNAL("triggered()"), self.drawing.changeToRect) self.circAct = QtGui.QAction(self.tr("Draw Circle"),self) self.connect(self.circAct,QtCore.SIGNAL("triggered()"), self.drawing.changeToCircle) self.newScreenAct = QtGui.QAction(self.tr("&New"), self) self.newScreenAct.setShortcut(self.tr("Ctrl+N")) self.connect(self.newScreenAct, QtCore.SIGNAL("triggered()"), self.new) self.undoAct = QtGui.QAction(self.tr("&Undo"), self) self.undoAct.setShortcut(self.tr("Ctrl+U")) self.connect(self.undoAct, QtCore.SIGNAL("triggered()"), self.drawing.undostack.undo) self.getListAct = QtGui.QAction(self.tr("List of shapes..."), self) self.connect(self.getListAct, QtCore.SIGNAL("triggered()"), self.drawing.getShapeList) #this act was mainly done in purpose of testing that the shapeslist includes all of the visible shapes self.cbutton = QtGui.QPushButton(self) self.cbutton.setIcon(QtGui.QIcon('circle.png')) self.connect(self.cbutton, QtCore.SIGNAL("clicked()"), self.drawing.changeToCircle) self.rbutton = QtGui.QPushButton(self) self.rbutton.setIcon(QtGui.QIcon('rectangle.png')) self.connect(self.rbutton, QtCore.SIGNAL("clicked()"), self.drawing.changeToRect) self.lbutton = QtGui.QPushButton(self) self.lbutton.setIcon(QtGui.QIcon('line_normal_begin.png')) self.connect(self.lbutton, QtCore.SIGNAL("clicked()"), self.drawing.changeToLine) self.undobutton = QtGui.QPushButton('Undo') self.connect(self.undobutton, QtCore.SIGNAL("clicked()"), self.drawing.undostack.undo) def createMenus(self): ''' Creates menus and toolbars to store the actions, and adds the actions to them ''' self.fileMenu = QtGui.QMenu(self.tr("&File"), self) self.fileMenu.addAction(self.newScreenAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAsAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.optionMenu = QtGui.QMenu(self.tr("&Options"), self) self.optionMenu.addAction(self.undoAct) self.optionMenu.addAction(self.selectcolorAct) self.optionMenu.addAction(self.penWidthAct) self.optionMenu.addAction(self.lineAct) self.optionMenu.addAction(self.rectAct) self.optionMenu.addAction(self.circAct) self.optionMenu.addSeparator() self.optionMenu.addAction(self.clearScreenAct) self.optionMenu.addAction(self.getListAct) #this act was mainly done in purpose of testing that the shapeslist includes all of the visible shapes self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.optionMenu) toolbar = self.addToolBar('draw') toolbar.addWidget(self.cbutton) toolbar.addWidget(self.rbutton) toolbar.addWidget(self.lbutton) toolbar.addWidget(self.undobutton) def maybeSave(self): ''' This method keeps track of whether or not the drawn image has to be saved before continuing with methods that conflict with the current image. ''' if self.drawing.isModified(): ret = QtGui.QMessageBox.warning(self, "Warning", self.tr("The image has been modified.\n" "Do you want to save your changes?"), QtGui.QMessageBox.Yes | QtGui.QMessageBox.Default, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Escape) if ret == QtGui.QMessageBox.Yes: return self.save() elif ret == QtGui.QMessageBox.Cancel: return False return True def save(self): ''' A method describing the saving of the current image into a text file ''' filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', 'untitled', self.tr("Text files (*.txt)")) if filename: fname = open(filename, 'w') fname.write(self.drawing.formTextList()) fname.close() self.drawing.setModified(False)