Browse Source

Modifica il sistema di rendering SDL e migliora la gestione delle unità nel gioco

master
Matteo Benedetto 1 year ago
parent
commit
3ccffdca7d
  1. 6
      engine/sdl2.py
  2. 20
      rats.py
  3. 50
      sdl2-tk-demo.py
  4. BIN
      units/__pycache__/rat.cpython-313.pyc
  5. 23
      units/rat.py

6
engine/sdl2.py

@ -12,10 +12,10 @@ class GameWindow:
self.width = width * cell_size
self.height = height * cell_size
self.delay = 50
sdl2.ext.init()
sdl2.ext.init(sdl2.SDL_INIT_VIDEO)
self.window = sdl2.ext.Window(title=title, size=(self.width, self.height))
self.window.show()
self.renderer = sdl2.ext.Renderer(self.window, flags=sdl2.SDL_RENDERER_ACCELERATED)
self.renderer = sdl2.ext.Renderer(self.window, flags=sdl2.SDL_RENDERER_PRESENTVSYNC)
self.factory = sdl2.ext.SpriteFactory(renderer=self.renderer)
self.fonts = self.generate_fonts("assets/AmaticSC-Regular.ttf")
self.running = True
@ -84,4 +84,4 @@ class GameWindow:
self.running = False
# Disegna qui gli sprite
self.renderer.present()
time.sleep(self.delay / 1000)
#time.sleep(self.delay / 1000)

20
rats.py

@ -1,3 +1,5 @@
import cProfile
import pstats
import random
from units import rat
import uuid
@ -7,11 +9,13 @@ from engine import maze, sdl2 as engine
class MiceMaze:
def __init__(self, maze_file):
self.map = maze.Map(maze_file)
self.audio = True
self.audio = False
self.cell_size = 60
self.engine = engine.GameWindow(self.map.width, self.map.height, self.cell_size, "Mice!", key_callback=self.key_pressed)
self.graphics_load()
self.units = {}
self.unit_positions = {}
self.unit_positions_before = {}
for _ in range(5):
self.new_rat()
@ -40,6 +44,11 @@ class MiceMaze:
def update_maze(self):
self.engine.delete_tag("unit")
self.unit_positions.clear()
self.unit_positions_before.clear()
for unit in self.units.values():
self.unit_positions.setdefault(unit.position, []).append(unit)
self.unit_positions_before.setdefault(unit.position_before, []).append(unit)
for unit in self.units.copy().values():
unit.move()
unit.collisions()
@ -62,6 +71,10 @@ class MiceMaze:
self.units[random.choice(list(self.units.keys()))].die()
elif event.keysym == "m":
self.audio = not self.audio
elif event.keysym == "s":
profiler.disable()
stats = pstats.Stats(profiler).sort_stats('cumtime')
stats.print_stats()
def play_sound(self, sound_file):
if self.audio:
@ -75,5 +88,10 @@ class MiceMaze:
self.rat_assets[sex] = {}
for direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
self.rat_assets[sex][direction] = self.engine.load_image(f"Rat/BMP_{sex}_{direction}.png", transparent_color=(128, 128, 128))
if __name__ == "__main__":
profiler = cProfile.Profile()
profiler.enable()
solver = MiceMaze('maze.json')
solver.run()

50
sdl2-tk-demo.py

@ -0,0 +1,50 @@
from sdl2 import *
import tkinter as tk
from tkinter import *
import random, ctypes
def draw():
global renderer
x1 = ctypes.c_int(random.randrange(0, 600))
y1 = ctypes.c_int(random.randrange(0, 500))
x2 = ctypes.c_int(random.randrange(0, 600))
y2 = ctypes.c_int(random.randrange(0, 500))
r = ctypes.c_ubyte(random.randrange(0, 255))
g = ctypes.c_ubyte(random.randrange(0, 255))
b = ctypes.c_ubyte(random.randrange(0, 255))
SDL_SetRenderDrawColor(renderer, r, g, b, ctypes.c_ubyte(255))
SDL_RenderDrawLine(renderer, x1, y1, x2, y2)
def sdl_update():
global window, event, renderer
SDL_RenderPresent(renderer);
if SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
SDL_DestroyRenderer(renderer)
SDL_DestroyWindow(window)
SDL_Quit()
# tkinter stuff #
root = tk.Tk()
embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
embed.grid(columnspan = (600), rowspan = 500) # Adds grid
embed.pack(side = LEFT) #packs window to the left
buttonwin = tk.Frame(root, width = 75, height = 500)
buttonwin.pack(side = LEFT)
button1 = Button(buttonwin,text = 'Draw', command=draw)
button1.pack(side=LEFT)
root.update()
#################################
# SDL window stuff #
SDL_Init(SDL_INIT_VIDEO)
window = SDL_CreateWindowFrom(embed.winfo_id())
renderer = SDL_CreateRenderer(window, -1, 0)
SDL_SetRenderDrawColor(renderer, ctypes.c_ubyte(255), ctypes.c_ubyte(255),
ctypes.c_ubyte(255), ctypes.c_ubyte(255))
SDL_RenderClear(renderer)
event = SDL_Event()
draw()
while True:
sdl_update()
root.update()

BIN
units/__pycache__/rat.cpython-313.pyc

Binary file not shown.

23
units/rat.py

@ -1,7 +1,6 @@
from .unit import Unit
import random
import uuid
from engine.tkinter import GameWindow
# Costanti
AGE_THRESHOLD = 200
@ -55,16 +54,14 @@ class Rat(Unit):
self.age += 1
if self.age == AGE_THRESHOLD:
self.speed *= SPEED_REDUCTION
if hasattr(self, "pregnant"):
if self.pregnant:
if getattr(self, "pregnant", False):
self.procreate()
if self.stop:
self.stop -= 1
return
if self.partial_move < 1:
self.partial_move += self.speed
self.partial_move = round(self.partial_move, 2)
if self.partial_move == 1:
self.partial_move = round(self.partial_move + self.speed, 2)
if self.partial_move >= 1:
self.partial_move = 0
self.position = self.find_next_position()
self.direction = self.calculate_rat_direction()
@ -72,21 +69,23 @@ class Rat(Unit):
def collisions(self):
if self.age < AGE_THRESHOLD:
return
units = self.game.units.copy().values()
units = []
units.extend(self.game.unit_positions.get(self.position, []))
units.extend(self.game.unit_positions.get(self.position_before, []))
units.extend(self.game.unit_positions_before.get(self.position, []))
units.extend(self.game.unit_positions_before.get(self.position_before, []))
for unit in units:
if unit.id == self.id:
continue
if unit.age < AGE_THRESHOLD:
if unit.id == self.id or unit.age < AGE_THRESHOLD:
continue
x1, y1, x2, y2 = self.bbox
ox1, oy1, ox2, oy2 = unit.bbox
# Verifica se c'è collisione con una tolleranza di sovrapposizione
if not (x1 < ox2 - OVERLAP_TOLERANCE and
if (x1 < ox2 - OVERLAP_TOLERANCE and
x2 > ox1 + OVERLAP_TOLERANCE and
y1 < oy2 - OVERLAP_TOLERANCE and
y2 > oy1 + OVERLAP_TOLERANCE):
continue
if self.id in self.game.units and unit.id in self.game.units:
if self.sex == unit.sex and self.fight:
self.die(unit)

Loading…
Cancel
Save