def __init__(self, location, mass, color): self.location = location self.mass = mass self.color = color self.velocity = Vec2d(0, 0) self.acceleration = Vec2d(0, 0) self.topspeed = 9
def __init__(self): self.d = Vec2d() self.p = Vec2d(random.randint(20, 500), random.randint(20, 460)) self.hit = 0 self.mass = random.randint(4, 18) self.hue = random.randint(0, 360) r, g, b = hsvRgb(self.hue, 0.7, 0.5) self.color = Color(r, g, b)
def find_target(self): if self.eaten: self.targetrow = 16 self.targetcol = 14 elif self.type == 'b': self.targetrow = self.p_man.row self.targetcol = self.p_man.col if len(self.maze.dots.sprites()) < 131 >= 65 and self.blinky_lvl == 0: self.speed *= 0.95 self.blinky_lvl = 1 elif len(self.maze.dots.sprites()) < 65 and self.blinky_lvl == 1: self.speed *= 0.95 self.blinky_lvl = 2 elif self.type == 'p': if self.p_man.dir == 'up': self.targetrow = self.p_man.row - 4 self.targetcol = self.p_man.col elif self.p_man.dir == 'down': self.targetrow = self.p_man.row + 4 self.targetcol = self.p_man.col elif self.p_man.dir == 'left': self.targetcol = self.p_man.col - 4 self.targetrow = self.p_man.row elif self.p_man.dir == 'right': self.targetcol = self.p_man.col + 4 self.targetrow = self.p_man.row print(str(self.targetcol) + ' ' + str(self.targetrow)) elif self.type == 'i': p_vec = Vec2d(self.p_man.col, self.p_man.row) if self.p_man.dir == 'up': p_vec.x -= 2 elif self.p_man.dir == 'down': p_vec += 2 elif self.p_man.dir == 'right': p_vec.x += 2 elif self.p_man.dir == 'left': p_vec.x -= 2 b_vec = Vec2d(self.blinky.col, self.blinky.row) col_vec = p_vec - b_vec col_vec *= 2 r_vec = b_vec + col_vec self.targetcol = r_vec.x self.targetrow = r_vec.y elif self.type == 'c': p_vec = Vec2d(self.p_man.col, self.p_man.row) c_vec = Vec2d(self.col, self.row) dist = c_vec.get_distance(p_vec) if dist > 8: self.targetrow = self.p_man.row self.targetcol = self.p_man.col else: self.targetcol = 0 self.targetrow = 30
def __init__(self): self.d = Vec2d() self.p = Vec2d(random.randint(20, 140), random.randint(20, 100)) self.hit = 0 self.mass = random.randint(4, 18) r, g, b = hsvRgb(self.mass * 20, 0.7, 0.5) self.color = Color(r, g, b) r, g, b = hsvRgb(self.mass * 20, 0.5, 0.9) self.color2 = Color(r, g, b) r, g, b = hsvRgb(self.mass * 20, 0.8, 0.7) self.color3 = Color(r, g, b)
def move(self, cars): for car in cars: start = time.time() oldDir = Vec2d(car.dir.x, car.dir.y) oldPos = Vec2d(car.pos.x, car.pos.y) car.update() newPos = car.getPos() newDir = car.getDir() deltaPos = newPos - oldPos deltaAngle = oldDir.get_angle_between(newDir) self.updateTime += time.time() - start if Const.SHOW_CARS or car.isJunior(): self.moveCarDisplay(car, deltaPos, deltaAngle) if self.isLearning: self.learner.noteCarMove(oldPos, newPos)
def heartbeat(self): oldDir = Vec2d(self.junior.dir.x, self.junior.dir.y) oldPos = Vec2d(self.junior.pos.x, self.junior.pos.y) quitAction = self.junior.action() carProb = self.model.getProbCar() if carProb and Const.AUTO: agentGraph = self.model.getJuniorGraph() self.junior.autonomousAction(carProb, agentGraph) if quitAction: self.quit = True return self.junior.update() self.collision = self.model.checkCollision(self.junior) self.victory = self.model.checkVictory() newPos = self.junior.getPos() newDir = self.junior.getDir() deltaPos = newPos - oldPos deltaAngle = oldDir.get_angle_between(newDir) Display.move(self.junior, deltaPos) Display.rotate(self.junior, deltaAngle)
def update(self, mouse_x, mouse_y): mouse_loc = Vec2d(mouse_x, mouse_y) dir = mouse_loc - self.location dir = dir.normalized() dir *= 0.5 self.acceleration = dir self.velocity += self.acceleration if self.velocity.length > self.topspeed: self.velocity.length = self.topspeed self.location += self.velocity
def __init__(self, init_pos, init_dir, color=colors.g, size=500): pygame.sprite.Sprite.__init__(self) self._image = pygame.Surface((500, 500)) self._image.fill((0, 0, 0)) self._image.set_colorkey((0, 0, 0)) self.ta = (250, 100) self.tb = (50, 300) self.tc = (450, 300) pygame.draw.polygon(self._image, color, [self.ta, self.tb, self.tc], 40) if size: scale = 500. / size scaled_im = pygame.transform.smoothscale(self._image, (size, size)) self._image = scaled_im self.ta = (250 / scale, 100 / scale) self.tb = (50 / scale, 300 / scale) self.tc = (450 / scale, 300 / scale) self.te = (250 / scale, 380 / scale) self.tt = (100 / scale, 200 / scale) self.pos = Vec2d(init_pos) # movement direction self.dir = Vec2d(init_dir).normalized() # we are we heading self.heading = Vec2d(init_dir).normalized() self.speed = 0. self.force = 0. self.rect = self._image.get_rect() self.rect.center = init_pos self.render_rotation() self.rotate_points(self.heading.angle - 90)
def __init__(self, init_pos, init_dir, color=colors.g, size=500): pygame.sprite.Sprite.__init__(self) self._image = pygame.Surface((500, 500)) self._image.fill((0, 0, 0)) self._image.set_colorkey((0, 0, 0)) self._image.set_alpha(66) self.ta = (250, 100) self.tb = (50, 300) self.tc = (450, 300) pygame.draw.polygon(self._image, color, [self.ta, self.tb, self.tc], 40) if size: scale = 500. / size key = "" + str(color) + str(scale) if key in Particle.cache: scaled_im = Particle.cache[key] else: scaled_im = pygame.transform.smoothscale( self._image, (size, size)) Particle.cache[key] = scaled_im self._image = scaled_im self.pos = Vec2d(init_pos) # movement direction self.dir = Vec2d(init_dir).normalized() # we are we heading self.heading = Vec2d(init_dir).normalized() self.speed = 0.1 self.force = 0.1 self.rect = self._image.get_rect() self.rect.center = init_pos self.render_rotation()
def doHit(b1, b2): a = b1.d b = b2.d s1 = b1.p s2 = b2.p impact = b - a impulse = (s2 - s1).norm() adb = math.atan2(impulse.y, impulse.x) impactspeed = impact * impulse q = math.sqrt(abs(impactspeed) * b1.mass * b2.mass) * cmp(impactspeed, 0) impulse *= q b1.d = a + impulse / b1.mass b2.d = b - impulse / b2.mass # Keep 'erroff. s = 21 b2.p = b1.p + Vec2d(s * math.cos(adb), s * math.sin(adb))
def update(self, time_passed): self.render_rotation() self.speed *= 0.999 d = Vec2d(self.dir.x * self.speed, self.dir.y * self.speed) #-self.dir.x * self.speed * time_passed, #self.dir.y * self.speed * time_passed) self.pos.x += d.x self.pos.y -= d.y self.rect.centerx = self.pos.x self.rect.centery = self.pos.y a = math.radians(self.heading.angle) d.x += math.cos(a) * self.force d.y += math.sin(a) * self.force self.speed = min(3, d.length) self.dir.angle = math.degrees(math.atan2(d.y, d.x)) super(Ship, self).update()
show_help = not show_help if event.key == pygame.K_KP_MULTIPLY: speed *= 2 if event.key == pygame.K_KP_DIVIDE: speed /= 2 if event.key == pygame.K_KP_MINUS: knots[current_knot].addition_points -= 1 if event.key in range(48, 59): # event.key is number knots[current_knot].color = pygame.Color("white") current_knot = event.key - 48 if event.key == pygame.K_DELETE: knots[current_knot].remove_point() if event.type == pygame.MOUSEBUTTONDOWN: knots[current_knot].add_point( Vec2d(*event.pos), Vec2d(random.random() * 2, random.random() * 2)) gameDisplay.fill((0, 0, 0)) hue = (hue + 1) % 360 knots[current_knot].color.hsla = (hue, 100, 50, 100) for k in knots: k.draw_points(gameDisplay, 'line') if not pause: k.set_points(*SCREEN_DIM, speed) if show_help: draw_help(knots, current_knot) pygame.display.flip()
GRAY_50 = (33, 33, 33, 50) RED_50 = (255, 0, 0, 50) GREEN_50 = (0, 255, 0, 50) BLUE_50 = (0, 0, 255, 50) BLACK = (0, 0, 0) WHITE = (255, 255, 255) NUM_MOVERS = 50 movers = [] for _ in range(NUM_MOVERS): #random_color = random.choice([GRAY_50, RED_50, GREEN_50, BLUE_50]) random_color = GRAY_50 random_location = Vec2d(random.randint(0, WIDTH), random.randint(0, HEIGHT)) random_mass = random.uniform(0.5, 4) movers.append(Mover(random_location, random_mass, random_color)) pygame.init() FPS = 60 fpsClock = pygame.time.Clock() screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('Bouncing Balls with Force') while True: screen.fill(WHITE)
def __init__(self): self.location = Vec2d(random.randint(0, WIDTH), random.randint(0, HEIGHT)) self.velocity = Vec2d(0, 0) self.topspeed = 9
from pygame.locals import * from sys import exit from vector import Vec2d background_image = '../image/sushiplate.jpg' sprite_image = '../image/fugu.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image).convert() sprite = pygame.image.load(sprite_image) clock = pygame.time.Clock() position = Vec2d(100, 100) heading = Vec2d((0, 0)) while True: for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(background, (0, 0)) screen.blit(sprite, position) time_passed = clock.tick(30) time_passed_seconds = time_passed / 1000 # 在参数前面加*意味着把列表或元组展开 destination = Vec2d(
import pygame from pygame.locals import * from sys import exit from vector import Vec2d from math import * background_image = '../image/sushiplate.jpg' sprite_image = '../image/fugu.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image).convert() sprite = pygame.image.load(sprite_image) clock = pygame.time.Clock() sprite_pos = Vec2d(200, 150) sprite_speed = 300 sprite_rotation = 0 sprite_rotation_speed = 360 while True: for event in pygame.event.get(): if event.type == QUIT: exit() pressed_keys = pygame.key.get_pressed() rotation_direction = 0 movement_direction = 0 # 更改角度 if pressed_keys[K_LEFT]: rotation_direction = +1
pygame.display.set_caption('Fluid Resistance') GRAY_50 = (33, 33, 33, 50) AQUA = (0, 255, 255) BLACK = (0, 0, 0) WHITE = (255, 255, 255) liquid = Liquid(0, HEIGHT / 2, WIDTH, HEIGHT / 2, 0.1) NUM_MOVERS = 25 movers = [] for _ in range(NUM_MOVERS): color = GRAY_50 random_location = Vec2d(random.randint(0, WIDTH), random.randint(0, HEIGHT / 20)) random_mass = random.uniform(0.5, 4) movers.append(Mover(random_location, random_mass, color)) while True: screen.fill(WHITE) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() liquid.display() for mover in movers: if mover.is_inside(liquid):
def update(self, move): for explosion in self.explosions: if (pygame.time.get_ticks() - explosion.time_start) >= 100: self.explosions.remove(explosion) if not self.awake: if self.type == 'p': if pygame.time.get_ticks() - self.start_time > 2500: self.leave_house() elif self.type == 'i': if len(self.maze.dots.sprites()) <= 202: self.leave_house() elif self.type == 'c': if len(self.maze.dots.sprites()) <= 154: self.leave_house() else: self.leave_house() if pygame.time.get_ticks() - self.timer >= self.speed: self.animate() self.timer = pygame.time.get_ticks() if self.eaten: self.speed = 100 if self.row == 16 and self.col == 14: self.awake = False if pygame.time.get_ticks() - self.timer >= self.speed and self.awake: if move: self.col = self.nextcol self.row = self.nextrow self.dir = self.nextdir next_space = {} if self.dir == 'up': next_space = {'row': self.row - 1, 'col': self.col} elif self.dir == 'left': if self.col == 0 and self.row == 16: next_space = {'row': self.row, 'col': 27} else: next_space = {'row': self.row, 'col': self.col - 1} elif self.dir == 'down': next_space = {'row': self.row + 1, 'col': self.col} elif self.dir == 'right': if self.col == 27 and self.row == 16: next_space = {'row': self.row, 'col': 0} else: next_space = {'row': self.row, 'col': self.col + 1} adj_spaces = [{'row': next_space['row'] - 1, 'col': next_space['col'], 'dir': 'up'}, {'row': next_space['row'], 'col': next_space['col'] - 1, 'dir': 'left'}, {'row': next_space['row'] + 1, 'col': next_space['col'], 'dir': 'down'}, {'row': next_space['row'], 'col': next_space['col'] + 1, 'dir': 'right'}] behind = '' options = [] if self.dir == 'left': behind = 'right' elif self.dir == 'right': behind = 'left' elif self.dir == 'up': behind = 'down' elif self.dir == 'down': behind = 'up' for space in adj_spaces: if space['dir'] == behind: continue temp = self.maze.rows[space['row']] val = temp[space['col']] if val not in self.walls: options.append(space) if self.eaten and val == 'S': options.append(space) if len(options) > 1: self.update_target() target = Vec2d(self.targetcol, self.targetrow) min_distance = 28*36 for o in options: opt_vec = Vec2d(o['col'], o['row']) o['dist'] = opt_vec.get_distance(Vec2d(target)) if o['dist'] < min_distance: self.nextdir = o['dir'] min_distance = o['dist'] self.nextrow = next_space['row'] self.nextcol = next_space['col'] self.animate() self.timer = pygame.time.get_ticks() self.im.blitme()
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('Mover and Attractor') GRAY_50 = (33, 33, 33, 50) AQUA = (0, 255, 255) ORANGE = (255, 191, 0) BLACK = (0, 0, 0) WHITE = (255, 255, 255) NUM_MOVERS = 10 movers = [] for _ in range(NUM_MOVERS): color = GRAY_50 random_location = Vec2d(random.randint(0, WIDTH), random.randint(0, HEIGHT)) random_mass = random.uniform(1, 4) movers.append(Mover(random_location, random_mass, color)) attractor = Attractor(ORANGE) while True: screen.fill(WHITE) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() attractor.display() for mover in movers:
def __init__(self, color): super().__init__() self.location = Vec2d(WIDTH / 2, HEIGHT / 2) self.mass = 40 self.G = 0.2 self.color = color
balls = [] nballs = 25 for i in range(nballs): balls.append(Ball()) lmx = 0 lmy = 0 mx = 0 my = 0 frames = fps = 0 t = time.time() while not keyPressed(): screen.clear() lmx, lmy = mx, my mx, my, mb = mouseX(), mouseY(), mouseB() mdx, mdy = mx - lmx, my - lmy balls[0].d += Vec2d(mdx * 0.3, mdy * 0.3) hits = [] for b in balls: b.hit = 0 for nb, b in enumerate(balls): b.update() for d in balls: if d != b: ds = b.p.dist(d.p) if ds <= 20: hits.append((b.p.tup(), d.p.tup())) b.hit = 1 d.hit = 1 doHit(b, d) doForce(b, d) if 0:
GRAY_50 = (33, 33, 33, 50) RED_50 = (255, 0, 0, 50) GREEN_50 = (0, 255, 0, 50) BLUE_50 = (0, 0, 255, 50) BLACK = (0, 0, 0) WHITE = (255, 255, 255) NUM_MOVERS = 10 movers = [] for _ in range(NUM_MOVERS): #random_color = random.choice([GRAY_50, RED_50, GREEN_50, BLUE_50]) random_color = GRAY_50 random_location = Vec2d(random.randint(0, WIDTH), random.randint(0, HEIGHT)) random_mass = random.uniform(0.5, 4) movers.append(Mover(random_location, random_mass, random_color)) pygame.init() FPS = 60 fpsClock = pygame.time.Clock() screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('Bouncing Balls with Friction') while True: screen.fill(WHITE)
if event.key == pygame.K_F1: show_help = not show_help if event.key == pygame.K_KP_MULTIPLY: speed *= 2 if event.key == pygame.K_KP_DIVIDE: speed /= 2 if event.key == pygame.K_KP_MINUS: knots[current_knot].addition_points -= 1 if event.key in range(48, 59): # event.key is number knots[current_knot].color = pygame.Color("white") current_knot = event.key - 48 if event.key == pygame.K_DELETE: knots[current_knot].remove_point() if event.type == pygame.MOUSEBUTTONDOWN: knots[current_knot].add_point(Vec2d(*event.pos), Vec2d( random.random() * 2, random.random() * 2)) gameDisplay.fill((0, 0, 0)) hue = (hue + 1) % 360 knots[current_knot].color.hsla = (hue, 100, 50, 100) for k in knots: k.draw_points(gameDisplay, 'line') if not pause: k.set_points(*SCREEN_DIM, speed) if show_help: draw_help(knots, current_knot) pygame.display.flip()
balls = [] nballs = 15 for i in range(nballs): balls.append(Ball()) lmx = 0 lmy = 0 mx = 0 my = 0 frames = fps = 0 t = time.time() while not keyPressed(): pg.fillRect(0, 0, 320, 240, 0x004400) lmx, lmy = mx, my mx, my, mb = mouseX(), mouseY(), mouseB() mdx, mdy = mx - lmx, my - lmy balls[0].d += Vec2d(mdx * 0.3, mdy * 0.3) hits = [] for b in balls: b.hit = 0 for nb, b in enumerate(balls): b.update() for d in balls: if d != b: ds = b.p.dist(d.p) if ds <= 40: hits.append((b.p.tup(), d.p.tup())) b.hit = 1 d.hit = 1 doHit(b, d) b.draw(pg, nb == 0) for a, b in hits:
def doForce(b1, b2): h = abs(b1.hue - b2.hue) / 360.0 * -0.00001 vec = Vec2d((b1.p.x - b2.p.x) * h, (b1.p.y - b2.p.y) * h) b1.d = b1.d + vec
import pygame from pygame.locals import * from sys import exit from vector import Vec2d background_image = '../image/sushiplate.jpg' sprite_image = '../image/fugu.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image).convert() sprite = pygame.image.load(sprite_image) clock = pygame.time.Clock() sprite_pos = Vec2d(200, 150) sprite_speed = 300 while True: for event in pygame.event.get(): if event.type == QUIT: exit() pressed_keys = pygame.key.get_pressed() key_direction = Vec2d(0, 0) if pressed_keys[K_LEFT]: key_direction.x = -1 elif pressed_keys[K_RIGHT]: key_direction.x = +1 if pressed_keys[K_UP]: key_direction.y = -1