improve script berikut ini, pastikan kepadatan jumlah bintang nya merata untuk seluruh map, karena ini masih memadat dan tidak merata pada 1 area saja, seharus nya merata, lalu improve dept effect untuk bintang nya agar lebih real , lakukan improvisasi lainnya yang dibutuhkan agar sempurna, buatkan dengan tepat dan benar : 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
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' # Judul lagu
SONG_CREATOR = 'SUBSCRIBE :D' # Kreator lagu
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 = 10
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))
# Safe areas and stars
for safe_area, stars in self.world.stars_in_safe_areas:
offsetted_area = self.camera.offset(safe_area)
if screen_rect.colliderect(offsetted_area):
pygame.draw.rect(screen, get_colors()["hallway"], offsetted_area)
# Render stars within this safe area
for star in stars:
parallax_factor = 1 / star.depth
screen_x = star.x - self.camera.x * parallax_factor
screen_y = star.y - self.camera.y * parallax_factor
screen_pos = (screen_x, screen_y)
if offsetted_area.collidepoint(screen_pos):
pygame.draw.circle(screen, (255, 255, 255), screen_pos, star.size)
# 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"])
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()
To address your request for improving the script, specifically:
Ensure the density of the stars is evenly distributed throughout the entire map, because currently they are concentrated and uneven in only one area.
Improve the depth effect for the stars to make them more realistic.
Make any other necessary improvisations to make it perfect.
Here is a detailed plan to modify the script to meet these requirements:
1. Even Distribution of Stars Across the Entire Map
Issue Identification: In the current script, stars are generated only within the "safe areas," which can lead to uneven star distribution since safe areas might be clustered in certain parts of the map.
Solution: Modify the generate_stars method in the World class to generate stars over the entire map area rather than just within the safe areas.
Implementation Steps:
Calculate Map Boundaries: After the safe areas are finalized and merged in the gen_future_bounces method, compute the overall map boundaries (minimum and maximum x and y coordinates) by iterating through the safe areas.
def calculate_map_boundaries(self):
min_x = min(area.left for area in self.safe_areas)
max_x = max(area.right for area in self.safe_areas)
min_y = min(area.top for area in self.safe_areas)
max_y = max(area.bottom for area in self.safe_areas)
return pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
Generate Stars Over Entire Map: In the generate_stars method, use the calculated map boundaries to generate stars across the entire map area.
def generate_stars(self):
# Generate stars over the entire map area
area = self.map_rect
area_size = area.width * area.height
num_stars = int(area_size / Config.STAR_DENSITY)
stars = []
for _ in range(num_stars):
x = random.uniform(area.left, area.right)
y = random.uniform(area.top, area.bottom)
depth = random.uniform(Config.MIN_STAR_DEPTH, Config.MAX_STAR_DEPTH)
star = Star(x, y, depth)
stars.append(star)
self.stars = stars # Save the stars
Adjust STAR_DENSITY: Since the map area might be significantly larger than earlier, adjust Config.STAR_DENSITY to ensure a reasonable number of stars. You might need to increase the value to maintain performance.
Config.STAR_DENSITY = 100000 # Adjust as needed
Modify Drawing Code: Update the drawing logic in the Game.draw method to render stars from self.world.stars rather than from stars tied to safe areas.
Issue Identification: The current depth effect may not be realistic enough, and depth ranges might not provide a significant parallax effect.
Solution: Enhance the parallax effect and adjust star brightness based on depth to create a more realistic depth perception.
Implementation Steps:
Adjust Depth Ranges: Increase the range of MIN_STAR_DEPTH and MAX_STAR_DEPTH in the Config class to allow for a greater depth variance among stars.
Config.MIN_STAR_DEPTH = 0.5
Config.MAX_STAR_DEPTH = 10 # Increased from 5 to 10
Improve Parallax Calculation: Ensure that closer stars move more significantly relative to the camera movement, while distant stars move less. This is already achieved with parallax_factor = 1 / star.depth, but you can fine-tune it further if necessary.
Adjust Star Brightness and Size Based on Depth: Modify the drawing code to adjust the brightness and size of stars based on their depth. Closer stars should appear brighter and larger, while distant stars are dimmer and smaller.
Enhance Star Generation: Ensure that stars are distributed across different depths uniformly or tweak the depth distribution to group stars at certain desirable depths for a better visual effect.
3. Other Necessary Improvements
Consistent Starfield Across Runs: Set a random seed for star generation to ensure that the starfield remains consistent every time the game runs.
random.seed(Config.star_seed) # Set star_seed in Config, e.g., Config.star_seed = 42
Optimize Performance:
Clipping Stars Outside the Viewport: Already handled by checking screen_rect.collidepoint(screen_pos) before drawing each star.
Efficient Data Structures: If performance becomes an issue with a large number of stars, consider spatial partitioning or only generating/drawing stars near the current camera position.
Code Clean-up and Comments: Ensure that comments are clear (preferably in English if your codebase is in English for consistency) and remove any redundant code.
User Settings for Star Density and Depth: Expose settings for star density and depth ranges to allow users to adjust them according to their preferences and hardware capabilities.
Updated Sections of the Code
Below are the key updated sections of the script incorporating the improvements:
In World Class:
def calculate_map_boundaries(self):
min_x = min(area.left for area in self.safe_areas)
max_x = max(area.right for area in self.safe_areas)
min_y = min(area.top for area in self.safe_areas)
max_y = max(area.bottom for area in self.safe_areas)
return pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
def generate_stars(self):
# Generate stars over the entire map area
area = self.map_rect
area_size = area.width * area.height
num_stars = int(area_size / Config.STAR_DENSITY)
stars = []
for _ in range(num_stars):
x = random.uniform(area.left, area.right)
y = random.uniform(area.top, area.bottom)
depth = random.uniform(Config.MIN_STAR_DEPTH, Config.MAX_STAR_DEPTH)
star = Star(x, y, depth)
stars.append(star)
self.stars = stars # Save the stars
In Game.draw Method:
# Draw safe areas
for safe_area in self.world.safe_areas:
offsetted_area = self.camera.offset(safe_area)
if screen_rect.colliderect(offsetted_area):
pygame.draw.rect(screen, get_colors()["hallway"], offsetted_area)
# Draw stars
for star in self.world.stars:
parallax_factor = 1 / star.depth
screen_x = star.x - self.camera.x * parallax_factor
screen_y = star.y - self.camera.y * parallax_factor
screen_pos = (screen_x, screen_y)
if screen_rect.collidepoint(screen_pos):
brightness = max(100, min(255, int(255 * (1 / (star.depth * 0.5)))))
color = (brightness, brightness, brightness)
pygame.draw.circle(screen, color, screen_pos, star.size)
In Config Class:
# Starfield Configuration
MIN_STAR_DEPTH = 0.5 # Closer stars
MAX_STAR_DEPTH = 10 # Further stars
STAR_DENSITY = 100000 # Adjusted density value for uniform distribution
BASE_STAR_SIZE = 2 # Base size for stars
# Other configurations
star_seed = 42 # Consistent starfield across runs
In main() Function Before Star Generation:
# Set seed for consistent starfield
random.seed(Config.star_seed)
Conclusion
With these modifications, the stars should now be evenly distributed across the entire map, and the depth effect should appear more realistic due to adjustments in parallax calculation, star size, and brightness based on depth.
Please replace the corresponding sections in your script with the above code to implement the improvements.
improve script berikut ini, pastikan kepadatan jumlah… · The Chat Archive