def __init__(self, goalie_pos_start, GRID_NUM_HEIGHT=8, GRID_NUM_WIDTH=5, GRID_SIZE=75, draw_scene=True, gridworld=False): self.goalie_pos = goalie_pos_start self.GRID_NUM_HEIGHT = GRID_NUM_HEIGHT self.GRID_NUM_WIDTH = GRID_NUM_WIDTH self.GRID_SIZE = GRID_SIZE self.WIDTH = self.GRID_SIZE * self.GRID_NUM_WIDTH self.HEIGHT = self.GRID_SIZE * self.GRID_NUM_HEIGHT self.num_interations = 0 self.draw_scene = draw_scene self.gridworld = gridworld self.ball_radius = GRID_SIZE / 2 self.reset() if self.draw_scene: stddraw.setXscale(0, self.WIDTH) stddraw.setYscale(0, self.HEIGHT) stddraw.setCanvasSize(self.WIDTH, self.HEIGHT) time.sleep(1)
def canvas(): # set the dimensions of the game grid global grid_h, grid_w grid_h, grid_w = 18, 12 # set the size of the drawing canvas canvas_h, canvas_w = 40 * grid_h, 60 * grid_w stddraw.setCanvasSize(canvas_w, canvas_h) # set the scale of the coordinate system stddraw.setXscale(-0.5, grid_w + 4.5) stddraw.setYscale(-0.5, grid_h - 0.5) # display a simple menu before opening the game display_game_menu(grid_h, grid_w + 5)
def main(): n = int(sys.argv[1]) # number of biased coin flips per trial p = float(sys.argv[2]) # heads with probability p trialCount = int(sys.argv[3]) # number of trials histogram = Histogram(n + 1) for trial in range(trialCount): heads = stdrandom.binomial(n, p) histogram.addDataPoint(heads) stddraw.setCanvasSize(500, 200) stddraw.clear(stddraw.LIGHT_GRAY) histogram.draw() stddraw.show()
def main(): w = stdio.readInt() h = stdio.readInt() stddraw.setCanvasSize(w, h) stddraw.setXscale(0, w) stddraw.setYscale(0, h) stddraw.setPenRadius(.005) while not stdio.isEmpty(): x = stdio.readFloat() y = stdio.readFloat() p = Point(x, y) p.draw() stddraw.show()
def main(): # Test method grid_h, grid_w = 18, 12 # set the size of the drawing canvas canvas_h, canvas_w = 40 * grid_h, 60 * grid_w stddraw.setCanvasSize(canvas_w, canvas_h) # set the scale of the coordinate system stddraw.setXscale(-0.5, grid_w + 4.5) stddraw.setYscale(-0.5, grid_h - 0.5) obj = Tile(Point(2, 4)) obj.draw() stddraw.show() pass
def main(): # Refresh rate (in seconds) for the keyboard. KEYBOARD_REFRESH_DELAY = 0.01 # Specifies superposition window size. SUPERPOSITION_RANGE = 2 # Setup the canvas and scale for the keyboard. stddraw.setCanvasSize(1056, 300) stddraw.setXscale(0, 1056) stddraw.setYscale(0, 300) # Create guitar strings for notes corresponding to the keys in keyboard. keyboard = 'q2we4r5ty7u8i9op-[=zxdcfvgbnjmk,.;/\' ' notes = [] for i in range(len(keyboard)): hz = 440 * 2**((i - 24.0) / 12.0) notes += [guitar_string.create(hz)] pressed = -1 # index of the pressed key start = time.clock() # for refreshing the keyboard while True: # Check if the user has typed a key; if so, process it, ie, pluck # the corresponding string. if stddraw.hasNextKeyTyped(): key = stddraw.nextKeyTyped() if key in keyboard: pressed = index(keyboard, key) guitar_string.pluck(notes[pressed]) if pressed != -1: # Superimpose samples for keys that are within the # 2 * SUPERPOSITION_RANGE window centered at the pressed key. sample = 0.0 b = max(0, pressed - SUPERPOSITION_RANGE) e = min(len(keyboard) - 1, pressed + SUPERPOSITION_RANGE) for i in range(b, e + 1): note = notes[i] sample += guitar_string.sample(note) guitar_string.tic(note) # Play the sample on standard audio. stdaudio.playSample(sample) # Display the keyboard with the pressed key in red, every # KEYBOARD_REFRESH_DELAY seconds. if time.clock() - start > KEYBOARD_REFRESH_DELAY: start = time.clock() draw_keyboard(pressed) stddraw.show(0.0)
def initialize(karel_world): """ :param karel_world: World object that this module can draw :return: None """ global _cell_size global _font_size_small global _font_size_large # determine a reasonable canvas cell and canvas size na = karel_world.num_avenues ns = karel_world.num_streets _cell_size = _calculate_cell_size(na, ns) cell_dimensions = (_cell_size, _cell_size) width = _cell_size * (na + 2) + _cell_size // 2 height = _cell_size * ns + (3 * _cell_size) // 4 stddraw.setCanvasSize(int(width), int(height)) stddraw.setXscale(-0.5, float(na) + 2.0) stddraw.setYscale(-0.5, float(ns) + 0.25) # choose a reasonable font size _font_size_small = max(_cell_size // 4, 8) _font_size_large = max(_cell_size // 3, 11) # print('cell size is', _cell_size) # print('font size is', _font_size_small) # create and scale a Picture object for a beeper global _beeper_picture _beeper_picture = Picture(constants.beeper_image_file(_cell_size)) surface = _beeper_picture._surface _beeper_picture._surface = pygame.transform.scale(surface, cell_dimensions) # create and scale a Picture object for Karel's error state global _error_picture _error_picture = Picture(constants.error_image_file()) surface = _error_picture._surface _error_picture._surface = pygame.transform.scale(surface, cell_dimensions) # create, scale, and rotate Picture objects for each of Karel's directions for angle in [90, 0, 270, 180]: pic = Picture(constants.karel_image_file(_cell_size)) pic._surface = pygame.transform.scale(pic._surface, cell_dimensions) pic._surface = pygame.transform.rotate(pic._surface, angle) _karel_pictures.append(pic)
def main(): WIDTH = 200 # Width of largest disc HEIGHT = 15 # Height of each disc n = int(sys.argv[1]) # number of discs # Set size of window and sale stddraw.setCanvasSize(4 * WIDTH, (n + 3) * HEIGHT) stddraw.setXscale(-1, 3) stddraw.setYscale(0, n + 3) # Solve the Towers of Hanoi with n discs hanoi(n) stddraw.show()
def main(): w = stdio.readInt() h = stdio.readInt() stddraw.setCanvasSize(w, h) stddraw.setXscale(0, w) stddraw.setYscale(0, h) stddraw.setPenRadius(.005) tour = Tour() while not stdio.isEmpty(): x = stdio.readFloat() y = stdio.readFloat() p = Point(x, y) tour.insertSmallest(p) stdio.writef('Tour distance = %f\n', tour.distance()) stdio.writef('Number of points = %d\n', tour.size()) tour.draw() stddraw.show()
def drawBoard(x, y): stddraw.setCanvasSize(600, 750) stddraw.setXscale(0, x) stddraw.setYscale(0, y + 3) stddraw.clear(stddraw.WHITE) #Draw the vertical lines for i in range(x + 1): stddraw.line(i / 1.5, 1, i / 1.5, y + 1) #Draw the horizontal lines for i in range(y + 1): stddraw.line(0, i, x / 1.5, i) drawScore(x, y) drawLogo(x, y) drawTotalScore(x, y, 0)
def main(): r = Rectangle(0, 0, 4, 6) r1 = Rectangle(1, 1, 10, 27) r2 = Rectangle(3, 4, 3, 3) print(r2.intersects(r)) print(r2.contains(r)) print(r2.contains(r2)) print(r1.contains(r)) print(r1.contains(r2)) print(r.contains(r1)) #手工设置画布,否则要判断很多 stddraw.setCanvasSize(1000, 1000) stddraw.setXscale(-17, 17) stddraw.setYscale(-17, 17) r.draw() r1.draw() r2.draw() stddraw.show()
def main(): n = int(sys.argv[1]) p = float(sys.argv[2]) trials = int(sys.argv[3]) t = int(sys.argv[4]) q = evaluate(n, p, trials) stdio.writeln(q) norm = exTimes(n, p, trials, t) phi = stdarray.create1D(n + 1, 0.0) stddev = math.sqrt(n) / 2.0 for i in range(n + 1): phi[i] = gaussian.pdf(i, n / 2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi))) stdstats.plotBars(norm) stdstats.plotLines(phi) stddraw.show()
def draw_map(a): # draws and displays a map based on a 2D array, a, # using the max and min to set the grayscale amin = find_min(a) amax = find_max(a) stddraw.setXscale(-10, len(a[0]) + 10) stddraw.setYscale(-5, len(a) + 5) stddraw.setCanvasSize(int(512*1.5), int(512*len(a)/len(a[0])*1.5)) m = 255 / (amax - amin) b = -m*amin for i in range(len(a)): for j in range(len(a[i])): value = int(m*a[i][j] + b) # print(a[i][j], value) gray = Color(value, value, value) stddraw.setPenColor(gray) stddraw.filledRectangle(j, len(a) - i, 1, 1)
def main(): R = 3 stddraw.setXscale(-5*R,5*R) stddraw.setYscale(-5*R,5*R) stddraw.setCanvasSize(700,700) stddraw.circle(0,0,R) centerPointArray1 = centers(0,0,R) # stddraw.setPenColor(stddraw.RED) # for i in range(-6*R,6*R): # for j in range(-6*R,6*R): # stddraw.line(i,j,i,(6*R)-j) # stddraw.line(i, j, (6*R)-i, j) # stddraw.setPenColor(stddraw.BLACK) for i in range(6): stddraw.circle(centerPointArray1[i][0], centerPointArray1[i][1], R) stddraw.show(50) for i in range(6): centerPointArray2 = centers(centerPointArray1[i][0], centerPointArray1[i][1], R) for j in range(6): stddraw.circle(centerPointArray2[j][0], centerPointArray2[j][1], R) # stddraw.picture('python.png' ,centerPointArray2[j][0], centerPointArray2[j][1] ) for k in range(6): centerPointArray3 = centers(centerPointArray2[k][0], centerPointArray2[k][1], R) for p in range(6): stddraw.circle(centerPointArray3[p][0], centerPointArray3[p][1], R) # stddraw.picture('python.png', centerPointArray3[p][0], centerPointArray3[p][1]) stddraw.show(15) # for i in range(6): # centerPointArray3 = centers(centerPointArray2[i][0], centerPointArray2[i][1], R) # for j in range(6): # stddraw.circle(centerPointArray3[j][0], centerPointArray3[j][1], R) # stddraw.show(50) stddraw.show()
import random import sys import stddraw from rectangle import Rectangle # n = eval(sys.argv[1]) # lo = eval(sys.argv[2]) #为保持画布大小,lo和hi取值,2,6 # hi = eval(sys.argv[3]) n = 3 lo = 2 #为保持画布大小,lo和hi取值,2,6 hi = 6 stddraw.setCanvasSize(1000, 1000) stddraw.setXscale(-6, 6) stddraw.setYscale(-6, 6) i = 0 r = [] while i < n: x = random.randint(-3, 3) y = random.randint(-3, 3) width = random.randint(lo, hi) height = random.randint(lo, hi) r.append(Rectangle(x, y, width, height)) i += 1 area = 0 per = 0 for t in r:
MAX = 255 # n = int(sys.argv[1]) # xc = float(sys.argv[2]) # yc = float(sys.argv[3]) # size = float(sys.argv[4]) n = 512 xc = -.5 yc = 0 size = 2 pic = Picture(n, n) for col in range(n): for row in range(n): x0 = xc - (size / 2) + (size * col / n) y0 = yc - (size / 2) + (size * row / n) z0 = complex(x0, y0) gray = MAX - mandel(z0, MAX) color = Color(gray, gray, gray) pic.set(col, n - 1 - row, color) stddraw.setCanvasSize(n, n) stddraw.picture(pic) stddraw.show() #----------------------------------------------------------------------- # python mandelbrot.py 512 -.5 0 2 # python mandelbrot.py 512 .1015 -.633 .01
# distribution function, thereby allowing easy comparison of the # experimental results to the theoretically predicted results. n = int(sys.argv[1]) trials = int(sys.argv[2]) freq = stdarray.create1D(n+1, 0) for t in range(trials): heads = stdrandom.binomial(n, 0.5) freq[heads] += 1 norm = stdarray.create1D(n+1, 0.0) for i in range(n+1): norm[i] = 1.0 * freq[i] / trials phi = stdarray.create1D(n+1, 0.0) stddev = math.sqrt(n)/2.0 for i in range(n+1): phi[i] = gaussian.pdf(i, n/2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi))) stdstats.plotBars(norm) stdstats.plotLines(phi) stddraw.show() #----------------------------------------------------------------------- # python bernoulli.py 20 100000
def start(): # set the dimensions of the game grid grid_h, grid_w = 20, 12 # set the size of the drawing canvas canvas_h, canvas_w = 40 * grid_h, 40 * grid_w stddraw.setCanvasSize(canvas_w, canvas_h) # set the scale of the coordinate system stddraw.setXscale(-0.5, grid_w - 0.5) stddraw.setYscale(-0.5, grid_h - 0.5) # create the game grid grid = GameGrid(grid_h, grid_w) # create the first tetromino to enter the game grid # by using the create_tetromino function defined below current_tetromino = create_tetromino(grid_h, grid_w) next_tetromino = create_tetromino(grid_h, grid_w) grid.current_tetromino = current_tetromino # display a simple menu before opening the game display_game_menu(grid_h, grid_w) # main game loop (keyboard interaction for moving the tetromino) while True: # check user interactions via the keyboard if stddraw.hasNextKeyTyped(): key_typed = stddraw.nextKeyTyped() # if the left arrow key has been pressed if key_typed == "left": # move the tetromino left by one current_tetromino.move(key_typed, grid) # if the right arrow key has been pressed elif key_typed == "right": # move the tetromino right by one current_tetromino.move(key_typed, grid) # if the down arrow key has been pressed elif key_typed == "down": # move the tetromino down by one # (causes the tetromino to fall down faster) current_tetromino.move(key_typed, grid) # clear the queue that stores all the keys pressed/typed elif key_typed == "up": current_tetromino.rotateTetromino() elif key_typed == "space": temp = current_tetromino.move("down", grid) while (temp): temp = current_tetromino.move("down", grid) stddraw.clearKeysTyped() # move (drop) the tetromino down by 1 at each iteration success = current_tetromino.move("down", grid) # place the tetromino on the game grid when it cannot go down anymore if not success: # get the tile matrix of the tetromino tiles_to_place = current_tetromino.tile_matrix # update the game grid by adding the tiles of the tetromino game_over = grid.update_grid(tiles_to_place) rowSet = rowsToCheck(tiles_to_place) grid.rowCheck(rowSet) columnSet = columnsToCheck(tiles_to_place) grid.sumCheck(columnSet, current_tetromino) # end the main game loop if the game is over if game_over: break # create the next tetromino to enter the game grid # by using the create_tetromino function defined below current_tetromino = next_tetromino grid.current_tetromino = current_tetromino next_tetromino = create_tetromino(grid_h, grid_w) print("Score = " + str(grid.score)) print("Next tetromino type is: " + next_tetromino.type) # display the game grid and as well the current tetromino grid.display() print("Game over")
pic = Picture() for col in range(pic.width()): for row in range(pic.height()): # Compute pixel color. x = 1.0 * col / pic.width() y = 1.0 * row / pic.height() v = 0.0 for i in range(n): v += charges[i].potentialAt(x, y) v = (MAX_GRAY_SCALE / 2.0) + (v / 2.0e10) if v < 0: grayScale = 0 elif v > MAX_GRAY_SCALE: grayScale = MAX_GRAY_SCALE else: grayScale = int(v) color = Color(grayScale, grayScale, grayScale) pic.set(col, pic.height()-1-row, color) # Draw the Picture. stddraw.setCanvasSize(pic.width(), pic.height()) stddraw.picture(pic) stddraw.show() #----------------------------------------------------------------------- # python potential.py < charges.txt
GRID_NUM_HEIGHT = 8 GRID_NUM_WIDTH = 5 GRID_SIZE = 75 # in pixels WIDTH = GRID_SIZE * GRID_NUM_WIDTH HEIGHT = GRID_SIZE * GRID_NUM_HEIGHT #RL constants EPSILON = 1 # greedy police ALPHA = 0.5 # learning rate GAMMA = 1 # discount ITERS = 1000 #iterations UPDATE_FREQ = 60 #How often to update environment stddraw.setXscale(0, WIDTH) stddraw.setYscale(0, HEIGHT) stddraw.setCanvasSize(WIDTH, HEIGHT) agent = rl_agent( list(range(3)), #STAY,LEFT,RIGHT GAMMA, ALPHA, EPSILON) agent.init_q_table() goalie_pos = 3 #randint(0,GRID_NUM_WIDTH-1) ball_x = randint(0, GRID_NUM_WIDTH - 1) ball_y = 0 episodes = 0 steps = 0
# Then, over the course of frameCount frames, gradually replace the # image from sourceFile with the image with the image from targetFile. # Display to standard draw each intermediate image. The images in the # files can be in either JPG or PNG formats. sourceFile = sys.argv[1] targetFile = sys.argv[2] n = int(sys.argv[3]) # number of intermediate frames source = Picture(sourceFile) target = Picture(targetFile) width = source.width() height = source.height() stddraw.setCanvasSize(width, height) pic = Picture(width, height) for t in range(n+1): for col in range(width): for row in range(height): c0 = source.get(col, row) cn = target.get(col, row) alpha = float(t) / float(n) c = blend(c0, cn, alpha) pic.set(col, row, c) stddraw.picture(pic) stddraw.show(1000.0) stddraw.show()
import sys import stdio import random import stddraw import picture as p import pygame pygame.init() pygame.mixer.init() score = 0 number_of_moves = 10 hmatches = [] vmatches = [] stddraw.setCanvasSize(1300, 980) stddraw.setFontSize(70) stddraw.setXscale(0.0, 8.999) stddraw.setYscale(0.0, 9.999) pic1 = p.Picture("strawberry.png") pic2 = p.Picture("lemon.png") pic3 = p.Picture("orange.png") pic4 = p.Picture("pear.png") pic5 = p.Picture("grapes.png") pic6 = p.Picture("watermelon.png") pic7 = p.Picture("background.png") pic8 = p.Picture("heart.png") pic9 = p.Picture("star.png") pic10 = p.Picture("win.png") pic11 = p.Picture("lose.png") v_combo1 = pygame.mixer.Sound('v_combo1.ogg') v_combo2 = pygame.mixer.Sound('v_combo2.ogg') v_combo3 = pygame.mixer.Sound('v_combo3.ogg') v_combo4 = pygame.mixer.Sound('v_combo4.ogg')
# iterations before the Mandelbrot sequence for the corresponding # complex number grows past 2.0, up to 255. MAX = 255 n = int(sys.argv[1]) xc = float(sys.argv[2]) yc = float(sys.argv[3]) size = float(sys.argv[4]) pic = Picture(n, n) for col in range(n): for row in range(n): x0 = xc - (size / 2) + (size * col / n) y0 = yc - (size / 2) + (size * row / n) z0 = complex(x0, y0) gray = MAX - mandel(z0, MAX) color = Color(gray, gray, gray) pic.set(col, n-1-row, color) stddraw.setCanvasSize(n, n) stddraw.picture(pic) stddraw.show() #----------------------------------------------------------------------- # python mandelbrot.py 512 -.5 0 2 # python mandelbrot.py 512 .1015 -.633 .01
import stddraw stddraw.setCanvasSize(500, 500) stddraw.setXscale(-1.0, 1.0) stddraw.setYscale(-1.0, 1.0) radius = .05 rx = .080 ry = .060 vx = .015 vy = .013 while True: # Update position rx = rx + vx ry = ry + vy # Clear the background stddraw.clear(stddraw.LIGHT_GRAY) # Draw the ball on the screen stddraw.setPenColor(stddraw.BLACK) stddraw.filledCircle(rx, ry, radius) # Copy buffer to screen stddraw.show(0) stddraw.pause(20)
def init_stddraw(self, width): stddraw.setXscale(0, width) stddraw.setYscale(0, width) stddraw.setCanvasSize(width, width)
import sys import stddraw import stdrandom from linkedqueue import Queue from histogram import Histogram # Accept float command-line arguments lamb and mu. Simulate an # M/M/1 queue with arrival rate lamb and service rate mu. lamb = float(sys.argv[1]) # Arrival rate mu = float(sys.argv[2]) # Service rate histogram = Histogram(60 + 1) queue = Queue() stddraw.setCanvasSize(700, 500) # Compute time of next arrival. nextArrival = stdrandom.exp(lamb) # Compute time of next completed service. nextService = nextArrival + stdrandom.exp(mu) # Simulate the M/M/1 queue. while True: # Next event is an arrival. while nextArrival < nextService: # Simulate an arrival queue.enqueue(nextArrival) nextArrival += stdrandom.exp(lamb)
# dpsiI/dt = (1/2)d^2 psiR/dx^2 - V(x) psiR # # Ref: P.B. Visscher, A Fast Explicit Algorithm # for the Time-Dependent Schrodinger Equation, # Computers In Physics, 596–598 (Nov/Dec 1991). # # run: % python Schro1DSplit.py # import stddraw import cmath import math from numpy import * # set the canvas size stddraw.setCanvasSize(500,250); # set the axis scales stddraw.setXscale(0.0, 20.0); stddraw.setYscale(-1.5, 1.5); i = 0 n = 0 NX = 400 ic = 200 dx = 20.0/NX # For stable simulation dt < dx dt = dx*dx/2.0; cc = 0.5*dt/(dx*dx)
import stddraw test = matrix_to_complex( generation_test2() ) # если test1 - изменить количество кластеров (2), если test2 - (2), если test3 - (2) # data_arr = [] # будущий массив с данными # data_arr = generation(data_arr) # генерация этого массива data_arr = separation(test) data_learning = learning_data( data_arr[1]) # массив с данными для дообучения, разбитый на группы data_main = data_arr[0] # массив с данными для первого прохода data = Data(data_main) print(data_main) data_sample = data.sample() # выборка данных для иерархической кластеризации stddraw.setCanvasSize(CANVAS, CANVAS) stddraw.setYscale(0, CANVAS) stddraw.setXscale(0, CANVAS) for i in range(len(data_main)): stddraw.point(data_main[i][0][0], data_main[i][0][1]) stddraw.show(10000) for i in range(len(data_sample)): stddraw.setPenColor(stddraw.GREEN) stddraw.point(data_sample[i][0][0], data_sample[i][0][1]) stddraw.show(1000) ierarhic = Ierarhic(data_sample) clasters = ierarhic.Ierarhic1( ) # иерархическая кластеризация, итог - массив с кластерами centers_of_clasters = Ierarhic2(clasters) # центры полученных кластеров
# file, and display the image scaled to width w and height h. fileName = sys.argv[1] w = int(sys.argv[2]) h = int(sys.argv[3]) source = Picture(fileName) target = Picture(w, h) for tCol in range(w): for tRow in range(h): sCol = tCol * source.width() // w sRow = tRow * source.height() // h target.set(tCol, tRow, source.get(sCol, sRow)) stddraw.setCanvasSize(w, h) stddraw.picture(target) stddraw.show() #----------------------------------------------------------------------- # python scale.py mandrill.jpg 800 800 # python scale.py mandrill.jpg 600 300 # python scale.py mandrill.jpg 200 400 # python scale.py mandrill.jpg 200 200 # python scale.py mandrill.png 200 200
import sys import stddraw import luminance from picture import Picture pic = Picture(sys.argv[1]) for col in range(pic.width()): for row in range(pic.height()): pixel = pic.get(col, row) gray = luminance.toGray(pixel) pic.set(col, row, gray) stddraw.setCanvasSize(pic.width(), pic.height()) stddraw.picture(pic) stddraw.show()
import stddraw from picture import Picture import sys from threshold import threshold if len(sys.argv) < 3: print """ Usage: python %s <run #> <frame delay> [<threshold>] """ % sys.argv[0] sys.exit() stddraw.setCanvasSize(640, 480) run = int(sys.argv[1]) delay = int(sys.argv[2]) tau = None if len(sys.argv) > 3: tau = float(sys.argv[3]) for frame in range(200): pic = Picture('data/run_%d/frame%05d.jpg' % (run, frame)) if tau: threshold(pic, tau) stddraw.picture(pic) stddraw.show(delay)
from charge import Charge import stddraw import stdarray from picture import Picture from color import Color a = stdarray.create1D(3) a[0] = Charge(.4, .6, 50) a[1] = Charge(.5, .5, -5) a[2] = Charge(.6, .6, 50) MAX_GRAY_SCALE = 255 p = Picture() stddraw.setCanvasSize(p.width(),p.height()) for t in range(100): # Compute the picture p. for col in range(p.width()): for row in range(p.height()): # Compute pixel color. x = 1.0 * col / p.width() y = 1.0 * row / p.height() v = 0.0 for i in range(3): v += a[i].potentialAt(x, y) v = (MAX_GRAY_SCALE / 2.0) + (v / 2.0e10) if v < 0: grayScale = 0 elif v > MAX_GRAY_SCALE: grayScale = MAX_GRAY_SCALE else:
# and the waved image. pic1 = Picture(sys.argv[1]) width = pic1.width() height = pic1.height() pic2 = Picture(width, height) # Apply the wave filter. for col in range(width): for row in range(height): cc = col rr = int(row + 20.0 * math.sin(col * 2.0 * math.pi / 64.0)) if (rr >= 0) and (rr < height): pic2.set(col, row, pic1.get(cc, rr)) stddraw.setCanvasSize(width, height) stddraw.picture(pic2) stddraw.show() #----------------------------------------------------------------------- # python wave.py mandrill.jpg # python wave.py mandrill.png # python wave.py darwin.jpg # python wave.py darwin.png
if n == 0: myTurtle.goForward(stepSize) return koch(n-1, stepSize, myTurtle) myTurtle.turnLeft(60.0) koch(n-1, stepSize, myTurtle) myTurtle.turnLeft(-120.0) koch(n-1, stepSize, myTurtle) myTurtle.turnLeft(60.0) koch(n-1, stepSize, myTurtle) # Accept integer n as a command-line argument. Plot a Koch curve of # order n to standard draw. n = int(sys.argv[1]) stddraw.setCanvasSize(512, 256) stddraw.setYscale(-.1, 0.4) stddraw.setPenRadius(0.0) stddraw.clear(stddraw.LIGHT_GRAY) stepSize = 1.0 / (3.0 ** n) myTurtle = Turtle(0.0, 0.0, 0.0) koch(n, stepSize, myTurtle) stddraw.show() #----------------------------------------------------------------------- # python koch.py 0 # python koch.py 1 # python koch.py 2
def main(): # Open file from the command liness try: k = sys.argv[1] # number of collinear points to search file_name = sys.argv[2] # file name path = Path.cwd() file_path = path / 'data' / file_name if k <= 2: raise AssertionError("We neead at least search for three collinear points") except: k = 4 file_name = 'input20.txt' # defaul file path = Path.cwd() file_path = path / 'data' / file_name data = open(file_path) n = data.readline() points = numpy.empty(int(n), dtype=object) i = 0 # print("n = ",points.size) for line in data: x, y = line.split() x = int(x) y = int(y) # print(x, " , ", y) points[i] = Point.Point(x, y) i += 1 # * Random points generator # Instead of read the data from files, uncomment the lines below to generate them randomly # and set k to search for at leat k collinear points k = 4 points = randomPointsGenerator.random_points(2000) # set canvas size screen_width_max = max(points,key=lambda a:a._x)._x screen_high_max = max(points,key=lambda a:a._y)._y screen_width_min = min(points,key=lambda a:a._x)._x screen_high_min = min(points,key=lambda a:a._y)._y width_buffer = int(screen_width_max*0.01) high_buffer = int(screen_high_max*0.01) stddraw.setCanvasSize(800, 800) stddraw.setXscale(screen_width_min - width_buffer, screen_width_max + width_buffer) stddraw.setYscale(screen_high_min - high_buffer , screen_high_max + high_buffer) stddraw.setPenRadius(0.01) #print and draw the line segments collinear_points = fastSearchCollinearPoints(points, k) for segment in collinear_points.segments(): print(segment) segment.draw() stddraw.setPenRadius(0.005) stddraw.setPenColor(stddraw.RED) for p in points: p.draw() print(collinear_points.numberOfSegments()) stddraw.show()