dari script ini improve agar tidak ada batass RecursionError: maximum recursion depth exceeded ,, buatkan dengen benar dan lengkap : 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 = "Ace of Base - Happy Nation.mp3.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 = True # 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=(255, 255, 255))
new.delta = [random.randint(-2, 2)/20, random.randint(5, 15)/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(),,, agar tidak ada output error ini : pygame-ce 2.5.1 (SDL 2.30.6, Python 3.9.19)
Traceback (most recent call last):
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 985, in
main()
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 963, in main
if msg := game.start_song(screen):
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 731, in start_song
self.safe_areas = self.world.gen_future_bounces(self.notes, update_loading_screen)
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 653, in gen_future_bounces
self.future_bounces = recurs(
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 610, in recurs
toextend = recurs(
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 610, in recurs
toextend = recurs(
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 610, in recurs
toextend = recurs(
[Previous line repeated 989 more times]
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 613, in recurs
bounces_so_far=[_b.copy() for _b in bounces_so_far],
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 613, in
bounces_so_far=[_b.copy() for _b in bounces_so_far],
File "d:\Script\chubb3Dmusic\chubbMidi\chubb copy.py", line 302, in copy
return Bounce(self.square_pos.copy(), self.square_dir.copy(), self.time, self.bounce_dir)
RecursionError: maximum recursion depth exceeded
To resolve the RecursionError: maximum recursion depth exceeded, we need to address the deep recursion caused by the recurs function inside the gen_future_bounces method. The recursion depth increases with the number of notes being processed, leading to exceeding Python's default recursion limit (which is 1000).
Here are the steps to improve the script:
Increase the Recursion Limit:
We can increase the maximum recursion depth by using sys.setrecursionlimit(). However, this is not a perfect solution and might lead to other issues if set too high. Still, it can temporarily resolve the error if the number of notes isn't excessively large.
import sys
sys.setrecursionlimit(2000)
Limit the Number of Notes Processed:
By limiting the number of notes, we can ensure that the recursion depth stays within the manageable limit. You can set Config.max_notes to a value that doesn't exceed the recursion limit.
# At the top of your code where configurations are set
# Maximum notes to process (adjust as needed)
MAX_NOTES = 900
# In the Config class
class Config:
# ... other configurations ...
max_notes: Optional[int] = MAX_NOTES
# ... rest of the class ...
Modify the recurs Function:
While converting the recursive function to an iterative one is ideal, it might be complex due to the nature of the code. For now, you can add a check to prevent the recursion from going too deep:
MAX_RECURSION_DEPTH = 900 # Adjust as needed based on sys.getrecursionlimit()
def recurs(...):
# ... existing code ...
if depth > MAX_RECURSION_DEPTH:
while len(path) != path_segment_start:
path.pop()
return False
# ... rest of the code ...
Combining these steps, here's the improved section of your script:
import sys
import pygame
import mido
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
sys.setrecursionlimit(2000)
# =========================
# Customizable Configuration
# =========================
# Screen Resolution
SCREEN_WIDTH = 1280 # Ganti sesuai keinginan Anda
SCREEN_HEIGHT = 720 # Ganti sesuai keinginan Anda
# File Selection
SONG = "Ace of Base - Happy Nation.mp3.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 = True # Aktifkan atau nonaktifkan jejak partikel
PARTICLE_SPEED = 5
BOUNCE_PEG = True
# Maximum notes to process (adjust as needed)
MAX_NOTES = 900
# =========================
# ... rest of your code ...
class Config:
# Constants
SQUARE_SIZE = SQUARE_SIZE
PARTICLE_SPEED = PARTICLE_SPEED
# Colors
# ... existing code ...
# Configuration
# ... existing code ...
theme: Optional[str] = "dark"
seed: Optional[int] = None
camera_mode: Optional[int] = 2
start_playing_delay = 3000
max_notes: Optional[int] = MAX_NOTES # Set the maximum notes here
bounce_min_spacing: Optional[float] = BOUNCE_MIN_SPACING
square_speed: Optional[int] = SQUARE_SPEED
volume: Optional[int] = 70
music_offset: Optional[int] = 0
direction_change_chance: Optional[int] = DIRECTION_CHANGE
theatre_mode = True
particle_trail = PARTICLE_TRAIL
do_color_bounce_pegs = BOUNCE_PEG
do_particles_on_bounce = True
# ... rest of your code ...
class World:
# ... existing code ...
def gen_future_bounces(self, _start_notes: list[float], percent_update_callback):
"""Recursive function with optimized overlap checking"""
total_notes = len(_start_notes)
max_percent = 0
path = []
safe_areas = []
force_return = 0
MAX_RECURSION_DEPTH = 900 # Adjust according to sys.getrecursionlimit()
def recurs(
square: Square,
notes: list[float],
bounces_so_far: list[Bounce] = None,
prev_index_priority=None,
t: float = 0,
depth: int = 0
) -> Union[list[Bounce], bool]:
nonlocal force_return, max_percent
if prev_index_priority is None:
prev_index_priority = [0, 1]
if bounces_so_far is None:
bounces_so_far = []
if total_notes:
gone_through_percent = (total_notes-len(notes)) * 100 // total_notes
while gone_through_percent > max_percent:
max_percent += 1
if percent_update_callback(f"{max_percent}% done generating map"):
raise UserCancelsLoadingError()
if depth > MAX_RECURSION_DEPTH:
while len(path) != path_segment_start:
path.pop()
return False
# ... rest of the recurs function ...
_start_notes = _start_notes[:Config.max_notes] if Config.max_notes is not None else _start_notes
# ... rest of the gen_future_bounces method ...
# ... rest of your code ...
By setting MAX_NOTES to a value like 900 and increasing the recursion limit, you should avoid the RecursionError. Keep in mind that these are temporary fixes, and the ideal solution would be to refactor the recursive function into an iterative one to handle large numbers of notes without recursion issues.