Browse Source

Aggiungi supporto per audio e migliora la gestione delle dipendenze nel progetto

master
Matteo Benedetto 12 months ago
parent
commit
cb25866754
  1. 3
      README.md
  2. 54
      engine/sdl2.py
  3. 28535
      get-pip.py
  4. 7
      get-venv.py
  5. 116
      imgui-test.py
  6. 25
      imgui.ini
  7. 53
      opengl.test.py
  8. 4
      rats.py
  9. 4
      requirements.txt
  10. 3436
      testwindow.py
  11. 15
      wgdzh

3
README.md

@ -1,7 +1,8 @@
# Mice! # Mice!
Mice! is a strategic game where players must kill rats with bombs before they reproduce and become too numerous. The game is a clone of the classic game Rats! for Windows 95. Mice! is a strategic game where players must kill rats with bombs before they reproduce and become too numerous. The game is a clone of the classic game Rats! for Windows 95.
## Compatibility
*It's developed in Python 3.11, please use it*
## Features ## Features
- **Maze Generation**: Randomly generated mazes using Depth First Search (DFS) algorithm. - **Maze Generation**: Randomly generated mazes using Depth First Search (DFS) algorithm.

54
engine/sdl2.py

@ -2,9 +2,12 @@ import os
import sdl2 import sdl2
import sdl2.ext import sdl2.ext
from sdl2.ext.compat import byteify from sdl2.ext.compat import byteify
from ctypes import *
from PIL import Image from PIL import Image
from sdl2 import SDL_AudioSpec
import random
class GameWindow: class GameWindow:
def __init__(self, width, height, cell_size, title="Default", key_callback=None): def __init__(self, width, height, cell_size, title="Default", key_callback=None):
@ -34,10 +37,15 @@ class GameWindow:
self.running = True self.running = True
self.key_down, self.key_up, self.axis_scroll = key_callback self.key_down, self.key_up, self.axis_scroll = key_callback
self.performance = 0 self.performance = 0
self.audio_devs = []
for i in range(5):
self.audio_devs.append((True, sdl2.SDL_OpenAudioDevice(None, 0, SDL_AudioSpec(freq=22050, aformat=sdl2.AUDIO_U8, channels=1, samples=2048), None, 0)))
def load_joystick(self): def load_joystick(self):
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
sdl2.SDL_JoystickOpen(0) sdl2.SDL_JoystickOpen(0)
def generate_fonts(self,font_file): def generate_fonts(self,font_file):
fonts = {} fonts = {}
@ -206,11 +214,41 @@ class GameWindow:
self.h_offset = y self.h_offset = y
def play_sound(self, sound_file): def play_sound(self, sound_file):
print(sound_file)
sound_file = os.path.join("sound", sound_file)
rw = sdl2.SDL_RWFromFile(byteify(sound_file, "utf-8"), b"rb")
if not rw:
raise RuntimeError("Failed to open sound file")
_buf = POINTER(sdl2.Uint8)()
_length = sdl2.Uint32()
spec = SDL_AudioSpec(freq=22050, aformat=sdl2.AUDIO_U8, channels=1, samples=2048)
if sdl2.SDL_LoadWAV_RW(rw, 1, byref(spec), byref(_buf), byref(_length)) == None:
raise RuntimeError("Failed to load WAV")
devid = None
while not devid:
id = random.randint(0, 4)
for idx, dev in enumerate(self.audio_devs):
if dev[0]:
devid = dev[1]
sdl2.SDL_ClearQueuedAudio(devid)
self.audio_devs[id] = (False, devid)
break
if not devid:
devid = self.audio_devs[id][1]
sdl2.SDL_ClearQueuedAudio(devid)
self.audio_devs[random.randint(0, 4)] = (True, devid)
# Start playing audio
sdl2.SDL_QueueAudio(devid, _buf, _length)
sdl2.SDL_PauseAudioDevice(devid, 0)
return def stop_sound(self):
sample = sdl2.sdlmixer.Mix_LoadWAV(byteify(sound_file, "utf-8")) for dev in self.audio_devs:
if sample is None: if not dev[0]:
raise RuntimeError("Cannot open audio file: {}".format(sdl2.sdlmixer.Mix_GetError())) sdl2.SDL_PauseAudioDevice(dev[1], 1)
channel = sdl2.sdlmixer.Mix_PlayChannel(-1, sample, 0) sdl2.SDL_ClearQueuedAudio(dev[1])
if channel == -1: dev[0] = True
print(f"Cannot play sound: {sdl2.sdlmixer.Mix_GetError()}")

28535
get-pip.py

File diff suppressed because it is too large Load Diff

7
get-venv.py

@ -0,0 +1,7 @@
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.27.0</center>
</body>
</html>

116
imgui-test.py

