dari script ini improve particle trail nya agar bentuk nya lebih memanjang dan ganti warna trail ini menjadi warna putih saja, buatkan dengan benar dan tepat : import pygame
import mido
import sys
import random
import requests
import colorsys
import os
from os.path import join, isfile
from time import time as get_current_time
from typing import Union, Optional, Any
from enum import Enum
from math import sin, pi
import math # Ditambahkan untuk fungsi matematika
pygame.mixer.init()
pygame.init()
FRAMERATE = 60
=========================
Customizable Configuration
=========================
Screen Resolution
SCREEN_WIDTH = 1280 # Ganti sesuai keinginan Anda
SCREEN_HEIGHT = 720 # Ganti sesuai keinginan Anda
File Selection
SONG = "bad-piggies.mid" # Ganti dengan nama file MIDI Anda
Song Information
SONG_NAME = 'SquareVibes' # Set the song name here
SONG_CREATOR = 'SUBSCRIBE :D' # Set the song creator here
Other Customizable Settings
SQUARE_SPEED = 600 # Kecepatan kotak
SQUARE_SIZE = 50
BOUNCE_MIN_SPACING = 50 # Spasi minimum antar pantulan
DIRECTION_CHANGE = 30 # Peluang perubahan arah
PARTICLE_TRAIL = False # Aktifkan atau nonaktifkan jejak partikel
PARTICLE_SPEED = 5
BOUNCE_PEG = True
=========================
def color_hunt():
def is_bright(hex_color):
hex_color = hex_color.lstrip('#')
rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
luminance = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]
r, g, b = [x / 255.0 for x in rgb]
h, s, v = colorsys.rgb_to_hsv(r, g, b)
return luminance >= 130 and s >= 0.3
while True:
url = 'https://colorhunt.co/php/feed.php'
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
data = {
'step': 0,
'sort': 'random',
'tags': ''
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
palettes = response.json()
color_pairs = []
for palette in palettes:
code = palette['code']
hex_colors = [f'#{code[i:i+6].upper()}' for i in range(0, len(code), 6)]
if len(hex_colors) == 4 and all(is_bright(hex_color) for hex_color in hex_colors):
color_pairs.append(tuple(hex_colors))
if color_pairs:
selected_color_pair = random.choice(color_pairs)
return selected_color_pair
else:
raise Exception(f"Failed to retrieve data. Status code: {response.status_code}")
notes = []
current_time = 0
for msg in midi_file:
if msg.type == 'note_on' and msg.velocity != 0:
timestamp = current_time + msg.time
notes.append(round(timestamp*1000)/1000)
current_time += msg.time
return notes
def remove_too_close_values(lst: list[float], threshold=30) -> list[float]:
"""Assumes the list is sorted"""
new = []
before = None
for _ in lst:
if before is None:
before = _
new.append(_)
continue
if before+threshold/1000 > :
continue
before = _
new.append()
return new
def fix_overlap(rects: list[pygame.Rect], callback=None):
"""
Optimized function to merge overlapping rectangles efficiently.
"""
if callback is None:
callback = lambda _: None
rects = rects.copy()
# Sort rectangles based on x coordinate
rects.sort(key=lambda r: (r.x, r.y))
merged_rects = []
for rect in rects:
if not merged_rects:
merged_rects.append(rect)
else:
last = merged_rects[-1]
if last.colliderect(rect):
merged_rect = last.union(rect)
merged_rects[-1] = merged_rect
else:
merged_rects.append(rect)
callback("Finished merging rectangles")
return merged_rects
def __init__(self, pos: list[float], delta: list[float], invert_color: bool = False, color: Optional[tuple] = None):
self.pos = pos.copy()
self.size = random.randint(Particle.SIZE_MIN, Particle.SIZE_MAX)
self.delta = delta.copy()
self.delta[0] += random.randint(-Particle.SPEED_VARIATION, Particle.SPEED_VARIATION)/8
self.delta[1] += random.randint(-Particle.SPEED_VARIATION, Particle.SPEED_VARIATION)/8
if color is not None:
self.color = color
else:
# Warna default jika warna tidak diberikan
self.color = get_colors()["hallway"] if not invert_color else get_colors()["background"]
def age(self):
self.size -= Particle.AGE_RATE*Config.dt
self.x += self.delta[0] * Config.PARTICLE_SPEED
self.y += self.delta[1] * Config.PARTICLE_SPEED
if Config.dt != 0:
self.delta[0] /= (Particle.SLOW_DOWN_RATE+FRAMERATE) * Config.dt
self.delta[1] /= (Particle.SLOW_DOWN_RATE+FRAMERATE) * Config.dt
return self.size <= 0
@property
def x(self):
return self.pos[0]
@x.setter
def x(self, val: float):
self.pos[0] = val
@property
def y(self):
return self.pos[1]
@y.setter
def y(self, val: float):
self.pos[1] = val
@property
def rect(self):
return pygame.Rect(self.x-self.size/2, self.y-self.size/2, *(2*[self.size]))
class Bounce:
def init(self, sq_pos: list[float], sq_dir: list[int], time: float, bounce_dir: int):
self.square_pos = sq_pos # New square position
self.square_dir = sq_dir # New square direction
self.bounce_dir = bounce_dir # Bounce direction for squish effect; 0 or 1
self.time = time # Time during bounce
def get_collision_rect(self):
sx, sy = self.square_pos
if self.bounce_dir == 0:
# Bounce left or right wall
if self.square_dir[0] == -1:
# Right wall
return pygame.Rect(
sx+Config.SQUARE_SIZE/2+1,
sy-10,
10,
20
)
elif self.square_dir[0] == 1:
# Left wall
return pygame.Rect(
sx-10-Config.SQUARE_SIZE/2-1,
sy-10,
10,
20
)
elif self.bounce_dir == 1:
# Bounce top or bottom wall
if self.square_dir[1] == -1:
# Bottom wall
return pygame.Rect(
sx-10,
sy+Config.SQUARE_SIZE/2+1,
20,
10
)
elif self.square_dir[1] == 1:
# Top wall
return pygame.Rect(
sx-10,
sy-10-Config.SQUARE_SIZE/2-1,
20,
10
)
def copy(self) -> "Bounce":
return Bounce(self.square_pos.copy(), self.square_dir.copy(), self.time, self.bounce_dir)
def __repr__(self):
return f"<Bounce(sq_pos={self.square_pos}, sq_dir={self.square_dir}, time={self.time}, dir={self.bounce_dir})"
class Camera:
def init(self, x: int = 0, y: int = 0):
self.x = x
self.y = y
self.locked_on_square = True
self.lock_type: CameraFollow = CameraFollow(Config.camera_mode)
def start_song(self, screen: pygame.Surface):
random.seed(Config.seed)
# Load song and notes
with open(Config.current_song.fp, 'rb') as f:
notes = read_midi_file(file=f)
notes = sorted([note for note in notes])
self.notes = notes
# Other settings
self.world = World()
self.music_has_played = False
self.offset_happened = False
self.camera.lock_type = CameraFollow(Config.camera_mode)
screen.fill(get_colors()["background"])
pygame.display.flip()
def update_loading_screen(message: str):
screen.fill(get_colors()["background"], pygame.Rect(0, 0, Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT))
font_size = int(Config.SCREEN_HEIGHT * 0.05)
loading_text = get_font(font_size).render(message, True, get_colors()["hallway"])
text_rect = loading_text.get_rect()
text_rect.center = (Config.SCREEN_WIDTH // 2, Config.SCREEN_HEIGHT // 2)
screen.blit(loading_text, text_rect)
pygame.display.flip()
try:
self.safe_areas = self.world.gen_future_bounces(self.notes, update_loading_screen)
# No need to fix overlap here, as it's handled in gen_future_bounces
except UserCancelsLoadingError:
return True
except MapLoadingFailureError as e:
return e.args[0] if len(e.args) else "Big error... can't load map :("
# Display song title and creator with fade-in and fade-out effects
self.display_song_info(screen)
self.world.start_time = get_current_time()
self.world.square.dir = [0, 0]
if self.world.future_bounces:
self.world.square.pos = self.world.future_bounces[0].square_pos
else:
self.world.square.pos = [Config.SCREEN_WIDTH / 2, Config.SCREEN_HEIGHT / 2]
return None
def display_song_info(self, screen):
# Function to display song title and creator with fade-in and fade-out effects
display_duration = 5000 # milliseconds
fade_duration = 1000 # milliseconds for fade-in and fade-out
start_time = pygame.time.get_ticks()
elapsed = 0
font_size = int(Config.SCREEN_HEIGHT * 0.10)
font_size2 = int(Config.SCREEN_HEIGHT * 0.05)
# Prepare text surfaces with per-pixel alpha
title_surface = get_font(font_size).render(f"{SONG_NAME}", True, color4)
creator_surface = get_font(font_size2).render(f"{SONG_CREATOR}", True, color4)
# Enable alpha blending
title_surface = title_surface.convert_alpha()
creator_surface = creator_surface.convert_alpha()
# Centering the text
title_rect = title_surface.get_rect(center=(Config.SCREEN_WIDTH // 2, Config.SCREEN_HEIGHT // 2 - font_size))
creator_rect = creator_surface.get_rect(center=(Config.SCREEN_WIDTH // 2, Config.SCREEN_HEIGHT // 2 + font_size2))
while elapsed < display_duration:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.handle_event(event)
elapsed = pygame.time.get_ticks() - start_time
# Calculate alpha value
if elapsed < fade_duration:
# Fade-in phase
alpha = int(255 * (elapsed / fade_duration))
elif elapsed > display_duration - fade_duration:
# Fade-out phase
alpha = int(255 * ((display_duration - elapsed) / fade_duration))
else:
# Fully visible
alpha = 255
# Clamp alpha value
alpha = max(0, min(255, alpha))
# Set alpha
title_surface.set_alpha(alpha)
creator_surface.set_alpha(alpha)
# Clear screen
screen.fill(get_colors()["background"])
# Draw text
screen.blit(title_surface, title_rect)
screen.blit(creator_surface, creator_rect)
pygame.display.flip()
pygame.time.delay(30) # Slight delay to control the frame rate
def draw(self, screen: pygame.Surface):
if not self.active:
return
if not self.music_has_played:
if not self.offset_happened:
for bnc_change in self.world.future_bounces:
bnc_change.time += Config.start_playing_delay / 1000
self.offset_happened = True
if self.world.time-Config.music_offset/1000 > Config.start_playing_delay/1000:
self.music_has_played = True
song_load_before = get_current_time()
pygame.mixer.music.play()
for bnc_change in self.world.future_bounces:
bnc_change.time += (get_current_time()-song_load_before)/1000
screen_rect = screen.get_rect()
# Set world time
self.world.update_time()
# Move camera
self.camera.attempt_movement()
# Handle square bounces
self.world.handle_bouncing(self.world.square)
# Move square
self.world.square.reg_move()
# Square in center of camera if locked
if self.camera.locked_on_square:
self.camera.follow(self.world.square)
# Bounce animation
sqrect = self.camera.offset(self.world.square.rect)
if (self.world.time - 0.25) + Config.music_offset / 1000 < self.world.square.last_bounce_time:
lerp = abs((self.world.time - 0.25 + Config.music_offset / 1000) - self.world.square.last_bounce_time) * 5
lerp = lerp ** 2 # Square it for better-looking interpolation
if self.world.square.latest_bounce_direction:
sqrect.inflate_ip((lerp * 5, -10 * lerp))
else:
sqrect.inflate_ip((-10 * lerp, lerp * 5))
# Draw background (walls)
screen.fill(get_colors()["background"])
# Create a hallway surface
hallway_surface = pygame.Surface((Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT), pygame.SRCALPHA)
# Safe areas
for safe_area in self.world.safe_areas:
offsetted = self.camera.offset(safe_area)
if screen_rect.colliderect(offsetted):
pygame.draw.rect(hallway_surface, get_colors()["hallway"], offsetted)
# Obtain current time
current_time = pygame.time.get_ticks() / 1000.0 # Time in seconds
# Draw stars onto the hallway surface
for star in self.world.stars:
star.update(current_time) # Update blinking effect
screen_pos = star.get_screen_pos(self.camera)
if 0 <= screen_pos[0] < Config.SCREEN_WIDTH and 0 <= screen_pos[1] < Config.SCREEN_HEIGHT:
# Check if star's position is within the hallway (safe areas)
if hallway_surface.get_at((int(screen_pos[0]), int(screen_pos[1]))).a != 0:
pygame.draw.circle(hallway_surface, star.color, (int(screen_pos[0]), int(screen_pos[1])), int(star.size))
# Blit the hallway surface onto the main screen
screen.blit(hallway_surface, (0, 0))
# Draw pegs
for i, bounce_rect in enumerate(self.world.rectangles):
offsetted = self.camera.offset(bounce_rect)
if offsetted.colliderect(screen_rect):
if Config.do_color_bounce_pegs and self.world.collision_times[i] < (self.world.time * 1000 + Config.music_offset - Config.start_playing_delay)/1000:
pygame.draw.rect(screen, self.world.colors[i], offsetted)
else:
pygame.draw.rect(screen, get_colors()["background"], offsetted)
# Particles
for particle in self.world.particles:
pygame.draw.rect(screen, particle.color, self.camera.offset(particle.rect))
for remove_particle in [particle for particle in self.world.particles if particle.age()]:
self.world.particles.remove(remove_particle)
# Particle trail in game
if Config.particle_trail:
# Tambahkan partikel secara periodik
if not self.world.square.died:
square_color = self.world.square.get_current_color()
new = Particle(self.world.square.pos.copy(), [0, 0], True, color=square_color)
new.delta = [random.randint(-10, 10)/20, random.randint(-10, 10)/20]
self.world.particles.append(new)
# Draw square
self.world.square.draw(screen, sqrect)
def handle_event(self, event: pygame.event.Event):
if not self.active:
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_TAB:
self.camera.locked_on_square = not self.camera.locked_on_square
class InvalidSongError(Exception):
"""The song is invalid somehow"""
pass
def make_song_from_midi(fpath: str) -> Any:
new_song = type('Song', (object,), {})()
new_song.fp = fpath
new_song.name = SONG_NAME # Use the song name from the top
new_song.creator = SONG_CREATOR # Use the song creator from the top
new_song.music_offset = 0
return new_song
# Specify the song file to use
selected_song_filepath = join(Config.song, SONG)
if not isfile(selected_song_filepath):
print(f"Song file {selected_song_filepath} not found.")
return
Config.current_song = make_song_from_midi(selected_song_filepath)
# Load the music file
try:
pygame.mixer.music.load(Config.current_song.fp)
except Exception as e:
print(f"Error loading MIDI file as audio: {e}")
print("Your platform may not support MIDI playback via pygame.mixer.music.")
print("The game will run without audio.")
# Uncomment the line below to exit if audio is essential
# return
pygame.mixer.music.set_volume(Config.volume / 100)
# Initialize the game
game = Game()
# Start the game
if msg := game.start_song(screen):
if isinstance(msg, str):
print(f"Error starting game: {msg}")
return
game.active = True
running = True
while running:
# screen.fill(get_colors()["background"]) # Moved to the draw function
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
game.handle_event(event)
game.draw(screen)
pygame.display.flip()
clock.tick(FRAMERATE)
Config.dt = clock.get_time() / 1000.0 if clock.get_time() > 0 else 0.016 # Avoid division by zero
pygame.quit()
if name == 'main':
main()
Sure! I can help you modify your script to improve the particle trail so that it becomes more elongated and changes the trail's color to white. Here's how you can do it:
Changes to the Particle Trail:
Make the Particle Trail More Elongated:
Adjust the particles' movement so they trail behind the square more noticeably.
Extend the lifespan of the particles so the trail appears longer.
Change the Trail Color to White:
Set the particles' color to white instead of the current color.
Detailed Modifications:
1. Update the Particle Class
Decrease the AGE_RATE to extend the particles' lifespan.
Adjust the particle's movement direction to trail behind the square.
class Particle:
SPEED_VARIATION = 4
SIZE_MIN = 7
SIZE_MAX = 14
AGE_RATE = 5 # Decrease to make particles last longer
SLOW_DOWN_RATE = 1.2
def __init__(self, pos: list[float], delta: list[float], color: Optional[tuple] = None):
self.pos = pos.copy()
self.size = random.randint(Particle.SIZE_MIN, Particle.SIZE_MAX)
self.delta = delta.copy()
# Remove random variation to make the trail smoother
# self.delta[0] += random.randint(-Particle.SPEED_VARIATION, Particle.SPEED_VARIATION)/8
# self.delta[1] += random.randint(-Particle.SPEED_VARIATION, Particle.SPEED_VARIATION)/8
if color is not None:
self.color = color
else:
# Set default color to white if color is not provided
self.color = (255, 255, 255)
2. Modify the Particle Trail Generation in the Game Class
Set the particle color to white.
Align the particles' movement opposite to the square's direction.
class Game:
...
def draw(self, screen: pygame.Surface):
...
# Particle trail in game
if Config.particle_trail:
# Add particles periodically
if not self.world.square.died:
square_pos = self.world.square.pos.copy()
dx = self.world.square.dir_x
dy = self.world.square.dir_y
# If square is stationary, set default direction
if dx == 0 and dy == 0:
dx, dy = 0, 1 # Default to moving upwards
particle_speed_factor = 10 # Adjust to change trail length
random_factor = 0 # Set to 0 for a consistent trail direction
# Calculate the particle's movement opposite to the square's direction
delta_x = -dx * particle_speed_factor + random.uniform(-random_factor, random_factor)
delta_y = -dy * particle_speed_factor + random.uniform(-random_factor, random_factor)
# Create a new particle with white color
new_particle = Particle(
square_pos,
[delta_x, delta_y],
color=(255, 255, 255) # Set color to white
)
self.world.particles.append(new_particle)
# Particles
for particle in self.world.particles:
# Draw particles as circles to make them look elongated when moving
pygame.draw.circle(screen, particle.color, self.camera.offset((particle.x, particle.y)), int(particle.size))
for remove_particle in [particle for particle in self.world.particles if particle.age()]:
self.world.particles.remove(remove_particle)
...
3. Optionally Increase the Particle Speed
Adjust Config.PARTICLE_SPEED to control how fast the particles move.
class Config:
...
PARTICLE_SPEED = 10 # Increase to make particles move faster
...
Explanation of Changes:
Particle Lifespan (AGE_RATE): By decreasing the AGE_RATE, particles will decrease in size more slowly, effectively extending their lifespan and creating a longer trail.
Particle Movement:
By setting the particle's delta to the negative of the square's direction, the particles will move opposite to the square, creating an elongated trail.
Removing the random variation in delta ensures the trail is smooth and consistent.
Particle Color:
Setting the particle color to white (255, 255, 255) ensures that all trail particles appear white, as requested.
Full Modified Code for Relevant Sections:
Here are the fully modified sections of your code incorporating the changes:
Particle Class:
class Particle:
SPEED_VARIATION = 4
SIZE_MIN = 7
SIZE_MAX = 14
AGE_RATE = 5 # Decreased from 20
SLOW_DOWN_RATE = 1.2
def __init__(self, pos: list[float], delta: list[float], color: Optional[tuple] = None):
self.pos = pos.copy()
self.size = random.randint(Particle.SIZE_MIN, Particle.SIZE_MAX)
self.delta = delta.copy()
if color is not None:
self.color = color
else:
self.color = (255, 255, 255) # Default to white
Game Class (draw Method):
class Game:
...
def draw(self, screen: pygame.Surface):
...
# Particle trail in game
if Config.particle_trail:
# Add particles periodically
if not self.world.square.died:
square_pos = self.world.square.pos.copy()
dx = self.world.square.dir_x
dy = self.world.square.dir_y
# If the square is stationary, default direction for particles
if dx == 0 and dy == 0:
dx, dy = 0, 1 # Move upwards
particle_speed_factor = 10 # Controls trail length
random_factor = 0 # No random variation for consistency
delta_x = -dx * particle_speed_factor + random.uniform(-random_factor, random_factor)
delta_y = -dy * particle_speed_factor + random.uniform(-random_factor, random_factor)
# Create a new particle with white color
new_particle = Particle(
square_pos,
[delta_x, delta_y],
color=(255, 255, 255)
)
self.world.particles.append(new_particle)
# Draw particles
for particle in self.world.particles:
pygame.draw.circle(
screen,
particle.color,
self.camera.offset((particle.x, particle.y)),
int(particle.size)
)
for remove_particle in [particle for particle in self.world.particles if particle.age()]:
self.world.particles.remove(remove_particle)
...
Config Class:
class Config:
...
PARTICLE_SPEED = 10 # Increased from 5 to 10
...
Notes:
Particle Size and Shape: I changed the particle drawing from rectangles to circles to make them appear smoother and more natural. You can adjust the drawing method based on your preference.
Trail Smoothness: Setting random_factor to 0 eliminates randomness in the particles' movement, resulting in a smooth and consistent trail. If you prefer a more scattered trail, you can increase random_factor.
Adjusting Trail Length and Appearance:
particle_speed_factor: Increasing this value makes the trail longer.
AGE_RATE: Decreasing this value extends the particles' lifespan.
PARTICLE_SPEED: Increasing this value makes particles move faster.
Final Thoughts:
With these modifications, your particle trail should now be more elongated and white in color, creating a better visual effect as per your request. Feel free to adjust the particle_speed_factor, AGE_RATE, and PARTICLE_SPEED values to fine-tune the trail's appearance to your liking.
Let me know if you have any questions or need further assistance!