def __init__(self): self.map_data = [] self.entry_point = Vector2(0, 0)
def __init__(self, board: Rect): """ Construct all the carrom board parameters required to draw the carrom board layout """ """ Board must be square in shape """ assert board.width == board.height self.board = board self.frame_width = int(board.width * Board.FRAME_LENGTH / Board.TOTAL_LENGTH) """ Coins are restricted to the container """ self.container = board.inflate(-2 * self.frame_width, -2 * self.frame_width) """ Calculate the multiplier by which to scale parameters to obtain values wrt board""" m = self.board.width / Board.TOTAL_LENGTH self.m = m """ Calculate the pocket radius and the center positions """ self.pocket_radius = m * Board.POCKET_RADIUS self.coin_radius = m * Board.COIN_RADIUS self.striker_radius = m * Board.STRIKER_RADIUS self.pocket_centers = [ Vector2(self.container.left + self.pocket_radius, self.container.top + self.pocket_radius), Vector2(self.container.right - self.pocket_radius, self.container.top + self.pocket_radius), Vector2(self.container.right - self.pocket_radius, self.container.bottom - self.pocket_radius), Vector2(self.container.left + self.pocket_radius, self.container.bottom - self.pocket_radius), ] """ These are solely defined for the purpose of rebounds """ self.diagonal_pocket_opposite = [ (self.container.right - self.striker_radius, self.container.bottom - self.striker_radius), (self.container.left + self.striker_radius, self.container.bottom - self.striker_radius), (self.container.left + self.striker_radius, self.container.top + self.striker_radius), (self.container.right - self.striker_radius, self.container.top + self.striker_radius), ] self.normal_vectors = [ (Vector2(-1, 0), Vector2(0, -1)), (Vector2(1, 0), Vector2(0, -1)), (Vector2(1, 0), Vector2(0, 1)), (Vector2(-1, 0), Vector2(0, 1)), ] """ Calculate the base line positions, the lines defining the region where player places the striker """ base_offset = m * Board.BASE_OFFSET base_distance = m * Board.BASE_DISTANCE base_height = m * Board.BASE_HEIGHT base_length = m * Board.BASE_LENGTH base_radius = m * Board.BASE_RADIUS self.base_lines = [ ((self.container.left + base_offset + base_radius, self.container.top + base_distance), (self.container.left + base_offset + base_length - base_radius, self.container.top + base_distance)), ((self.container.left + base_offset + base_radius, self.container.top + base_distance + base_height), (self.container.left + base_offset + base_length - base_radius, self.container.top + base_distance + base_height)), ((self.container.left + base_offset + base_radius, self.container.bottom - base_distance), (self.container.left + base_offset + base_length - base_radius, self.container.bottom - base_distance)), ((self.container.left + base_offset + base_radius, self.container.bottom - base_distance - base_height), (self.container.left + base_offset + base_length - base_radius, self.container.bottom - base_distance - base_height)), ((self.container.left + base_distance, self.container.top + base_offset + base_radius), (self.container.left + base_distance, self.container.top + base_offset + base_length - base_radius)), ((self.container.left + base_distance + base_height, self.container.top + base_offset + base_radius), (self.container.left + base_distance + base_height, self.container.bottom - base_offset - base_radius)), ((self.container.right - base_distance, self.container.top + base_offset + base_radius), (self.container.right - base_distance, self.container.top + base_offset + base_length - base_radius)), ((self.container.right - base_distance - base_height, self.container.top + base_offset + base_radius), (self.container.right - base_distance - base_height, self.container.bottom - base_offset - base_radius)) ] """ Base circle centers, the circles at the end of base lines """ self.base_circle_centers = [ (int(self.container.left + base_offset + base_radius), int(self.container.top + base_distance + base_radius)), (int(self.container.left + base_offset + base_length - base_radius), int(self.container.top + base_distance + base_radius)), (int(self.container.left + base_offset + base_radius), int(self.container.bottom - base_distance - base_radius)), (int(self.container.left + base_offset + base_length - base_radius), int(self.container.bottom - base_distance - base_radius)), (int(self.container.left + base_distance + base_radius), int(self.container.top + base_offset + base_radius)), (int(self.container.left + base_distance + base_radius), int(self.container.bottom - base_offset - base_radius)), (int(self.container.right - base_distance - base_radius), int(self.container.top + base_offset + base_radius)), (int(self.container.right - base_distance - base_radius), int(self.container.bottom - base_offset - base_radius)) ] """ Arrow lines """ arrow_start = self.pocket_radius * 2 + m * Board.ARROW_OFFSET / sqrt(2) arrow_end = arrow_start + m * Board.ARROW_LENGTH / sqrt(2) self.arrow_lines = [((int(self.container.left + arrow_start), int(self.container.top + arrow_start)), (int(self.container.left + arrow_end), int(self.container.top + arrow_end))), ((int(self.container.left + arrow_start), int(self.container.bottom - arrow_start)), (int(self.container.left + arrow_end), int(self.container.bottom - arrow_end))), ((int(self.container.right - arrow_start), int(self.container.bottom - arrow_start)), (int(self.container.right - arrow_end), int(self.container.bottom - arrow_end))), ((int(self.container.right - arrow_start), int(self.container.top + arrow_start)), (int(self.container.right - arrow_end), int(self.container.top + arrow_end)))] arc_offset = int(arrow_end - m * Board.ARROW_RADIUS * (1 + 1 / sqrt(2))) arc_width = int(m * Board.ARROW_DIAMETER) """ Arrow Arcs""" self.arrow_arcs = [(Rect(self.container.left + arc_offset, self.container.top + arc_offset, arc_width, arc_width), radians(180), radians(90)), (Rect(self.container.left + arc_offset, self.container.bottom - arc_offset, arc_width, -arc_width), radians(-90), radians(180)), (Rect(self.container.right - arc_offset, self.container.bottom - arc_offset, -arc_width, -arc_width), radians(0), radians(-90)), (Rect(self.container.right - arc_offset, self.container.top + arc_offset, -arc_width, arc_width), radians(90), radians(0))] self.base_radius = m * Board.BASE_RADIUS self.base_distance = m * Board.BASE_DISTANCE self.base_offset = m * Board.BASE_OFFSET self.base_inner_radius = m * Board.BASE_INNER_RADIUS self.center_outer_radius = m * Board.CENTER_OUTER_RADIUS self.center_inner_radius = m * Board.CENTER_INNER_RADIUS
def _item_center(self, item_index, total_items): """Returns a Vector2 corresponding to the item center""" screen_center = Vector2(self._screen.surface.get_rect().center) menu_height = self._item_spacing * total_items menu_start = screen_center - Vector2(0, menu_height) / 2 return menu_start + Vector2(0, self._item_spacing) * item_index
def __init__(self, point1, point2): self.a = Vector2(point1) self.b = Vector2(point2)
import numpy as np WIDTH = 1600 HEIGHT = 900 DARKGRAY = (15, 15, 15) DARKGREEN = (6, 91, 9) BLUE = (0, 0, 255) GRAY = (90, 90, 90) RED = (255, 0, 0) YELLOW = (200, 200, 0) MAX_STEPS = 0 EPSILON = 0.001 MAX_DEPTH = WIDTH p = Vector2(WIDTH // 2, HEIGHT - 50) angle = -pi / 2 cx1, cy1, cr1 = WIDTH // 2, HEIGHT // 2, 100 cx2, cy2, cr2 = 0, 0, 500 length = 0 depth = 0 os.environ['SDL_VIDEO_WINDOW_POS'] = f'{(tk.Tk().winfo_screenwidth() - WIDTH) // 2},' \ f'{(tk.Tk().winfo_screenheight() - HEIGHT) // 4}' pygame.init() sc = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() pygame.mouse.set_visible(False) def sdf_scene(vec):
def renderLine(self, start, end, color=(255, 255, 255), weight=1): start = Vector2(start.x, self.__surface.get_height() - start.y) end = Vector2(end.x, self.__surface.get_height() - end.y) pg.draw.line(self.__surface, color, (start.x, start.y), (end.x, end.y), weight)
def moveup(self): #Angle is the rotation speed_down = 12 direction = Vector2(0, -1).rotate(-self.angle) / speed_down #Define the movement to be in the direction of the jet self.movement += direction
def notify(self, event): if isinstance(event, Event.TickEvent): for event in pygame.event.get(): ev = None # Quit event from pygame if event.type == pygame.QUIT: ev = Event.QuitEvent() # If keyboard key is pressed elif event.type == pygame.KEYDOWN: if event.key == Settings.KEY_QUIT: ev = Event.QuitEvent() elif event.key == Settings.KEY_POINT_EDITING: ev = Event.ChangeModeEvent(Game.Mode(Game.Mode.POINT_EDITING)) elif event.key == Settings.KEY_LINE_EDITING: ev = Event.ChangeModeEvent(Game.Mode(Game.Mode.LINE_EDITING)) elif event.key == Settings.KEY_PLAY_MODE: ev = Event.ChangeModeEvent(Game.Mode(Game.Mode.PLAY_MODE)) elif event.key == Settings.KEY_TOGGLE_DEBUG: ev = Event.ToggleDebugEvent() elif event.key == Settings.KEY_SAVE_MAP: ev = Event.SaveMapEvent(input('Map name : ')) elif event.key == Settings.KEY_LOAD_MAP: ev = Event.LoadMapEvent(input('Map name : ')) # If mouse is pressed elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == Settings.MOUSE_CREATE: ev = Event.CreationEvent() elif event.button == Settings.MOUSE_REMOVE: ev = Event.RemovingEvent() if ev is not None: self.evManager.post(ev) # Keyboard inputs that has to be maintained key_pressed = pygame.key.get_pressed() direction = Vector2(0, 0) if key_pressed[Settings.KEY_MOVE_FRONT]: direction += Vector2(1, 0) if key_pressed[Settings.KEY_MOVE_BACK]: direction += Vector2(-1, 0) if key_pressed[Settings.KEY_MOVE_LEFT]: direction += Vector2(0, 1) if key_pressed[Settings.KEY_MOVE_RIGHT]: direction += Vector2(0, -1) if direction.x != 0 or direction.y != 0: self.evManager.post(Event.MovePlayerEvent(direction))
def set_pos(self, pos): self.position = Vector2(pos)
def move(self, d): self.v = Vector2(d)
def __init__(self, windowWidth, windowHeight, size=False, x=False, y=False, direction=False): self.width = windowWidth self.height = windowHeight self.pos = Vector2() # Sizes: 80, 40, 20 self.size = 0 # number of points in asteroid self.res = 5 # If size not given with init, choose random size if not size: choice = randint(1, 3) self.res *= choice if choice == 1: self.size = 20 elif choice == 2: self.size = 40 elif choice == 3: self.size = 80 else: self.res *= size if size == 1: self.size = 20 elif size == 2: self.size = 40 elif size == 3: self.size = 80 else: print("invalid size defaulting to 1!") self.size = 20 # Set speed as reciprocal of size self.speed = 80 / (self.size * 1.5) # If direction not given, set to random degree self.dir = direction or (random() * 360) # If x or y not given, if (not x or not y): rX = 0 rY = 0 if random() > 0.5: if random() > 0.5: rX = self.width rY = random() * self.height else: if random() > 0.5: rY = self.height rX = random() * self.width self.pos = Vector2(rX, rY) else: self.pos = Vector2(x, y) self.spin = 0 return
def __init__(self, pos, brain=None): self.pos = Vector2(pos) self.born = Vector2(pos) self.v = Vector2(1, 0) self.w = block self.h = block self.length = 4 self.guide = Vector2(self.v) self.body = [ self.pos, self.pos - self.v * block, self.pos - self.v * block * 2, self.pos - self.v * block * 3 ] self.score = 0 self.life = 0 self.time_limit = 150 self.alive = True self.dirs = [ Vector2(0, -1), Vector2(1, -1), Vector2(1, 0), Vector2(1, 1), Vector2(1, 0), Vector2(-1, 1), Vector2(-1, 0), Vector2(-1, -1) ] if brain == None: self.brain = initialize([26, 16, 3]) else: self.brain = brain
def processDistances(self, foods, walls, screen): inp = [0 for i in range(26)] # front = self.v * block # left = Vector2(self.v.rotate(-90)) * block # right = Vector2(self.v.rotate(90)) * block # fl = Vector2(self.v.rotate(-45)) * block # fr = Vector2(self.v.rotate(45)) * block # f = self.pos + front # l = self.pos + left # r = self.pos + right m = 100000000 f = None for food in foods: if self.pos.distance_to(food) < m: m = self.pos.distance_to(food) f = food inp[0], inp[1], inp[2] = self.look(Vector2(0, -1), f) inp[3], inp[4], inp[5] = self.look(Vector2(1, -1), f) inp[6], inp[7], inp[8] = self.look(Vector2(1, 0), f) inp[9], inp[10], inp[11] = self.look(Vector2(1, 1), f) inp[12], inp[13], inp[14] = self.look(Vector2(0, 1), f) inp[15], inp[16], inp[17] = self.look(Vector2(-1, 1), f) inp[18], inp[19], inp[20] = self.look(Vector2(-1, 0), f) inp[21], inp[22], inp[23] = self.look(Vector2(-1, -1), f) foodv = f - self.pos if foodv.magnitude() != 0: angle = np.arccos( foodv.dot(self.v) / (foodv.magnitude() * self.v.magnitude())) * 180 / np.pi inp[24] = np.cos(angle * np.pi / 180) else: inp[24] = 1 if self.time_limit == 0: inp[25] = 1 else: inp[25] = 1 / self.time_limit ############################################################################################################################################## ############################################################################################################################################## ############################################################################################################################################## # m = 100000000 # f = None # for food in foods: # if self.pos.distance_to(food) < m: # m = self.pos.distance_to(food) # f = food # for i in range(1, 4): # f = self.pos + front * i # if f.x < 0 or f.x > WIDTH or f.y < 0 or f.y > HEIGHT: # inputs[0] = 1 # break # for i in range(1, 4): # l = self.pos + left * i # if l.x < 0 or l.x > WIDTH or l.y < 0 or l.y > HEIGHT: # inputs[1] = 1 # break # for i in range(1, 4): # r = self.pos + right * i # if r.x < 0 or r.x > WIDTH or r.y < 0 or r.y > HEIGHT: # inputs[2] = 1 # break # #BODY IS FINE ######################################################## # for i in range(1, 5): # temp = Vector2(self.pos + front * i) # if temp in self.body: # inputs[3] = 1 # break # for i in range(1, 8): # temp = Vector2(f + left * i) # if temp in self.body: # inputs[4] = 1 # break # for i in range(1, 5): # temp = Vector2(f + right * i) # if temp in self.body: # inputs[5] = 1 # break # for i in range(1, 8): # temp = self.pos + fl * i # if temp in self.body: # inputs[6] = 1 # break # for i in range(1, 8): # temp = self.pos + fr * i # if temp in self.body: # inputs[7] = 1 # break # #FOOD IS FINE ######################################################## # if f != None: # foodv = f - self.pos # if foodv.magnitude() != 0: # angle = np.arccos(foodv.dot(self.v) / (foodv.magnitude() * self.v.magnitude())) * 180 / np.pi # inputs[12] = np.cos(angle * np.pi / 180) # else: # angle = 0 # if angle == 0: # inputs[8] = 1 # # print('food straight') # else: # if self.v == Vector2(0, -1): # if food.x < self.pos.x: # inputs[9] = 1 # # print('left') # else: # inputs[10] = 1 # # print('right') # elif self.v == Vector2(1, 0): # if food.y < self.pos.y: # inputs[9] = 1 # # print('left') # else: # inputs[10] = 1 # # print('right') # elif self.v == Vector2(0, 1): # if food.x > self.pos.x: # inputs[9] = 1 # # print('left') # else: # inputs[10] = 1 # # print('right') # elif self.v == Vector2(-1, 0): # if food.y > self.pos.y: # inputs[9] = 1 # # print('left') # else: # inputs[10] = 1 # # print('right') # # if self.time_limit <= 200: # # inputs[9] = 1 # if self.time_limit != 0: # inputs[11] = 1 / self.time_limit # else: # inputs[11] = 1 # # inputs[12] = self.length / 100 ############################################################################################################################################## ############################################################################################################################################## ############################################################################################################################################## inputs = np.array(inp) m = len(inputs) # print(m) inputs = inputs.reshape((m, 1)) return inputs
############################################################################################################################################## inputs = np.array(inp) m = len(inputs) # print(m) inputs = inputs.reshape((m, 1)) return inputs screen = pygame.display.set_mode(SCREEN) snakes = [ Snake(Vector2(block * 10, block * 10), brain=params) for i in range(GEN) ] prevscores = [snake.score for snake in snakes] def foodloc(): food = [] for i in range(20): x = random.randint(1, WIDTH // block - 1) y = random.randint(1, HEIGHT // block - 1) food.append(Vector2(x, y) * block) return food
if __name__ == '__main__': pygame.init() width = 1000 height = 500 screen = pygame.display.set_mode([width, height]) wallSurf = pygame.Surface([width, height], pygame.SRCALPHA) walls = [] for i in range(5): x1 = randint(0, width) y1 = randint(0, height) x2 = randint(0, width) y2 = randint(0, height) walls.append(Boundary(Vector2(x1, y1), Vector2(x2, y2), wallSurf)) walls.append(Boundary(Vector2(width, 0), Vector2(width, height), wallSurf)) walls.append(Boundary(Vector2(0, 0), Vector2(0, height), wallSurf)) walls.append(Boundary(Vector2(0, 0), Vector2(width, 0), wallSurf)) walls.append(Boundary(Vector2(0, height), Vector2(width, height), wallSurf)) p = RayParticle(Vector2((250, 250))) # Event Loop------------------------------------------------------------------------------------------------------------ while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
def apply_accel(self, vector): self.accel = self.accel + Vector2(vector)
ten_draws_time_cost = 0 avg_draw_time_cost = 0 stutter_counter = 0 stutter_frequency = 0, # Variables and set-up for visual effects spectrum = Spectrum(-50, 50, pygame.Color(0, 0, 255), pygame.Color(255, 0, 0)) blur = False # Main loop while not done: pos = Vector2(pygame.mouse.get_pos()) hex_pos = screen_to_hex_space(pos) tile = hex_pos.round() toolbar.tools[toolbar.current].before_math(tile) for event in pygame.event.get(): # Pipes mouse input into the currently selected tool if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 4: if tools.controlling() or tools.shifting(): toolbar.tools[toolbar.current].mouse_scroll(+1) else: toolbar.decrement_selection() elif event.button == 5:
def draw(self, screen): # Draws debug objects if self.DEBUG: # Selects color of buffer zone self.buffer_zone_image = self.buffer_zone_red if self.collision_imminent else self.buffer_zone_green # Draws buffer zone screen.blit(self.buffer_zone_image_rotated, self.buffer_zone_image_rect) # Draws vehicle on the screen screen.blit(self.image_rotated, self.image_rect) # Draws more debug objects if self.DEBUG: # Draws debug lines # Desired pygame.draw.line( pygame.display.get_surface(), (255, 0, 0), # red self.image_rect.center, self.image_rect.center + self.debug_lines[0], 2) # Speed pygame.draw.line( pygame.display.get_surface(), (0, 255, 0), # green self.image_rect.center, self.image_rect.center + self.debug_lines[1], 2) # Accel pygame.draw.line( pygame.display.get_surface(), (0, 0, 255), # blue self.image_rect.center, self.image_rect.center + self.debug_lines[2], 2) # Draws rotation indicators pygame.draw.circle(pygame.display.get_surface(), (255, 250, 70), self.image_rect.center, 3) pygame.draw.rect(pygame.display.get_surface(), (30, 250, 70), self.image_rect, 1) # Draws metrics velocity_text = self.textFont.render( "Velocity: %0.2f km/h" % (pixel_to_metric(Vector2(self.get_velocity()).length()) * 3.6), False, (255, 255, 255)) accel_text = self.textFont.render( "Accel: %0.2f km/h" % (pixel_to_metric(Vector2(self.get_accel()).length()) * 3.6), False, (255, 255, 255)) screen.blit( velocity_text, Vector2(screen.get_size()) - Vector2(velocity_text.get_size())) screen.blit( accel_text, Vector2(screen.get_size()) - Vector2( (accel_text.get_width(), 2 * accel_text.get_height()))) self.debug_lines.clear()
def renderWireRect(self, pos, size, color=(255, 255, 255), weight=1): pos = Vector2(pos.x, self.__surface.get_height() - pos.y) ul = Vector2(pos.x - size.x//2, pos.y - size.y // 2) ur = Vector2(pos.x + size.x//2, pos.y - size.y // 2) bl = Vector2(pos.x - size.x//2, pos.y + size.y // 2) br = Vector2(pos.x + size.x//2, pos.y + size.y // 2) self.renderLine(Vector2(ul.x, ul.y), Vector2( ur.x, ur.y), color, weight) self.renderLine(Vector2(ur.x, ur.y), Vector2( br.x, br.y), color, weight) self.renderLine(Vector2(br.x, br.y), Vector2( bl.x, bl.y), color, weight) self.renderLine(Vector2(bl.x, bl.y), Vector2( ul.x, ul.y), color, weight)
def __init__(self): self.lastState = Vector2(0, 0)
def __init__(self, pos, angle): self.pos = pos self.Dir = Vector2(1, 0) self.Dir = self.Dir.rotate(angle)
def getKey(self, keyState): if keyState[pg.K_LEFT] and self.lastState != Vector2( -1, 0) and self.lastState != Vector2(1, 0): self.lastState = Vector2(-1, 0) return Vector2(-1, 0) elif keyState[pg.K_RIGHT] and self.lastState != Vector2( -1, 0) and self.lastState != Vector2(1, 0): self.lastState = Vector2(1, 0) return Vector2(1, 0) elif keyState[pg.K_UP] and self.lastState != Vector2( 0, -1) and self.lastState != Vector2(0, 1): self.lastState = Vector2(0, -1) return Vector2(0, -1) elif keyState[pg.K_DOWN] and self.lastState != Vector2( 0, -1) and self.lastState != Vector2(0, 1): self.lastState = Vector2(0, 1) return Vector2(0, 1) else: return self.lastState
def __init__(self): self.pos = Vector2(200, 200) self.dir = Vector2(1, 0) self.CreateRays()
# constants BG_COLOR = (10, 70, 10) # pygame init pygame.init() pygame.display.set_caption('Card Game') width, height = (1000, 300) screen = pygame.display.set_mode((width, height), flags=pygame.SCALED) f = random.choice(('co', 'ca', 'p', 't')) cards = [pygame.image.load(f"assets/{f}{i}.gif") for i in range(2, 15)] random.shuffle(cards) pos = [Vector2(x * width / 13, height / 16) for x in range(13)] card_surf = pygame.Surface((71, 96)) rectdet = [screen.blit(card_surf, (x, y)) for (x, y) in pos] click = False running = True clicked_card = -1 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: sexit() if event.type == pygame.MOUSEBUTTONDOWN: position_souris = event.pos for a in range(13): if rectdet[a].collidepoint(position_souris):
def get_striker_position(self, player): """ Returns the start position of the striker for the given player """ return Vector2(self.get_striker_x_position(), self.get_striker_y_position(player))
def yellow_bullet(self): return { 'neutral': Animation('neutral', [self.get_sprite('yellow_bullet')], [1000], Vector2(3, 3)) }
def allow_movement(self): if self.angle: return True if self.vector == Vector2(): return True
def rect(self): size = Vector2(self.size.x * 0.05, self.size.y * 0.19) rect = (self.pos.x - 0.5 * size.x + 0.05, self.pos.y - 0.5 * size.y, size.x, size.y * 0.05) l = 1000 return pygame.Rect(rect[0] * l, rect[1] * l, rect[2] * l, rect[3] * l)
from pygame import Vector2 """The null Vector2""" VECTOR2_NULL = Vector2(0, 0) class GlobalSettings: """Screen resolution""" RESOLUTION = (1024, 768) """Link to the banner font""" FONT = "assets/Cairo-Bold.ttf" class PhysicsSettings: """Physics operate on a higher scale than the transform. This is the factor to translate the physics values to the coordinate system. """ SCALE = 10_000 """If a component of a velocity drop below this threshold, it is set to zero. This is to prevent objects from sliding endlessly. """ NULLIFY_THRESHOLD = 1 """Force applied to every velocity. Will be applied differently based on the weight of the object. """ GRAVITY = Vector2(0, 13) """Used to simulate the decay of the velocity due to the air.""" STANDARD_RESISTANCE = 0.06 class PlayerSettings: """TO REPLACE WITH ABILITY.
def update(self, screen, boxes): # On récupère la boite qui est en colision avec la balle ou None collider: Box = self.collision(boxes) if (collider != None): # S'il y a une collision, on pose la balle juste au dessus de la boite self.pos.y = collider.pos.y - self.diameter + 1 # On crée un rebond en inversant l'accélération de la balle # On divise par le quotient de rebond et on met un seuil pour éviter # que la balle rebondisse à l'infini (passé 0.1 on arrête) self.acc.y = -(self.acc.y / self.bounciness) if self.acc.y > 0.1 else 0 # On indique qu'on a touché le sol self.grounded = True else: # Sinon, on est dans les airs, donc on ajoute la gravité à l'accélération self.acc.y += G # et on indique qu'on est pas au sol self.grounded = False # On ne peut sauter que lorsqu'on est au sol if (self.grounded and key.get_pressed()[K_SPACE]): # On met brutalement l'accélération à la force de saut, ce qui la propulse # dans les airs self.acc.y = self.jump_force # On regarde le joueur se déplace if (key.get_pressed()[K_LEFT]): # S'il se déplace à gauche on accélère à la vitesse -x_acc self.acc.x -= self.x_acc # et s'il dépasse -max_speed, on cap à -max_speed self.acc.x = max(self.acc.x, -self.max_speed) elif (key.get_pressed()[K_RIGHT]): # S'il se déplace à droite on accélère à la vitesse x_acc self.acc.x += self.x_acc # et s'il dépasse max_speed, on cap à max_speed self.acc.x = min(self.acc.x, self.max_speed) else: # Si le joueur ne se déplace plus, il faut décélérer (tendre vers 0) # Si on est à plusieurs fois x_dec de 0, on se rapproche de 0 dans le # bon sens if (self.acc.x < -self.x_dec): self.acc.x += self.x_dec elif (self.acc.x > self.x_dec): self.acc.x -= self.x_dec else: # Sinon, si on est à x_dec de 0, on met directement à 0 pour stopper # la balle, sinon elle accélère et décélère en bouche self.acc.x = 0 # Avec tous ces calculs, on change la position de la balle self.pos += self.acc # Et on la dessine draw.circle(screen, WHITE, self.pos + Vector2(self.diameter / 2), self.diameter / 2)