@ -0,0 +1,116 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from imgui.integrations.sdl2 import SDL2Renderer
from sdl2 import *
import OpenGL.GL as gl
import ctypes
import imgui
import sys
def main():
window, gl_context = impl_pysdl2_init()
imgui.create_context()
impl = SDL2Renderer(window)
show_custom_window = True
running = True
event = SDL_Event()
while running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
running = False
break
impl.process_event(event)
impl.process_inputs()
imgui.new_frame()
#show_test_window()
#imgui.show_test_window()
if show_custom_window:
is_expand, show_custom_window = imgui.begin("Custom window", True)
if is_expand:
imgui.text("Bars")
imgui.text_colored("Eggs", 0.2, 1.0, 0.0)
imgui.end()
gl.glClearColor(1.0, 1.0, 1.0, 1)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
imgui.render()
impl.render(imgui.get_draw_data())
SDL_GL_SwapWindow(window)
impl.shutdown()
SDL_GL_DeleteContext(gl_context)
SDL_DestroyWindow(window)
SDL_Quit()
def impl_pysdl2_init():
width, height = 640, 480
window_name = "minimal ImGui/SDL2 example"
if SDL_Init(SDL_INIT_EVERYTHING) < 0:
print(
"Error: SDL could not initialize! SDL Error: "
+ SDL_GetError().decode("utf-8")
)
sys.exit(1)
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8)
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1)
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE)
SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, b"1")
SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, b"1")
window = SDL_CreateWindow(
window_name.encode("utf-8"),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE,
)
if window is None:
print(
"Error: Window could not be created! SDL Error: "
+ SDL_GetError().decode("utf-8")
)
sys.exit(1)
gl_context = SDL_GL_CreateContext(window)
if gl_context is None:
print(
"Error: Cannot create OpenGL Context! SDL Error: "
+ SDL_GetError().decode("utf-8")
)
sys.exit(1)
SDL_GL_MakeCurrent(window, gl_context)
if SDL_GL_SetSwapInterval(1) < 0:
print(
"Warning: Unable to set VSync! SDL Error: " + SDL_GetError().decode("utf-8")
)
sys.exit(1)
return window, gl_context
if __name__ == "__main__":
main()

25
imgui.ini

@ -0,0 +1,25 @@
[Window][Debug##Default]
Pos=60,60
Size=400,400
Collapsed=0
[Window][Custom window]
Pos=297,261
Size=107,117
Collapsed=0
[Window][Dear ImGui Demo]
Pos=650,20
Size=550,680
Collapsed=0
[Window][Your first window!]
Pos=60,60
Size=100,48
Collapsed=0
[Window][ImGui Demo]
Pos=236,96
Size=550,680
Collapsed=0

53
opengl.test.py

@ -0,0 +1,53 @@
import ctypes
import os
import sdl2
import imgui
from imgui.integrations.sdl2 import SDL2Renderer
import sdl2.ext
def main():
# Initialize SDL2
sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
# Set OpenGL ES version
sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 2)
sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 0)
sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_ES)
# Create an SDL window
window = sdl2.SDL_CreateWindow(b"SDL2 OpenGL ES2",
sdl2.SDL_WINDOWPOS_UNDEFINED,
sdl2.SDL_WINDOWPOS_UNDEFINED,
640, 480,
sdl2.SDL_WINDOW_OPENGL | sdl2.SDL_WINDOW_SHOWN)
# Create an OpenGL context
gl_context = sdl2.SDL_GL_CreateContext(window)
# Main loop
running = True
event = sdl2.SDL_Event()
# Create an SDL2 renderer for ImGui
imgui.set_current_context(imgui.create_context())
renderer = SDL2Renderer(window)
while running:
while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == sdl2.SDL_QUIT:
running = False
is_expand, show_custom_window = imgui.begin("Custom window", True)
if is_expand:
imgui.text("Bars")
imgui.text_colored("Eggs", 0.2, 1.0, 0.0)
imgui.end()
imgui.render()
renderer.render(imgui.get_draw_data())
sdl2.SDL_GL_SwapWindow(window)
# Cleanup
sdl2.SDL_GL_DeleteContext(gl_context)
sdl2.SDL_DestroyWindow(window)
sdl2.SDL_Quit()
if __name__ == "__main__":
main()

4
rats.py

@ -134,12 +134,16 @@ class MiceMaze(controls.KeyBindings):
self.engine.scroll_view(self.pointer) self.engine.scroll_view(self.pointer)
def play_sound(self, sound_file,tag="main"): def play_sound(self, sound_file,tag="main"):
self.engine.play_sound(sound_file)
return
if self.audio: if self.audio:
if len(self.sounds) > 5: if len(self.sounds) > 5:
self.sounds.pop(next(iter(self.sounds))).kill() self.sounds.pop(next(iter(self.sounds))).kill()
self.sounds[f"{tag}_{random.random()}"] = subprocess.Popen(["aplay", f"sound/{sound_file}"]) self.sounds[f"{tag}_{random.random()}"] = subprocess.Popen(["aplay", f"sound/{sound_file}"])
def stop_sound(self, tag=None): def stop_sound(self, tag=None):
self.engine.stop_sound()
return
for key, value in self.sounds.copy().items(): for key, value in self.sounds.copy().items():
if tag is None or tag in key: if tag is None or tag in key:
value.kill() value.kill()

4
requirements.txt

@ -1 +1,3 @@
pysdl2 pysdl2
Pillow
imgui[sdl2]

3436
testwindow.py

File diff suppressed because it is too large Load Diff

15
wgdzh

@ -0,0 +1,15 @@
<game>
<path>./dRally.sh</path>
<name>Death Rally</name>
<desc>Death Rally is a strategic top-down racing game where players start with a modest budget and car, competing across 19 tracks in races against increasingly challenging opponents to earn money for upgrades. With choices of six car models and enhancements in engi>
In addition to race earnings, players can score bonuses for achievements like wiping out all competition, completing races unscathed, or fulfilling sponsor missions. Bonuses vary based on the chosen car, with the ultimate goal being to top the championship table and defeat the Adve>
<image>./drally/cover.png</image>
<releasedate>19960101T000000</releasedate>
<developer>Remedy Entertainment Ltd.</developer>
<publisher>Apogee Software</publisher>
<genre>Simulation-Race 3rd Pers. view-Race, Driving</genre>
<players>1-4</players>
<playcount>1</playcount>
<lastplayed>20240915T212155</lastplayed>
</game>
Loading…
Cancel
Save