dari script ini ganti agar dapat menentukan song yang dipilih langsung saja dari file mid nya tidak menggunakan zip, dan langsung men generate map untuk lagu yang digunakan tersebut, buat kan dengan benar dan tepat lalu lengkap : import pygame
import mido
from os.path import join, isfile
from zipfile import ZipFile
from time import time as get_current_time
from typing import Union, Optional, Any
import sys
import random
import numpy as np
from enum import Enum
from math import sin, pi
import json
from io import BytesIO
from sys import setrecursionlimit
setrecursionlimit(10000) # Increase if more notes
pygame.init()
=========================
Customizable Configuration
=========================
Screen Resolution
SCREEN_WIDTH = 800 # Ganti sesuai keinginan Anda
SCREEN_HEIGHT = 600 # Ganti sesuai keinginan Anda
MIDI ZIP File Selection
selected_song_filename = 'bad-piggies.zip' # Ganti dengan nama file ZIP lagu Anda
Other Customizable Settings
square_speed = 600 # Kecepatan kotak
bounce_min_spacing = 30 # Spasi minimum antar pantulan
direction_change_chance = 50 # Peluang perubahan arah
particle_trail = True # Aktifkan atau nonaktifkan jejak partikel
=========================
class Config:
# Constants
SQUARE_SIZE = 50
PARTICLE_SPEED = 10
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
Assistant
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 ZipFile(Config.current_song.fp) as zf:
with zf.open(Config.current_song.song_file_name) 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, 100))
loading_text = get_font(60).render(message, True, get_colors()["hallway"])
screen.blit(loading_text, (10, 10))
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 :("
self.world.start_time = get_current_time()
self.world.square.dir = [1, 1] # Ensure starting direction is not [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 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.current_song.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_zip(fpath: str) -> Any:
with ZipFile(fpath) as zf:
if 'metadata.json' not in zf.namelist():
raise InvalidSongError(f"No metadata.json in {fpath}")
metadata_info = zf.getinfo("metadata.json")
metadata = json.loads(zf.read(metadata_info).decode('utf-8'))
if "name" not in metadata:
raise InvalidSongError(f"No name in metadata of {fpath}")
if "mapper" not in metadata:
raise InvalidSongError(f"No mapper in metadata of {fpath}")
if "audio_file" not in metadata:
raise InvalidSongError(f"No audio_file in metadata of {fpath}")
if "song_file" not in metadata:
raise InvalidSongError(f"No song_file in metadata of {fpath}")
if "version" not in metadata:
raise InvalidSongError(f"No version in metadata of {fpath}")
name = metadata.get("name")
artist = metadata.get("artist", metadata.get("author", "Unknown Artist"))
mapper = metadata.get("mapper")
audio_file = metadata.get("audio_file")
song_file = metadata.get("song_file")
version = metadata.get("version", -1)
new_song = type('Song', (object,), {})()
new_song.name = name
new_song.audio_file_name = audio_file
new_song.song_file_name = song_file
new_song.song_artist = artist
new_song.mapper = mapper
new_song.version = version
new_song.fp = fpath
new_song.music_offset = metadata.get("music_offset", 0)
return new_song
# Specify the song file to use
selected_song_filepath = join('songs', selected_song_filename)
if not isfile(selected_song_filepath):
print(f"Song file {selected_song_filepath} not found.")
return
try:
Config.current_song = make_song_from_zip(selected_song_filepath)
except InvalidSongError as e:
print(f"Error loading song: {e}")
return
# Load the music file
with ZipFile(Config.current_song.fp) as zf:
with zf.open(Config.current_song.audio_file_name) as f:
pygame.mixer.music.load(BytesIO(f.read()))
pygame.mixer.music.set_volume(Config.volume / 100)
# Initialize the game
game = Game()
# Start the game after a 3-second wait
pygame.time.wait(3000) # Wait for 3 seconds
game.active = True
if msg := game.start_song(screen):
if isinstance(msg, str):
print(f"Error starting game: {msg}")
return
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 modify your script so that it can select a song directly from a MIDI (.mid) file instead of using a zip file, and to generate the map for the song, you'll need to adjust your code to:
Replace zip file handling with direct MIDI file handling.
Adjust the code to read and play the MIDI file appropriately.
Ensure any references to zip files are removed or modified.
Here's how you can achieve this:
1. Update the Configuration
In your configuration section, update the selected_song_filename to point to your MIDI file:
# Screen Resolution
SCREEN_WIDTH = 800 # Adjust as desired
SCREEN_HEIGHT = 600 # Adjust as desired
# MIDI File Selection
selected_song_filename = 'your_song.mid' # Replace with your MIDI file name
2. Remove ZipFile Dependencies
Since you're no longer using zip files, remove any imports and code related to zip handling:
Remove the import statement for ZipFile:
# Remove this line:
# from zipfile import ZipFile
Remove any code that uses ZipFile. For example, if you have a function like make_song_from_zip, you should remove or modify it to handle MIDI files directly.
3. Adjust the main() Function
Modify your main() function to handle the MIDI file directly:
Set the selected_song_filepath to point directly to your MIDI file:
selected_song_filepath = join('songs', selected_song_filename)
if not isfile(selected_song_filepath):
print(f"Song file {selected_song_filepath} not found.")
return
Instead of loading the song from a zip file, create a simple Song object to hold song information:
# Set the current song
Config.current_song = type('Song', (object,), {})()
Config.current_song.song_file_name = selected_song_filepath
Config.current_song.music_offset = 0 # Set to the desired offset (if any)
# Load the audio file (if you have an audio file corresponding to the MIDI)
audio_file_path = selected_song_filepath.replace('.mid', '.mp3') # Adjust the extension as needed
if isfile(audio_file_path):
pygame.mixer.music.load(audio_file_path)
pygame.mixer.music.set_volume(Config.volume / 100)
else:
print("Audio file not found. Proceeding without audio.")
# You may choose to handle this case differently
4. Modify the Game.start_song() Method
In your Game class, update the start_song method to read the MIDI file directly:
Remove the code that opens the MIDI file from a zip archive.
Modify the code to read the MIDI file directly:
def start_song(self, screen: pygame.Surface):
random.seed(Config.seed)
# Load song and notes directly from the MIDI file
notes = read_midi_file(file=Config.current_song.song_file_name)
notes = sorted([note for note in notes])
self.notes = notes
# ... rest of your code remains the same
5. Remove References to Zip Files
Ensure you remove all other references to zip files in your code. For example:
If you have any code that attempts to read metadata from a zip file, you'll need to adjust it or remove it.
6. Handle MIDI Playback (Optional)
Note: MIDI files contain instructions for playback (not actual audio data). pygame.mixer cannot play MIDI files directly. If you want to play the MIDI file, you'll need to use pygame.midi or another library that can handle MIDI playback.
To play MIDI files using pygame.midi:
import pygame.midi
pygame.midi.init()
player = pygame.midi.Output(0)
midi_file = mido.MidiFile(Config.current_song.song_file_name)
for msg in midi_file.play():
if not msg.is_meta:
data = msg.bytes()
player.write_short(*data)
However, MIDI playback can be complex and hardware-dependent. If you don't need to play the MIDI file, or if you have an accompanying audio file (like an MP3 or WAV), you can use that instead.
7. Ensure Everything Works Together
After making these changes, your script should:
Select and read the MIDI file directly.
Generate the map based on the MIDI file notes.
Play the corresponding audio file if available.
Example Adjusted Code Snippets
Here are the key adjustments in code form:
In the configuration section:
selected_song_filename = 'your_song.mid' # Replace with your MIDI file name
In the main() function:
def main():
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((Config.SCREEN_WIDTH, Config.SCREEN_HEIGHT))
pygame.display.set_caption("Midi Playground")
try:
pygame.display.set_icon(pygame.image.load("./assets/icon.png").convert_alpha())
except Exception as e:
print(e)
# Specify the song file to use
selected_song_filepath = join('songs', selected_song_filename)
if not isfile(selected_song_filepath):
print(f"Song file {selected_song_filepath} not found.")
return
# Set the current song
Config.current_song = type('Song', (object,), {})()
Config.current_song.song_file_name = selected_song_filepath
Config.current_song.music_offset = 0 # Adjust as needed
# Load the audio file (if available)
audio_file_path = selected_song_filepath.replace('.mid', '.mp3') # Or '.wav', '.ogg'
if isfile(audio_file_path):
pygame.mixer.music.load(audio_file_path)
pygame.mixer.music.set_volume(Config.volume / 100)
else:
print("Audio file not found. Proceeding without audio.")
# Handle accordingly (e.g., skip audio playback)
# Initialize the game
game = Game()
# Start the game
game.active = True
if msg := game.start_song(screen):
if isinstance(msg, str):
print(f"Error starting game: {msg}")
return
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()
In the Game class's start_song method:
def start_song(self, screen: pygame.Surface):
random.seed(Config.seed)
# Load song and notes directly from the MIDI file
notes = read_midi_file(file=Config.current_song.song_file_name)
notes = sorted([note for note in notes])
self.notes = notes
# ... rest of your code remains the same
By making these adjustments, your script will read the MIDI file directly, generate the map, and handle audio playback if an accompanying audio file is available.
Important Notes:
MIDI Playback: Playing MIDI files directly can be complex, as they require a synthesizer to interpret the MIDI messages. The pygame.mixer.music module does not support MIDI files by default. If you need to play MIDI files, consider using the pygame.midi module or convert your MIDI files to an audio format like WAV or MP3 using external tools.
Audio File Requirement: If you want audio playback during your game, it's recommended to have an accompanying audio file in a supported format (e.g., MP3, WAV, OGG) that corresponds to your MIDI file.
Adjust Paths and File Names: Ensure that the paths and file names used in your code match the actual locations and names of your MIDI and audio files.
Conclusion
By following the steps above, you can modify your script to work directly with MIDI files without relying on zip archives. This will allow you to select the song from the MIDI file and generate the map based on it.
Let me know if you have any questions or need further assistance!