dari script ini ganti warna perticle dan atur banyak nya partikel agar lebih banyak, untuk warna nya mengikuti warna square : import pygame
import mido
import sys
import random
import requests
import colorsys
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 os
pygame.init()
=========================
Customizable Configuration
=========================
Screen Resolution
SCREEN_WIDTH = 800 # Ganti sesuai keinginan Anda
SCREEN_HEIGHT = 600 # Ganti sesuai keinginan Anda
File Selection
selected_song_filename = "rush-e.mid" # Ganti dengan nama file MIDI Anda
Song Information
song_name = 'Bad Piggies' # Set the song name here
song_creator = 'Rovio' # Set the song creator here
Other Customizable Settings
square_speed = 600 # Kecepatan kotak
bounce_min_spacing = 50 # Spasi minimum antar pantulan
direction_change_chance = 50 # Peluang perubahan arah
particle_trail = True # Aktifkan atau nonaktifkan jejak partikel
=========================
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
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.05)
# Prepare text surfaces with per-pixel alpha
title = song_name
creator = song_creator
title_surface = get_font(font_size).render(f"Title: {title}", True, get_colors()["hallway"])
creator_surface = get_font(font_size).render(f"Creator: {creator}", True, get_colors()["hallway"])
# 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_size))
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))
# Safe areas
for safe_area in self.safe_areas:
offsetted = self.camera.offset(safe_area)
if screen_rect.colliderect(offsetted):
pygame.draw.rect(screen, get_colors()["hallway"], offsetted)
# 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:
# Add a particle periodically
if not self.world.square.died:
new = Particle(self.world.square.pos.copy(), [0, 0], True)
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, selected_song_filename)
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"])
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()
Untuk mengubah warna partikel agar mengikuti warna kotak dan menambah jumlah partikel dalam skrip Anda, ikuti langkah-langkah berikut:
Tingkatkan Jumlah Partikel
Ubah nilai particle_amount di kelas Config untuk menambah jumlah partikel. Misalnya, ubah dari 10 menjadi 30 atau lebih:
class Config:
# ... konfigurasi lainnya ...
particle_amount = 30 # Atur ke jumlah yang lebih besar sesuai keinginan Anda
# ... konfigurasi lainnya ...
Modifikasi Kelas Particle untuk Menerima Warna
Ubah metode __init__ dalam kelas Particle agar dapat menerima parameter warna dan menggunakannya untuk menetapkan warna partikel:
class Particle:
# ... atribut kelas lainnya ...
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"]
Tambahkan Metode untuk Mendapatkan Warna Kotak Saat Ini
Pada kelas Square, tambahkan metode untuk mendapatkan warna kotak berdasarkan arah saat ini:
class Square:
# ... metode dan atribut lainnya ...
def get_current_color(self):
square_color_index = round((self.dir_x + 1) / 2 + self.dir_y + 1)
return get_colors()["square"][square_color_index % len(get_colors()["square"])]
Modifikasi Metode add_bounce_particles untuk Menerima Warna
Ubah metode add_bounce_particles dalam kelas World untuk menerima parameter warna dan meneruskannya saat membuat partikel:
class World:
# ... metode dan atribut lainnya ...
def add_bounce_particles(self, sp: list[float], sd: list[float], color: tuple):
for _ in range(Config.particle_amount):
new = Particle([sp[0] + random.randint(-10, 10), sp[1] + random.randint(-10, 10)], sd, color=color)
self.particles.append(new)
Gunakan Warna Kotak Saat Membuat Partikel Pantulan
Pada metode handle_bouncing dalam kelas World, panggil get_current_color() untuk mendapatkan warna kotak dan gunakan saat menambahkan partikel pantulan:
class World:
# ... metode dan atribut lainnya ...
def handle_bouncing(self, square: Square):
if len(self.future_bounces):
if (self.time * 1000 + Config.music_offset)/1000 > self.future_bounces[0].time:
current_bounce = self.get_next_bounce()
before = square.dir.copy()
square.obey_bounce(current_bounce)
changed = square.dir.copy()
for _ in range(2):
if before[_] == changed[_]:
changed[_] = 0
else:
changed[_] = -changed[_]
if Config.do_particles_on_bounce:
square_color = square.get_current_color()
self.add_bounce_particles(square.pos, changed, color=square_color)
# ... kode lainnya ...
Gunakan Warna Kotak untuk Partikel Jejak
Modifikasi bagian yang menambahkan partikel jejak dalam metode draw di kelas Game:
class Game:
# ... metode dan atribut lainnya ...
def draw(self, screen: pygame.Surface):
# ... kode lainnya ...
# Partikel
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)
# Partikel jejak dalam 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)
# ... kode lainnya ...
Dengan melakukan perubahan di atas:
Warna Partikel Akan Mengikuti Warna Kotak: Partikel yang dihasilkan baik dari pantulan maupun dari jejak akan memiliki warna yang sama dengan kotak saat itu.
Jumlah Partikel Bertambah: Nilai particle_amount yang ditingkatkan akan menghasilkan lebih banyak partikel, membuat efek partikel lebih padat dan terlihat.
Catatan Tambahan:
Pastikan Anda mengimpor Optional dari typing jika belum ada:
from typing import Optional
Jika diperlukan, pastikan untuk menyesuaikan nilai lain seperti SIZE_MIN, SIZE_MAX, atau parameter lain dalam kelas Particle untuk mendapatkan tampilan partikel sesuai keinginan Anda.
Setelah menerapkan perubahan ini, jalankan kembali skrip Anda. Anda akan melihat bahwa partikel sekarang memiliki warna yang sama dengan kotak dan jumlah partikel telah meningkat, memberikan efek visual yang lebih menarik.