def seinamaetaisyys(self,yksilo): """ Palauttaa vektorin, joka menee yksilosta lahimpaan seinaan """ lyhin = Vector(1000,1000) for seina in self.seinien_paikkavektorit: etaisyys = seina - yksilo.paikka if (etaisyys.length() < lyhin.length()): lyhin = etaisyys return lyhin
def test_katkaise_vektori(self): """ Tarkastaa etta vektori lyhennetaan tarvittaessa ja etta sita ei lyhenneta kun ei tarvitse. """ vektori = Vector(3,3) alkuperainen_pituus = vektori.length() maksimi_pienempi = 0.5*alkuperainen_pituus maksimi_isompi = 2*alkuperainen_pituus self.yksilo.katkaise_vektori(vektori,maksimi_pienempi) self.assertTrue(vektori.length() == maksimi_pienempi, "Vektorin katkaisu ei toimi") vektori = Vector(3,3) self.yksilo.katkaise_vektori(vektori,maksimi_isompi) self.assertTrue(vektori.length() == alkuperainen_pituus, "Vektorin katkaisemattomuus ei toimi")
def __init__(self, x ,y , size=5, color = (0,0,255), width = 0): self.x = x self.y = y self.size = size self.color = color self.width = width self.massa = 1. self.paikka = Vector(x,y) self.nopeus = Vector(0,0) self.suunta = Vector(0,0) self.voima = Vector(0,0) self.max_voima= 1.0 self.max_nopeus = 1.7
def __init__(self, x, y, world): """x and y are the coordinates of player's hand, world are all objects batarang can collide with """ self.width = BATARANG_WIDTH self.height = BATARANG_HEIGHT self.world = world.level_blocks self.saws = world.level_saws self.x, self.y = x, y self.triangle = Triangle([Vector(self.x, self.y), Vector(self.x + self.width, self.y), Vector(self.x + self.width // 2, self.y + self.height)], (self.x, self.y)) self.triangle.load_avatar("/Environment/{0}".format(BATARANG_IMAGE)) self.triangle.scale_avatar(self.width, self.height) self.direction = Vector(0, 0) self.rotation = 0 self.step = ROTATION_STEP self.speed = 0 self.last_update = 0 self.mouse_position = 0 self.should_fly = False
def setDesiredPosition(self, pos): self.striker.desiredPosition = Vector2(pos) self.limitMovement() self.calculateDesiredVelocity()
def debug_create_objects(object_list): ball = Ball(SCREEN_SIZE, Vector2(50, 50), Vector2(3, 3), [255, 0, 0], 10) object_list.append(ball)
def randomize(self): rand_x = random.randrange(self.pos_range.x) rand_y = random.randrange(self.pos_range.y) self.position = Vector2(rand_x, rand_y)
def step(self, action): ''' calculting the state and giving rewards for the step taken @param action: Angle of rotation @return: state,previousReward,done ''' global destX global destY global originX global originY global done global prevDistance global nonRoadCount # Action got from TD3 rotation = action.item() turnAngle = self.car.move(rotation) self.runCarUi(self.car.position.x, self.car.position.y, destX, destY, turnAngle) xx = destX - self.car.position.x yy = destY - self.car.position.y tempAngle = -(180 / math.pi) * math.atan2( self.car.velocity[0] * yy - self.car.velocity[1] * xx, self.car.velocity[0] * xx + self.car.velocity[1] * yy) orientation = tempAngle / 180 self.currDistance = self.distanceCalc(self.car.position.x, self.car.position.y, destX, destY) delta = prevDistance - self.currDistance state = [self.car.cropping, orientation, -orientation, delta] # Reward alloting if mapForCropping[int(self.car.position.x), int(self.car.position.y)] > 0: self.car.velocity = Vector2(0.5, 0).rotate(self.car.angle) previousReward = -5 else: self.car.velocity = Vector2(1.8, 0).rotate(self.car.angle) previousReward = -2 if self.currDistance < prevDistance: previousReward = 2 #boundary conditions if self.car.position.x < 5: self.car.position.x = 5 previousReward = -15 nonRoadCount += 1 if self.car.position.x > self.width - 5: self.car.position.x = self.width - 5 previousReward = -15 nonRoadCount += 1 if self.car.position.y < 5: self.car.position.y = 5 previousReward = -15 nonRoadCount += 1 if self.car.position.y > self.height - 5: self.car.position.y = self.height - 5 previousReward = -15 nonRoadCount += 1 # Destination check if self.currDistance < 40: originX = destX originY = destY destX, destY = coordinates[np.random.randint(0, len(coordinates))] previousReward = 100 done = True prevDistance = self.currDistance return state, previousReward, done
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 目標:檢查球與擋板是否相碰 核心概念 1. 以 GameState 切換場景 2. 插入圖片 pygame.image.load 3. 偵測鍵盤 event.key == pygame.K_SPACE: ''' import pygame from pygame.math import Vector2 screen = pygame.display.set_mode((640,480)) done = False ballP = Vector2(10,10) ballV = Vector2(5,3) barW = 60 barH = 30 barP = Vector2(200,440) #3-1 hitBar = False #3-2 gameState = True #4-1 failImage = pygame.image.load('fail.png') #4-2 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: #4-3 if event.key == pygame.K_SPACE: gameState = True ballP = Vector2(10,10) ballV = Vector2(5,3)
if active: change=j.get_button(0) if change: sleep(0.2) if j.get_button(0): if switch==True: switch=False print('Arm') else: switch=True print('Motor') if switch: motorcode() vec=Vector2(x1,y1) radius, angle = vec.as_polar() adjusted_angle = (angle+90) % 360 pygame.display.set_caption('Gear {:2d} '.format(gear)) # Rotate the image and get a new rect. player_rotated = pygame.transform.rotozoom(player_img, -adjusted_angle, 1) player_rect = player_rotated.get_rect(center=player_rect.center) screen.fill((30, 30, 30)) screen.blit(player_rotated, player_rect) pygame.display.flip() clock.tick(60) else: arm() except KeyboardInterrupt: print('lol')
def get_random_position(surface): return Vector2( random.randrange(surface.get_width()), random.randrange(surface.get_height()), )
def wrap_position(position, surface): x, y = position w, h = surface.get_size() return Vector2(x % w, y % h)
FPS = 40 clock = pygame.time.Clock() while True: e = pygame.event.poll() if e.type == pygame.QUIT: break elif e.type == pygame.MOUSEBUTTONDOWN: all_bullets.add(Bullet(velocity, start)) all_bullets.update() #calculate destination and velocity end_x = pygame.mouse.get_pos()[0] end_y = pygame.mouse.get_pos()[1] end = Vector2((end_x, end_y)) start = Vector2((WIDTH - 10, player2.y)) velocity = (start - end).normalize() * 16 # Draw / render clock.tick(FPS) player1.update() player2.update() screen.fill(pygame.Color("black")) #don't put after any draw function all_bullets.draw(screen) pygame.draw.rect(screen, pygame.Color("yellow"), pygame.Rect(0, 0, WIDTH, BORDER))
def draw_vector(self, vector, start_pos, length=10): v2 = Vector2(vector.x, vector.y) v2.scale_to_length(length) pygame.draw.line(self.screen, (150, 150, 150), start_pos, v2 + start_pos)
def crosshair(self): return Vector2(self.w * 0.5, self.h * 0.5)
def set_position(self, x, y): self.position = Vector2(x, y)
def get_random_velocity(min_speed, max_speed): speed = random.randint(min_speed, max_speed) angle = random.randrange(0, 360) return Vector2(speed, 0).rotate(angle)
class Batarang(): def __init__(self, x, y, world): """x and y are the coordinates of player's hand, world are all objects batarang can collide with """ self.width = BATARANG_WIDTH self.height = BATARANG_HEIGHT self.world = world.level_blocks self.saws = world.level_saws self.x, self.y = x, y self.triangle = Triangle([Vector(self.x, self.y), Vector(self.x + self.width, self.y), Vector(self.x + self.width // 2, self.y + self.height)], (self.x, self.y)) self.triangle.load_avatar("/Environment/{0}".format(BATARANG_IMAGE)) self.triangle.scale_avatar(self.width, self.height) self.direction = Vector(0, 0) self.rotation = 0 self.step = ROTATION_STEP self.speed = 0 self.last_update = 0 self.mouse_position = 0 self.should_fly = False def rotate(self, timer): self.triangle.rotate(self.rotation * (1000 / timer)) self.triangle.move(Vector((self.x, self.y)) - self.triangle.position) self.rotation += self.step if self.rotation > 360: self.rotation = self.step def move(self, timer): self.speed = 50 * 10 * (timer / 1000) self.x += self.direction.x * self.speed self.y += self.direction.y * self.speed self.triangle.move(self.direction * self.speed) def get_next_position(self): return self.x + self.direction.x * self.speed, \ self.y + self.direction.y * self.speed def direct(self, mouse_x, mouse_y): self.direction = Vector(mouse_x - self.x, mouse_y - self.y) self.direction = self.direction.normalize() def take_action(self, camera): self.last_update = time.get_ticks() self.mouse_position = camera.reverse_apply(mouse.get_pos()) self.direct(self.mouse_position[0], self.mouse_position[1]) self.should_fly = True def update(self): timer = time.get_ticks() - self.last_update + 1 self.last_update += timer if self.should_fly: self.move(timer) self.rotate(timer) self.collides(self.world) return self.should_fly def draw(self, surface, camera=0): if camera != 0: self.triangle.display_avatar(surface, camera) else: return def collide_saw(self, saw): rope = Line(Point(saw.x, saw.y), Point(saw.collision_circle.position.x, saw.collision_circle.position.y)) next_position = self.get_next_position() path = Line(Point(self.x, self.y), Point(next_position[0], next_position[1])) intersection = Line.get_intersection(rope, path) return bool(intersection) def collides(self, world): for obstacle in world: if self.triangle.check_if_collide(obstacle.rect)[0]: self.should_fly = False break for saw in self.saws: if not saw.is_severed and self.collide_saw(saw): saw.deploy() def reposition(self, coordinates, orientation): self.x, self.y = coordinates self.triangle.move(Vector(coordinates) - self.triangle.position) self.triangle.direction = orientation.normalize()
def __init__(self,position): self.img_cheese=pygame.image.load('img/cheese.png') self.pos=Vector2(position[0],position[1]) self.rect=self.img_cheese.get_rect(topleft=self.pos)
def run(self): # Load map if not os.path.exists(self.fileName): raise RuntimeError("No file {}".format(self.fileName)) tileMap = tmx.TileMap.load(self.fileName) # Check main properties if tileMap.orientation != "orthogonal": raise RuntimeError("Error in {}: invalid orientation".format(self.fileName)) if len(tileMap.layers) != 5: raise RuntimeError("Error in {}: 5 layers are expected".format(self.fileName)) # World size state = self.gameMode.gameState state.worldSize = Vector2(tileMap.width,tileMap.height) # Ground layer tileset, array = self.decodeArrayLayer(tileMap,tileMap.layers[0]) cellSize = Vector2(tileset.tilewidth,tileset.tileheight) state.ground[:] = array imageFile = tileset.image.source self.gameMode.layers[0].setTileset(cellSize,imageFile) # Walls layer tileset, array = self.decodeArrayLayer(tileMap,tileMap.layers[1]) if tileset.tilewidth != cellSize.x or tileset.tileheight != cellSize.y: raise RuntimeError("Error in {}: tile sizes must be the same in all layers".format(self.fileName)) state.walls[:] = array imageFile = tileset.image.source self.gameMode.layers[1].setTileset(cellSize,imageFile) # Units layer tanksTileset, tanks = self.decodeUnitsLayer(state,tileMap,tileMap.layers[2]) towersTileset, towers = self.decodeUnitsLayer(state,tileMap,tileMap.layers[3]) if tanksTileset != towersTileset: raise RuntimeError("Error in {}: tanks and towers tilesets must be the same".format(self.fileName)) if tanksTileset.tilewidth != cellSize.x or tanksTileset.tileheight != cellSize.y: raise RuntimeError("Error in {}: tile sizes must be the same in all layers".format(self.fileName)) state.units[:] = tanks + towers cellSize = Vector2(tanksTileset.tilewidth,tanksTileset.tileheight) imageFile = tanksTileset.image.source self.gameMode.layers[2].setTileset(cellSize,imageFile) # Player units self.gameMode.playerUnit = tanks[0] # Explosions layers tileset, array = self.decodeArrayLayer(tileMap,tileMap.layers[4]) if tileset.tilewidth != cellSize.x or tileset.tileheight != cellSize.y: raise RuntimeError("Error in {}: tile sizes must be the same in all layers".format(self.fileName)) state.bullets.clear() imageFile = tileset.image.source self.gameMode.layers[3].setTileset(cellSize,imageFile) # Window worldSize = state.worldSize.elementwise() * cellSize self.gameMode.notifyWorldSizeChanged(worldSize) # Resume game self.gameMode.gameOver = False
def __init__(self,position): self.img_trap=pygame.image.load('img/pulapka_pusta.png') self.pos=Vector2(position[0],position[1]) self.rect=self.img_trap.get_rect(topleft=self.pos)
def __init__(self, x, y, waypoints): super().__init__("enemy", x, y) self.waypoints = waypoints self.pos = Vector2(x, y) self.vel = Vector2(0, 0) self.acc = Vector2(0.1, 0)
def __init__(self,position,door): self.door=door self.collision = True self.img_door=pygame.image.load('img/door_triger_off.png') self.pos=Vector2(position[0],position[1]) self.rect=self.img_door.get_rect(topleft=self.pos)
def _render_pitch(self): surface = self.surface field = self.field white = Color('white') surface.fill(Color('darkgreen')) fieldmidleft = field.midleft fieldmidright = field.midright #goals self.home_goal.draw(surface) self.away_goal.draw(surface) #penalty_box - left goal = self.home_goal.rect pb = pg.Rect(0, 0, goal.width * 3.0, field.height * 0.5) pb.midleft = fieldmidleft pg.draw.rect(surface, white, pb, 1) #penalty_box_arc - left pbarc = pg.Rect(0, 0, pb.width * 0.35, pb.height * 0.5) pbarc.center = pb.midright pg.draw.arc(surface, white, pbarc, -math.pi * 0.5, math.pi * 0.5) #penalty_spot - left pb_spot = Vector2(pbarc.midleft) pb_spot.x *= 0.8 pg.draw.circle(surface, white, (int(pb_spot.x),int(pb_spot.y)), 3) # penalty-box - right pb.midright = fieldmidright pg.draw.rect(surface, white, pb, 1) #penalty_box_arc - right pbarc.center = pb.midleft pg.draw.arc(surface, white, pbarc, math.pi * 0.5, math.pi * 1.5) #penalty_spot -right pb_spot = Vector2(pbarc.midright) pb_spot.x += (0.2 * (field.width - pbarc.midright[0])) pg.draw.circle(surface, white, (int(pb_spot.x),int(pb_spot.y)), 3) # midfield x1,y1 = field.midtop x1 -= 0 pg.draw.line(surface, white, (x1,y1),(x1,field.height), 1) # field pg.draw.rect(surface, white, field, 2) #render the ball ## self.ball.draw(surface) ## self.ball.draw() # walls for w in self.walls: w.draw(surface,True) # center circle pg.draw.circle(surface, white, field.center, int(field.width * 0.15), 1) pg.draw.circle(surface, white, field.center, 3)
def __init__(self,position): self.my_exit=pygame.image.load('img/door.png') self.pos=Vector2(position[0],position[1]) self.rect=self.my_exit.get_rect(topleft=self.pos) self.cheese =0 self.you_can_go=False
def __init__(self, pos_range=(1, 1)): self.position = Vector2(0, 0) self.pos_range = Vector2(pos_range) self.randomize()
def generate_food(self): self.pos_x = random.randint(0, COLS - 1) self.pos_y = random.randint(0, ROWS - 1) self.pos = Vector2(self.pos_x, self.pos_y)
def initialCheck(self, pos): currentStepVector = pos - self.puck.position stepDistance = currentStepVector.magnitude() if self.puck.timeSinceCaptured == 0: stepSpeed = 0 else: stepSpeed = stepDistance / self.puck.timeSinceCaptured errorAngle = self.getAngleDifference(currentStepVector, self.puck.velocity) # Low angle condition if abs(errorAngle) > self.lowAngleTolerance and sign( errorAngle) == self.previousErrorSide: self.capturesWithBadLowAngle += 1 if (self.capturesWithBadLowAngle > 4): # print("Low Angle error") for i in range(4): self.puckHistory[self.firstUsefull].state = USELESS if self.firstUsefull > 1: self.firstUsefull -= 1 else: self.capturesWithBadLowAngle = 0 self.previousErrorSide = sign(errorAngle) if stepSpeed > 200 and stepDistance > 4 and abs(errorAngle): # Medium angle condition if abs(errorAngle) > self.mediumAngleTolerance and sign( errorAngle) == self.previousErrorSide: self.capturesWithBadMediumAngle += 1 if (self.capturesWithBadMediumAngle > 3): # print("Low angle condition.. 4 states -> useless") self.capturesWithBadLowAngle = 0 self.capturesWithBadMediumAngle = 0 # print("Medium Angle error") for i in range(3, len(self.puckHistory)): self.puckHistory[i].state = USELESS else: self.capturesWithBadMediumAngle = 0 # Debug # if len(self.puck.trajectory) > 0: # trajectoryLine = Line(self.puckHistory[self.firstUsefull].position, self.puck.position) # bounceLine = Line(Vector2(0, sign(pos.y) * (FIELD_HEIGHT/2 - PUCK_RADIUS)), Vector2(FIELD_WIDTH, sign(pos.y) * (FIELD_HEIGHT/2 - PUCK_RADIUS))) # self.debugLines.append(trajectoryLine) # self.debugLines.append(bounceLine) # self.debugPoints.append(self.getIntersectPoint(trajectoryLine, bounceLine)) # High angle condition if (abs(errorAngle) > self.highAngleTolerance) or ( stepSpeed > 700 and stepDistance > 25 and abs(errorAngle) > self.highAngleTolerance * .4): self.capturesWithBadLowAngle = 0 self.capturesWithBadMediumAngle = 0 # print("Angle condition: " + str(errorAngle)) if abs(pos.y) > max( 200, FIELD_HEIGHT / 2 - (stepDistance * abs(self.puck.vector.y) + PUCK_RADIUS) ) and sign(currentStepVector.x) == sign( self.puck.velocity.x ) and sign(self.puck.velocity.y) == sign( pos.y ) and self.puck.state == ACURATE: # seems like bounce from sidewalls occured trajectoryLine = Line( self.puckHistory[self.firstUsefull].position, self.puck.position) bounceLine = Line( Vector2(0, sign(pos.y) * (FIELD_HEIGHT / 2 - PUCK_RADIUS)), Vector2(FIELD_WIDTH, sign(pos.y) * (FIELD_HEIGHT / 2 - PUCK_RADIUS))) bouncePoint = trajectoryLine.getIntersectPoint(bounceLine) self.debugLines.append(trajectoryLine) self.debugLines.append(bounceLine) bouncePoint = trajectoryLine.getIntersectPoint(bounceLine) self.puck.position = bouncePoint # print(bouncePoint) for i in range(len(self.puckHistory)): self.puckHistory[i].state = USELESS
#Game loop run = True reset = True while run: #Events for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == SCREEN_UPDATE: reset = main_game.update() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: if not main_game.snake.body[0].y - 1 == main_game.snake.body[ 1].y: main_game.snake.direction = Vector2(0, -1) elif event.key == pygame.K_DOWN: if not main_game.snake.body[0].y + 1 == main_game.snake.body[ 1].y: main_game.snake.direction = Vector2(0, 1) elif event.key == pygame.K_LEFT: if not main_game.snake.body[0].x - 1 == main_game.snake.body[ 1].x: main_game.snake.direction = Vector2(-1, 0) elif event.key == pygame.K_RIGHT: if not main_game.snake.body[0].x + 1 == main_game.snake.body[ 1].x: main_game.snake.direction = Vector2(1, 0) #Helper for checking collitions since for loop not working on main class if reset == False:
def draw(self): if self.is_over: self.draw_menu() return # Dessine le decore & groupes self.dir.screen.fill((0, 0, 0)) self.dir.screen.blit(self.sky, self.sky_rect) self.group_platforms.draw(self.dir.screen) self.group_players.draw(self.dir.screen) self.group_explosions.draw(self.dir.screen) self.group_projectiles.draw(self.dir.screen) # Dessine les barres de vies for i, player in enumerate(self.group_players.sprites()): player.drawHealth() if i == self.current_player: x = player.rect.centerx - self.select_icon_rect.centerx y = player.rect.top - self.select_icon_rect.bottom - 16 - 16*math.sin(self.overtime) self.dir.screen.blit(self.select_icon, (x, y)) # Dessine la barre de puissance si active if self.current_player != -1 and self.group_players.sprites()[self.current_player]: self.group_players.sprites()[self.current_player].draw_powerbar() if self.is_shooting: mouse_pos = pygame.mouse.get_pos() player_center = self.group_players.sprites()[self.current_player].rect.center vect = (mouse_pos[0] - player_center[0], mouse_pos[1] - player_center[1]) angle = 0 if vect[0] is not 0: angle = math.degrees(-math.atan2(vect[1], vect[0])) back = pygame.transform.rotate(self.powerbar_back, angle) pos_back = back.get_rect() pos = Vector2(player_center)# - pos_back.midright).rotate(angle) rotated_offset = Vector2(64, 0).rotate(-angle) new_pos= Vector2(player_center) + rotated_offset back = pygame.transform.rotate(self.powerbar_back, angle) rect = back.get_rect(center=new_pos) self.dir.screen.blit(back, rect) # FRONT POWERBAR x = self.group_players.sprites()[self.current_player].mult * 128 cut_rect = (0, 0, x, 64) front = self.powerbar.subsurface(cut_rect) fr_rect = front.get_rect() rotated_offset = Vector2(fr_rect.width//2, 0).rotate(-angle) new_pos = Vector2(player_center) + rotated_offset back = pygame.transform.rotate(front, angle) rect = back.get_rect(center=new_pos) self.dir.screen.blit(pygame.transform.rotate(front, angle), rect) # Debug if self.current_player != -1 and debug == 1: mouse_pos = pygame.mouse.get_pos() player_center = self.group_players.sprites()[self.current_player].rect.center vect = (mouse_pos[0] - player_center[0], mouse_pos[1] - player_center[1]) #soh cah toa angle = 0 if vect[0] is not 0: angle = -math.atan2(vect[1], vect[0]) pygame.draw.aaline(self.dir.screen, (255, 0, 0), player_center, mouse_pos) pygame.draw.aaline(self.dir.screen, (0, 255, 0), player_center, (player_center[0] + vect[0], player_center[1])) pygame.draw.aaline(self.dir.screen, (0, 0, 255), (player_center[0] + vect[0], player_center[1]), (player_center[0] + vect[0], player_center[1] + vect[1])) pygame.draw.arc(self.dir.screen, (255, 0, 255), (player_center[0]-32, player_center[1]-32, 64, 64), 0, angle) ang_text = Fonts['default'].render(str(math.degrees(angle)), False, (0, 0, 0, 255)) self.dir.screen.blit(ang_text, player_center)
def __init__(self): self.x = random.randint(0, cell_number - 1) self.y = random.randint(0, cell_number - 1) self.pos = Vector2(self.x, self.y)
def velocity(self, vec): self._velocity = Vector2(vec) self.heading = Vector2(cos(radians(self.angle)), sin(radians(self.angle))) self.side = self.heading.rotate(90)
def draw_snake(self): for index, block in enumerate(self.body): if index == 0: difference = self.body[1] - self.body[0] if difference == Vector2(1, 0): block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.head_left, block_rect) elif difference == Vector2(-1, 0): block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.head_right, block_rect) elif difference == Vector2(0, 1): block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.head_up, block_rect) elif difference == Vector2(0, -1): block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.head_down, block_rect) elif index > 0 and index < len(self.body) - 1: if block.x + 1 == self.body[index - 1].x: if block.y + 1 == self.body[index + 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_br, block_rect) elif block.y - 1 == self.body[index + 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_tr, block_rect) else: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_horizontal, block_rect) elif block.x - 1 == self.body[index - 1].x: if block.y + 1 == self.body[index + 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_bl, block_rect) elif block.y - 1 == self.body[index + 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_tl, block_rect) else: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_horizontal, block_rect) elif block.y - 1 == self.body[index - 1].y: if block.x + 1 == self.body[index + 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_tr, block_rect) elif block.x - 1 == self.body[index + 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_tl, block_rect) else: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_vertical, block_rect) elif block.y + 1 == self.body[index - 1].y: if block.x - 1 == self.body[index + 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_bl, block_rect) elif block.x + 1 == self.body[index + 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_br, block_rect) else: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.body_vertical, block_rect) else: if block.x + 1 == self.body[index - 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.tail_left, block_rect) elif block.x - 1 == self.body[index - 1].x: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.tail_right, block_rect) elif block.y - 1 == self.body[index - 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.tail_down, block_rect) elif block.y + 1 == self.body[index - 1].y: block_rect = pygame.Rect(block.x * cell_size, block.y * cell_size, cell_size, cell_size) screen.blit(self.tail_up, block_rect)
class Yksilo(object): def __init__(self, x ,y , size=5, color = (0,0,255), width = 0): self.x = x self.y = y self.size = size self.color = color self.width = width self.massa = 1. self.paikka = Vector(x,y) self.nopeus = Vector(0,0) self.suunta = Vector(0,0) self.voima = Vector(0,0) self.max_voima= 1.0 self.max_nopeus = 1.7 def laske_uusi_paikka(self): self.edellinen_paikka = self.paikka if (self.voima.length() != 0): self.katkaise_vektori(self.voima, self.max_voima) kiihtyvyys = self.voima/self.massa nopeus = self.nopeus + kiihtyvyys self.katkaise_vektori(nopeus,self.max_nopeus) #laske uusi paikkavektori uusi_paikka = nopeus+self.paikka #paivita katsomissuunta ja nopeus self.nopeus = nopeus self.suunta = nopeus.normalize() else: uusi_paikka = self.paikka #uusi paikka paivitetaan vasta kaytosmallissa return uusi_paikka def jarruta(self): """ asettaa ohjausvoiman nollaan, eli pysayttaa yksilon valittomasti """ self.voima -= self.voima def katkaise_vektori(self,vektori, maksimi): """ lyhentaa parametria vektori jos se on pidempi kuin parametri maksimi. suunta pysyy ennallaan """ if (vektori.length()>maksimi): vektori.scale_to_length(maksimi)
def collide_with_rectangle(self, object): # This function is called after a first-pass test, that is the collision # rectangles overlap. left, right, top, bottom = False, False, False, False # TODO: This can probably be optimized if (object.position.x > self.position.x and object.position.x - object.rectangle.width / 2 <= self.position.x + self.radius and self.position.y <= object.position.y + object.rectangle.height / 2 and self.position.y >= object.position.y - object.rectangle.height / 2): left = True if (object.position.x < self.position.x and object.position.x + object.rectangle.width / 2 >= self.position.x - self.radius and self.position.y <= object.position.y + object.rectangle.height / 2 and self.position.y >= object.position.y - object.rectangle.height / 2): right = True if (object.position.y > self.position.y and object.position.y - object.rectangle.height / 2 <= self.position.y + self.radius and self.position.x <= object.position.x + object.rectangle.width / 2 and self.position.x >= object.position.x - object.rectangle.width / 2): top = True if (object.position.y < self.position.y and object.position.y + object.rectangle.width / 2 >= self.position.y - self.radius and self.position.x <= object.position.x + object.rectangle.width / 2 and self.position.x >= object.position.x - object.rectangle.width / 2): bottom = True test = left + right + top + bottom if test == 1: object.touched_by_ball = True # the ball has collided with an edge # TODO: # fix sticky edges if left or right: self.velocity.x *= -1 if left: self.position.x = object.position.x - object.rectangle.width / 2 - self.radius - 1 else: self.position.x = object.position.x + object.rectangle.width / 2 + self.radius + 1 if top or bottom: self.velocity.y *= -1 if top: self.position.y = object.position.y - object.rectangle.height / 2 - self.radius - 1 else: self.position.y = object.position.y + object.rectangle.height / 2 + self.radius + 1 elif test == 4: # TODO: Better error handling print('error: ball inside rectangle') elif test == 0: # We are at a corner. Either it narrowly missed, or it hit the corner corners = [ Vector2(object.position.x - object.rectangle.width / 2, object.position.y - object.rectangle.height / 2), Vector2(object.position.x + object.rectangle.width / 2, object.position.y - object.rectangle.height / 2), Vector2(object.position.x - object.rectangle.width / 2, object.position.y + object.rectangle.height / 2), Vector2(object.position.x + object.rectangle.width / 2, object.position.y + object.rectangle.height / 2) ] for corner in corners: relative_vector = self.position - corner if relative_vector.length() <= self.radius: object.touched_by_ball = True # Create a dummy object to make use of ball to ball collision, because the math is the same # Give it a velocity of the same magnitude as the current ball to cause it to reflect at # the same speed stand_in = Ball(self.bounds, corner, Vector2(0, self.velocity.length()), [0, 0, 0], 0) self.collide_with_ball(stand_in, relative_vector)
def rotate(self): pos = Vector2(self.position) direction = pygame.mouse.get_pos() - pos radius, angle = direction.as_polar() self.image = pygame.transform.rotate(self.playerOrig, -angle) self.rect = self.image.get_rect(center=self.rect.center)
def direct(self, mouse_x, mouse_y): self.direction = Vector(mouse_x - self.x, mouse_y - self.y) self.direction = self.direction.normalize()