From 2b4523d6446716eef5f36e4b3728556db8f69f80 Mon Sep 17 00:00:00 2001 From: Sergio Date: Sun, 19 Oct 2025 22:01:31 +0200 Subject: [PATCH] linter --- TODO.md | 61 --- linux_utils/iwyu_tool.py | 553 ++++++++++++++++++++++++++++ linux_utils/run_clang-tidy.sh | 2 + linux_utils/run_iwyu.sh | 4 +- source/animated_sprite.cpp | 31 +- source/animated_sprite.hpp | 17 +- source/asset.cpp | 39 +- source/asset_integrated.hpp | 10 +- source/audio.cpp | 4 +- source/audio.hpp | 12 +- source/background.cpp | 29 +- source/background.hpp | 6 +- source/balloon.cpp | 50 +-- source/balloon.hpp | 22 +- source/balloon_formations.cpp | 8 +- source/balloon_formations.hpp | 22 +- source/balloon_manager.cpp | 16 +- source/balloon_manager.hpp | 33 +- source/bullet.cpp | 17 +- source/bullet.hpp | 8 +- source/bullet_manager.cpp | 32 +- source/bullet_manager.hpp | 16 +- source/color.cpp | 8 +- source/color.hpp | 8 +- source/define_buttons.cpp | 10 +- source/define_buttons.hpp | 4 +- source/demo.cpp | 2 +- source/director.cpp | 52 +-- source/enter_name.cpp | 3 +- source/explosions.cpp | 6 +- source/explosions.hpp | 4 +- source/fade.cpp | 10 +- source/game_logo.cpp | 81 ++-- source/game_logo.hpp | 44 +-- source/global_inputs.cpp | 6 +- source/input.cpp | 11 +- source/input.hpp | 11 +- source/input_types.cpp | 2 + source/item.cpp | 40 +- source/item.hpp | 16 +- source/manage_hiscore_table.cpp | 15 +- source/moving_sprite.cpp | 20 +- source/moving_sprite.hpp | 17 +- source/options.cpp | 23 +- source/options.hpp | 19 +- source/param.cpp | 43 +-- source/path_sprite.cpp | 31 +- source/path_sprite.hpp | 8 +- source/player.cpp | 196 +++++----- source/player.hpp | 150 ++++---- source/rendering/shader_backend.hpp | 6 +- source/resource.cpp | 48 +-- source/resource_helper.cpp | 30 +- source/resource_helper.hpp | 22 +- source/resource_loader.cpp | 103 +++--- source/resource_loader.hpp | 39 +- source/resource_pack.cpp | 159 ++++---- source/resource_pack.hpp | 35 +- source/scoreboard.cpp | 118 +++--- source/scoreboard.hpp | 10 +- source/screen.cpp | 35 +- source/screen.hpp | 24 +- source/sections/credits.cpp | 93 ++--- source/sections/credits.hpp | 47 ++- source/sections/game.cpp | 293 +++++++-------- source/sections/game.hpp | 117 +++--- source/sections/hiscore_table.cpp | 26 +- source/sections/hiscore_table.hpp | 25 +- source/sections/instructions.cpp | 26 +- source/sections/instructions.hpp | 19 +- source/sections/intro.cpp | 49 ++- source/sections/intro.hpp | 40 +- source/sections/logo.cpp | 28 +- source/sections/logo.hpp | 24 +- source/sections/title.cpp | 78 ++-- source/sections/title.hpp | 44 +-- source/service_menu.cpp | 0 source/service_menu.hpp | 0 source/shutdown.cpp | 14 +- source/smart_sprite.cpp | 12 +- source/smart_sprite.hpp | 12 +- source/stage.cpp | 9 +- source/stage.hpp | 5 +- source/system_utils.cpp | 11 +- source/tabe.cpp | 35 +- source/tabe.hpp | 20 +- source/text.cpp | 13 +- source/texture.cpp | 2 +- source/tiled_bg.cpp | 21 +- source/tiled_bg.hpp | 6 +- source/ui/logger.hpp | 6 +- source/ui/menu_option.cpp | 4 +- source/ui/notifier.cpp | 12 +- source/ui/notifier.hpp | 6 +- source/ui/service_menu.hpp | 7 +- source/ui/ui_message.cpp | 11 +- source/ui/ui_message.hpp | 2 +- source/utils.cpp | 14 +- source/utils.hpp | 4 +- source/writer.cpp | 18 +- source/writer.hpp | 8 +- 101 files changed, 2058 insertions(+), 1564 deletions(-) delete mode 100644 TODO.md create mode 100755 linux_utils/iwyu_tool.py delete mode 100644 source/service_menu.cpp delete mode 100644 source/service_menu.hpp diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 48c408a..0000000 --- a/TODO.md +++ /dev/null @@ -1,61 +0,0 @@ -# TODO - -## Tareas pendientes - -- [ ] Revisar todas las variables static de los métodos para ver si se resetean correctamente - -## Mejoras arquitecturales (refactoring) - -### Eliminar variables static locales y usar patrones profesionales: - -**Opción 1: Máquina de Estados** -```cpp -class GameCompletedState { - bool start_celebrations_done = false; - bool end_celebrations_done = false; - float timer = 0.0f; - -public: - void reset() { - start_celebrations_done = false; - end_celebrations_done = false; - timer = 0.0f; - } - - void update(float deltaTime) { - timer += deltaTime; - // lógica aquí - } -}; -``` - -**Opción 2: Sistema de Eventos/Callbacks** -```cpp -// Al entrar en COMPLETED state -eventSystem.scheduleEvent(6.0f, []{ startCelebrations(); }); -eventSystem.scheduleEvent(14.0f, []{ endCelebrations(); }); -``` - -**Opción 3: Flags como miembros privados** -```cpp -class Game { -private: - struct GameOverState { - bool game_over_triggered = false; - bool start_celebrations_triggered = false; - bool end_celebrations_triggered = false; - - void reset() { - game_over_triggered = false; - start_celebrations_triggered = false; - end_celebrations_triggered = false; - } - } game_over_state_; -}; -``` - -**Ventajas:** -- Más fáciles de testear -- Más fáciles de debugear -- Más fáciles de entender y mantener -- No tienen "estado oculto" \ No newline at end of file diff --git a/linux_utils/iwyu_tool.py b/linux_utils/iwyu_tool.py new file mode 100755 index 0000000..8aa4c7b --- /dev/null +++ b/linux_utils/iwyu_tool.py @@ -0,0 +1,553 @@ +#!/usr/bin/env python3 + +##===--- iwyu_tool.py -----------------------------------------------------===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +""" Driver to consume a Clang compilation database and invoke IWYU. + +Example usage with CMake: + + # Unix systems + $ mkdir build && cd build + $ CC="clang" CXX="clang++" cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ... + $ iwyu_tool.py -p . + + # Windows systems + $ mkdir build && cd build + $ cmake -DCMAKE_CXX_COMPILER="%VCINSTALLDIR%/bin/cl.exe" \ + -DCMAKE_C_COMPILER="%VCINSTALLDIR%/VC/bin/cl.exe" \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ + -G Ninja ... + $ python3 iwyu_tool.py -p . + +See iwyu_tool.py -h for more details on command-line arguments. +""" +from __future__ import print_function +import os +import re +import sys +import json +import time +import shlex +import shutil +import argparse +import tempfile +import subprocess + + +CORRECT_RE = re.compile(r'^\((.*?) has correct #includes/fwd-decls\)$') +SHOULD_ADD_RE = re.compile(r'^(.*?) should add these lines:$') +ADD_RE = re.compile('^(.*?) +// (.*)$') +SHOULD_REMOVE_RE = re.compile(r'^(.*?) should remove these lines:$') +FULL_LIST_RE = re.compile(r'The full include-list for (.*?):$') +END_RE = re.compile(r'^---$') +LINES_RE = re.compile(r'^- (.*?) // lines ([0-9]+)-[0-9]+$') + + +GENERAL, ADD, REMOVE, LIST = range(4) + + +def clang_formatter(output, style): + """ Process iwyu's output into something clang-like. """ + formatted = [] + + state = (GENERAL, None) + for line in output.splitlines(): + match = CORRECT_RE.match(line) + if match: + # See PR#1806 for more info + continue + match = SHOULD_ADD_RE.match(line) + if match: + state = (ADD, match.group(1)) + continue + match = SHOULD_REMOVE_RE.match(line) + if match: + state = (REMOVE, match.group(1)) + continue + match = FULL_LIST_RE.match(line) + if match: + state = (LIST, match.group(1)) + elif END_RE.match(line): + state = (GENERAL, None) + elif not line.strip(): + continue + elif state[0] == GENERAL: + formatted.append(line) + elif state[0] == ADD: + match = ADD_RE.match(line) + if match: + formatted.append("%s:1:1: %s: add '%s' (%s)" % + (state[1], + style, + match.group(1), + match.group(2))) + else: + formatted.append("%s:1:1: %s: add '%s'" % + (state[1], style, line)) + elif state[0] == REMOVE: + match = LINES_RE.match(line) + line_no = match.group(2) if match else '1' + formatted.append("%s:%s:1: %s: superfluous '%s'" % + (state[1], line_no, style, match.group(1))) + + return os.linesep.join(formatted) + + +DEFAULT_FORMAT = 'iwyu' +FORMATTERS = { + 'iwyu': lambda output: output, + 'clang': lambda output: clang_formatter(output, style="error"), + 'clang-warning': lambda output: clang_formatter(output, style="warning"), +} + + +if sys.platform.startswith('win'): + # Case-insensitive match on Windows + def normcase(s): + return s.lower() +else: + def normcase(s): + return s + + +def is_subpath_of(path, parent): + """ Return True if path is equal to or fully contained within parent. + + Assumes both paths are canonicalized with os.path.realpath. + """ + parent = normcase(parent) + path = normcase(path) + + if path == parent: + return True + + if not path.startswith(parent): + return False + + # Now we know parent is a prefix of path, but they only share lineage if the + # difference between them starts with a path separator, e.g. /a/b/c/file + # is not a parent of /a/b/c/file.cpp, but /a/b/c and /a/b/c/ are. + parent = parent.rstrip(os.path.sep) + suffix = path[len(parent):] + return suffix.startswith(os.path.sep) + + +def is_msvc_driver(compile_command): + """ Return True if compile_command matches an MSVC CL-style driver. """ + compile_command = normcase(compile_command) + + if compile_command.endswith('cl.exe'): + # Native MSVC compiler or clang-cl.exe + return True + + if compile_command.endswith('clang-cl'): + # Cross clang-cl on non-Windows + return True + + return False + + +def win_split(cmdline): + """ Minimal implementation of shlex.split for Windows following + https://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft.aspx. + """ + def split_iter(cmdline): + in_quotes = False + backslashes = 0 + arg = '' + for c in cmdline: + if c == '\\': + # MSDN: Backslashes are interpreted literally, unless they + # immediately precede a double quotation mark. + # Buffer them until we know what comes next. + backslashes += 1 + elif c == '"': + # Quotes can either be an escaped quote or the start of a quoted + # string. Paraphrasing MSDN: + # Before quotes, place one backslash in the arg for every pair + # of leading backslashes. If the number of backslashes is odd, + # retain the double quotation mark, otherwise interpret it as a + # string delimiter and switch state. + arg += '\\' * (backslashes // 2) + if backslashes % 2 == 1: + arg += c + else: + in_quotes = not in_quotes + backslashes = 0 + elif c in (' ', '\t') and not in_quotes: + # MSDN: Arguments are delimited by white space, which is either + # a space or a tab [but only outside of a string]. + # Flush any buffered backslashes and yield arg, unless empty. + arg += '\\' * backslashes + if arg: + yield arg + arg = '' + backslashes = 0 + else: + # Flush buffered backslashes and append. + arg += '\\' * backslashes + arg += c + backslashes = 0 + + if arg: + arg += '\\' * backslashes + yield arg + + return list(split_iter(cmdline)) + + +def split_command(cmdstr): + """ Split a command string into a list, respecting shell quoting. """ + if sys.platform.startswith('win'): + # shlex.split does not work for Windows command-lines, so special-case + # to our own implementation. + cmd = win_split(cmdstr) + else: + cmd = shlex.split(cmdstr) + + return cmd + + +def find_include_what_you_use(): + """ Find IWYU executable and return its full pathname. """ + env_iwyu_path = os.environ.get('IWYU_BINARY') + if env_iwyu_path: + return os.path.realpath(env_iwyu_path) + + # Search in same dir as this script. + iwyu_path = shutil.which('include-what-you-use', + path=os.path.dirname(__file__)) + if iwyu_path: + return os.path.realpath(iwyu_path) + + # Search the system PATH. + iwyu_path = shutil.which('include-what-you-use') + if iwyu_path: + return os.path.realpath(iwyu_path) + + return None + + +IWYU_EXECUTABLE = find_include_what_you_use() + + +class Process(object): + """ Manages an IWYU process in flight """ + def __init__(self, proc, outfile): + self.proc = proc + self.outfile = outfile + self.output = None + + def poll(self): + """ Return the exit code if the process has completed, None otherwise. + """ + return self.proc.poll() + + @property + def returncode(self): + return self.proc.returncode + + def get_output(self): + """ Return stdout+stderr output of the process. + + This call blocks until the process is complete, then returns the output. + """ + if not self.output: + self.proc.wait() + self.outfile.seek(0) + self.output = self.outfile.read().decode("utf-8") + self.outfile.close() + + return self.output + + @classmethod + def start(cls, invocation): + """ Start a Process for the invocation and capture stdout+stderr. """ + outfile = tempfile.TemporaryFile(prefix='iwyu') + process = subprocess.Popen( + invocation.command, + cwd=invocation.cwd, + stdout=outfile, + stderr=subprocess.STDOUT) + return cls(process, outfile) + + +KNOWN_COMPILER_WRAPPERS=frozenset([ + "ccache" +]) + + +class Invocation(object): + """ Holds arguments of an IWYU invocation. """ + def __init__(self, command, cwd): + self.command = command + self.cwd = cwd + + def __str__(self): + return ' '.join(self.command) + + @classmethod + def from_compile_command(cls, entry, extra_args): + """ Parse a JSON compilation database entry into new Invocation. """ + if 'arguments' in entry: + # arguments is a command-line in list form. + command = entry['arguments'] + elif 'command' in entry: + # command is a command-line in string form, split to list. + command = split_command(entry['command']) + else: + raise ValueError('Invalid compilation database entry: %s' % entry) + + if command[0] in KNOWN_COMPILER_WRAPPERS: + # Remove the compiler wrapper from the command. + command = command[1:] + + # Rewrite the compile command for IWYU + compile_command, compile_args = command[0], command[1:] + if is_msvc_driver(compile_command): + # If the compiler is cl-compatible, let IWYU be cl-compatible. + extra_args = ['--driver-mode=cl'] + extra_args + + command = [IWYU_EXECUTABLE] + extra_args + compile_args + return cls(command, entry['directory']) + + def start(self, verbose): + """ Run invocation and collect output. """ + if verbose: + print('# %s' % self, file=sys.stderr) + + return Process.start(self) + + +def fixup_compilation_db(compilation_db): + """ Canonicalize paths in JSON compilation database. """ + for entry in compilation_db: + # Convert relative paths to absolute ones if possible, based on the entry's directory. + if 'directory' in entry and not os.path.isabs(entry['file']): + entry['file'] = os.path.join(entry['directory'], entry['file']) + + # Expand relative paths and symlinks + entry['file'] = os.path.realpath(entry['file']) + + return compilation_db + + +def select_compilation_db(compilation_db, selection): + """ Return a new compilation database reduced to the paths in selection. """ + if not selection: + return compilation_db + + # Canonicalize selection paths to match compilation database. + selection = [os.path.realpath(p) for p in selection] + + new_db = [] + for path in selection: + if not os.path.exists(path): + print('warning: \'%s\' not found on disk.' % path, file=sys.stderr) + continue + + found = [e for e in compilation_db if is_subpath_of(e['file'], path)] + if not found: + print('warning: \'%s\' not found in compilation database.' % path, + file=sys.stderr) + continue + + new_db.extend(found) + + return new_db + +def slice_compilation_db(compilation_db, selection, exclude): + """ Return a new compilation database with filtered entries. """ + + new_db = select_compilation_db(compilation_db, selection) + + # Canonicalize selection paths to match compilation database. + exclude = [os.path.realpath(p) for p in exclude] + + for path in exclude: + if not os.path.exists(path): + print('warning: excluded path \'%s\' not found on disk.' % path, + file=sys.stderr) + continue + + new_db = [e for e in new_db if not is_subpath_of(e['file'], path)] + + return new_db + + +def worst_exit_code(worst, cur): + """Return the most extreme exit code of two. + + Negative exit codes occur if the program exits due to a signal (Unix) or + structured exception (Windows). If we've seen a negative one before, keep + it, as it usually indicates a critical error. + + Otherwise return the biggest positive exit code. + """ + if cur < 0: + # Negative results take precedence, return the minimum + return min(worst, cur) + elif worst < 0: + # We know cur is non-negative, negative worst must be minimum + return worst + else: + # We know neither are negative, return the maximum + return max(worst, cur) + + +def execute(invocations, verbose, formatter, jobs, max_load_average=0): + """ Launch processes described by invocations. """ + exit_code = 0 + if jobs == 1: + for invocation in invocations: + proc = invocation.start(verbose) + print(formatter(proc.get_output())) + exit_code = worst_exit_code(exit_code, proc.returncode) + return exit_code + + pending = [] + while invocations or pending: + # Collect completed IWYU processes and print results. + complete = [proc for proc in pending if proc.poll() is not None] + for proc in complete: + pending.remove(proc) + print(formatter(proc.get_output())) + exit_code = worst_exit_code(exit_code, proc.returncode) + + # Schedule new processes if there's room. + capacity = jobs - len(pending) + + if max_load_average > 0: + one_min_load_average, _, _ = os.getloadavg() + load_capacity = max_load_average - one_min_load_average + if load_capacity < 0: + load_capacity = 0 + if load_capacity < capacity: + capacity = int(load_capacity) + if not capacity and not pending: + # Ensure there is at least one job running. + capacity = 1 + + pending.extend(i.start(verbose) for i in invocations[:capacity]) + invocations = invocations[capacity:] + + # Yield CPU. + time.sleep(0.0001) + return exit_code + + +def main(compilation_db_path, source_files, exclude, verbose, formatter, jobs, + max_load_average, extra_args): + """ Entry point. """ + + if not IWYU_EXECUTABLE: + print('error: include-what-you-use executable not found', + file=sys.stderr) + return 1 + + try: + if os.path.isdir(compilation_db_path): + compilation_db_path = os.path.join(compilation_db_path, + 'compile_commands.json') + + # Read compilation db from disk. + compilation_db_path = os.path.realpath(compilation_db_path) + with open(compilation_db_path, 'r') as fileobj: + compilation_db = json.load(fileobj) + except IOError as why: + print('error: failed to parse compilation database: %s' % why, + file=sys.stderr) + return 1 + + compilation_db = fixup_compilation_db(compilation_db) + compilation_db = slice_compilation_db(compilation_db, source_files, exclude) + + # Transform compilation db entries into a list of IWYU invocations. + invocations = [ + Invocation.from_compile_command(e, extra_args) for e in compilation_db + ] + + return execute(invocations, verbose, formatter, jobs, max_load_average) + + +def _bootstrap(sys_argv): + """ Parse arguments and dispatch to main(). """ + + # This hackery is necessary to add the forwarded IWYU args to the + # usage and help strings. + def customize_usage(parser): + """ Rewrite the parser's format_usage. """ + original_format_usage = parser.format_usage + parser.format_usage = lambda: original_format_usage().rstrip() + \ + ' -- []' + os.linesep + + def customize_help(parser): + """ Rewrite the parser's format_help. """ + original_format_help = parser.format_help + + def custom_help(): + """ Customized help string, calls the adjusted format_usage. """ + helpmsg = original_format_help() + helplines = helpmsg.splitlines() + helplines[0] = parser.format_usage().rstrip() + return os.linesep.join(helplines) + os.linesep + + parser.format_help = custom_help + + # Parse arguments. + parser = argparse.ArgumentParser( + description='Include-what-you-use compilation database driver.', + epilog='Assumes include-what-you-use is available on the PATH.') + customize_usage(parser) + customize_help(parser) + + parser.add_argument('-v', '--verbose', action='store_true', + help='Print IWYU commands') + parser.add_argument('-o', '--output-format', type=str, + choices=FORMATTERS.keys(), default=DEFAULT_FORMAT, + help='Output format (default: %s)' % DEFAULT_FORMAT) + parser.add_argument('-j', '--jobs', type=int, default=1, + nargs='?', const=0, + help=('Number of concurrent subprocesses. If zero, ' + 'will try to match the logical cores of the ' + 'system.')) + parser.add_argument('-l', '--load', type=float, default=0, + help=('Do not start new jobs if the 1min load average ' + 'is greater than the provided value')) + parser.add_argument('-p', metavar='', required=True, + help='Compilation database path', dest='dbpath') + parser.add_argument('-e', '--exclude', action='append', default=[], + help=('Do not run IWYU on source files (or directories) ' + 'below this path.')) + parser.add_argument('source', nargs='*', + help=('Zero or more source files (or directories) to ' + 'run IWYU on. Defaults to all in compilation ' + 'database.')) + + def partition_args(argv): + """ Split around '--' into driver args and IWYU args. """ + try: + double_dash = argv.index('--') + return argv[:double_dash], argv[double_dash+1:] + except ValueError: + return argv, [] + argv, extra_args = partition_args(sys_argv[1:]) + args = parser.parse_args(argv) + + jobs = args.jobs + if jobs == 0: + jobs = os.cpu_count() or 1 + + return main(args.dbpath, args.source, args.exclude, args.verbose, + FORMATTERS[args.output_format], jobs, args.load, extra_args) + + +if __name__ == '__main__': + sys.exit(_bootstrap(sys.argv)) diff --git a/linux_utils/run_clang-tidy.sh b/linux_utils/run_clang-tidy.sh index 25d4dac..7ec390a 100755 --- a/linux_utils/run_clang-tidy.sh +++ b/linux_utils/run_clang-tidy.sh @@ -6,6 +6,8 @@ # Lista de rutas donde ejecutar clang-tidy PATHS=( "/home/sergio/gitea/coffee_crisis_arcade_edition/source" + "/home/sergio/gitea/coffee_crisis_arcade_edition/source/rendering" + "/home/sergio/gitea/coffee_crisis_arcade_edition/source/rendering/opengl" "/home/sergio/gitea/coffee_crisis_arcade_edition/source/sections" "/home/sergio/gitea/coffee_crisis_arcade_edition/source/ui" ) diff --git a/linux_utils/run_iwyu.sh b/linux_utils/run_iwyu.sh index 5c01506..aa02e58 100755 --- a/linux_utils/run_iwyu.sh +++ b/linux_utils/run_iwyu.sh @@ -15,8 +15,8 @@ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR" # 🛠️ Ejecutar IWYU con fix_includes.py echo "🚀 Ejecutando IWYU..." -iwyu_tool.py -p "$BUILD_DIR" -- -Xiwyu --mapping_file="$MAPPING_FILE" -Xiwyu --verbose=3 \ -| python3 /usr/bin/fix_includes.py --update_comments --reorder --nosafe_headers +./iwyu_tool.py -p "$BUILD_DIR" -- -Xiwyu --mapping_file="$MAPPING_FILE" -Xiwyu --verbose=3 \ +| fix_include --update_comments --reorder --nosafe_headers # 🧹 Reemplazar // for por // Para en líneas de #include echo "✍️ Corrigiendo comentarios en includes..." diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 2898e83..c86dfb8 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -2,17 +2,16 @@ #include // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError, SDL_FRect -#include // Para min, max +#include // Para min #include // Para size_t -#include // Para basic_istream, basic_ifstream, basic_ios, ifstream, stringstream -#include // Para basic_stringstream +#include // Para basic_istream, basic_ifstream, istream, basic_ios, ifstream, istringstream, stringstream +#include // Para basic_istringstream, basic_stringstream #include // Para runtime_error -#include // Para pair +#include // Para move, pair -#include "resource_helper.hpp" // Para ResourceHelper +#include "resource_helper.hpp" // Para loadFile #include "texture.hpp" // Para Texture -#include "utils.hpp" // Para printWithDots -#include "ui/logger.hpp" +#include "ui/logger.hpp" // Para dots // Carga las animaciones en un vector(Animations) desde un fichero auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer { @@ -88,13 +87,13 @@ auto AnimatedSprite::getAnimationIndex(const std::string& name) -> int { } // Calcula el frame correspondiente a la animación (time-based) -void AnimatedSprite::animate(float deltaTime) { +void AnimatedSprite::animate(float delta_time) { if (animations_[current_animation_].speed == 0 || animations_[current_animation_].paused) { return; } // Acumular tiempo transcurrido - animations_[current_animation_].time_accumulator += deltaTime; + animations_[current_animation_].time_accumulator += delta_time; // Verificar si es momento de cambiar frame if (animations_[current_animation_].time_accumulator >= animations_[current_animation_].speed) { @@ -107,7 +106,7 @@ void AnimatedSprite::animate(float deltaTime) { animations_[current_animation_].current_frame = animations_[current_animation_].frames.size() - 1; animations_[current_animation_].completed = true; } else { // Si hay loop, vuelve al frame indicado - animations_[current_animation_].time_accumulator = 0.0f; + animations_[current_animation_].time_accumulator = 0.0F; animations_[current_animation_].current_frame = animations_[current_animation_].loop; } } @@ -130,7 +129,7 @@ void AnimatedSprite::setCurrentAnimation(const std::string& name, bool reset) { current_animation_ = NEW_ANIMATION; if (reset) { animations_[current_animation_].current_frame = 0; - animations_[current_animation_].time_accumulator = 0.0f; + animations_[current_animation_].time_accumulator = 0.0F; animations_[current_animation_].completed = false; } else { animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size() - 1); @@ -149,7 +148,7 @@ void AnimatedSprite::setCurrentAnimation(int index, bool reset) { current_animation_ = NEW_ANIMATION; if (reset) { animations_[current_animation_].current_frame = 0; - animations_[current_animation_].time_accumulator = 0.0f; + animations_[current_animation_].time_accumulator = 0.0F; animations_[current_animation_].completed = false; } else { animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size()); @@ -161,15 +160,15 @@ void AnimatedSprite::setCurrentAnimation(int index, bool reset) { } // Actualiza las variables del objeto (time-based) -void AnimatedSprite::update(float deltaTime) { - animate(deltaTime); - MovingSprite::update(deltaTime); +void AnimatedSprite::update(float delta_time) { + animate(delta_time); + MovingSprite::update(delta_time); } // Reinicia la animación void AnimatedSprite::resetAnimation() { animations_[current_animation_].current_frame = 0; - animations_[current_animation_].time_accumulator = 0.0f; + animations_[current_animation_].time_accumulator = 0.0F; animations_[current_animation_].completed = false; animations_[current_animation_].paused = false; updateSpriteClip(); diff --git a/source/animated_sprite.hpp b/source/animated_sprite.hpp index 2c44e7d..d26e2a8 100644 --- a/source/animated_sprite.hpp +++ b/source/animated_sprite.hpp @@ -2,15 +2,14 @@ #include // Para SDL_FRect -#include // Para max #include // Para size_t -#include // Para allocator, shared_ptr -#include // Para string, hash +#include // Para shared_ptr +#include // Para basic_string, string, hash #include // Para unordered_map -#include -#include // Para vector +#include // Para move +#include // Para vector -#include "moving_sprite.hpp" // Para MovingSprite +#include "moving_sprite.hpp" // for MovingSprite // Declaración adelantada class Texture; @@ -25,7 +24,7 @@ struct Animation { int loop{0}; // Frame de vuelta al terminar (-1 para no repetir) bool completed{false}; // Indica si la animación ha finalizado size_t current_frame{0}; // Frame actual en reproducción - float time_accumulator{0.0f}; // Acumulador de tiempo para animaciones time-based + float time_accumulator{0.0F}; // Acumulador de tiempo para animaciones time-based bool paused{false}; // La animación no avanza Animation() = default; @@ -55,7 +54,7 @@ class AnimatedSprite : public MovingSprite { ~AnimatedSprite() override = default; // --- Métodos principales --- - void update(float deltaTime) override; // Actualiza la animación (time-based) + void update(float delta_time) override; // Actualiza la animación (time-based) // --- Control de animaciones --- void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre @@ -78,7 +77,7 @@ class AnimatedSprite : public MovingSprite { int current_animation_ = 0; // Índice de la animación activa // --- Métodos internos --- - void animate(float deltaTime); // Calcula el frame correspondiente a la animación (time-based) + void animate(float delta_time); // Calcula el frame correspondiente a la animación (time-based) void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame diff --git a/source/asset.cpp b/source/asset.cpp index 6b6e1fe..228d88b 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -1,17 +1,18 @@ #include "asset.hpp" -#include // Para SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn +#include // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError -#include // Para std::sort +#include // Para sort #include // Para size_t #include // Para exception -#include // Para std::filesystem -#include // Para basic_istream, basic_ifstream, ifstream, istringstream +#include // Para exists, path +#include // Para basic_ifstream, basic_istream, basic_ostream, operator<<, ifstream, istringstream, endl +#include // Para cout #include // Para basic_istringstream #include // Para runtime_error -#include "resource_helper.hpp" // Para ResourceHelper -#include "ui/logger.hpp" // Pâra Logger +#include "resource_helper.hpp" // Para loadFile +#include "ui/logger.hpp" // Para info, section, CYAN #include "utils.hpp" // Para getFileName // Singleton @@ -124,7 +125,7 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string& } } - std::cout << "Loaded " << file_list_.size() << " assets from config file" << std::endl; + std::cout << "Loaded " << file_list_.size() << " assets from config file" << '\n'; file.close(); } @@ -204,20 +205,18 @@ auto Asset::checkFile(const std::string& path) const -> bool { // MODO PACK: Usar ResourceHelper (igual que la carga real) auto data = ResourceHelper::loadFile(path); return !data.empty(); - } else { - // MODO FILESYSTEM: Verificación directa (modo desarrollo) - std::ifstream file(path); - bool success = file.good(); - file.close(); + } // MODO FILESYSTEM: Verificación directa (modo desarrollo) + std::ifstream file(path); + bool success = file.good(); + file.close(); - if (!success) { - SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, - "Error: Could not open file: %s", - path.c_str()); - } - - return success; + if (!success) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, + "Error: Could not open file: %s", + path.c_str()); } + + return success; } // Parsea string a Type @@ -290,7 +289,7 @@ auto Asset::getListByType(Type type) const -> std::vector { } // Ordenar alfabéticamente para garantizar orden consistente - std::sort(list.begin(), list.end()); + std::ranges::sort(list); return list; } diff --git a/source/asset_integrated.hpp b/source/asset_integrated.hpp index 0c92048..1d0260f 100644 --- a/source/asset_integrated.hpp +++ b/source/asset_integrated.hpp @@ -13,17 +13,17 @@ class AssetIntegrated : public Asset { const std::string& resource_pack_path = "resources.pack"); // Carga un archivo usando ResourceLoader como primera opción - std::vector loadFile(const std::string& filename); + auto loadFile(const std::string& filename) -> std::vector; // Verifica si un archivo existe (pack o filesystem) - bool fileExists(const std::string& filename) const; + auto fileExists(const std::string& filename) const -> bool; // Obtiene la ruta completa para archivos del sistema/config - std::string getSystemPath(const std::string& filename) const; + auto getSystemPath(const std::string& filename) const -> std::string; private: - static bool resource_pack_enabled_; + static bool resource_pack_enabled; // Determina si un archivo debe cargarse del pack o del filesystem - bool shouldUseResourcePack(const std::string& filepath) const; + auto shouldUseResourcePack(const std::string& filepath) const -> bool; }; \ No newline at end of file diff --git a/source/audio.cpp b/source/audio.cpp index 6b3536c..e9c9604 100644 --- a/source/audio.cpp +++ b/source/audio.cpp @@ -7,7 +7,7 @@ #include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM... #include "options.hpp" // Para AudioOptions, audio, MusicOptions #include "resource.hpp" // Para Resource -#include "ui/logger.hpp" // Para logger +#include "ui/logger.hpp" // Para logger // Singleton Audio* Audio::instance = nullptr; @@ -91,7 +91,7 @@ void Audio::fadeOutMusic(int milliseconds) const { } // Consulta directamente el estado real de la música en jailaudio -auto Audio::getRealMusicState() const -> MusicState { +auto Audio::getRealMusicState() -> MusicState { JA_Music_state ja_state = JA_GetMusicState(); switch (ja_state) { case JA_MUSIC_PLAYING: diff --git a/source/audio.hpp b/source/audio.hpp index 4e5c547..adaef96 100644 --- a/source/audio.hpp +++ b/source/audio.hpp @@ -67,12 +67,12 @@ class Audio { void setMusicVolume(int volume) const; // Ajustar volumen de música // --- Getters para debug --- - bool isEnabled() const { return enabled_; } - bool isSoundEnabled() const { return sound_enabled_; } - bool isMusicEnabled() const { return music_enabled_; } - MusicState getMusicState() const { return music_.state; } - MusicState getRealMusicState() const; // Consulta directamente a jailaudio - const std::string& getCurrentMusicName() const { return music_.name; } + [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } + [[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; } + [[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; } + [[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; } + [[nodiscard]] static auto getRealMusicState() -> MusicState; // Consulta directamente a jailaudio + [[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; } private: // --- Estructuras privadas --- diff --git a/source/background.cpp b/source/background.cpp index 020c703..3253d55 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -3,18 +3,19 @@ #include // Para SDL_FRect, SDL_SetRenderTarget, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetRenderTarget, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_TextureAccess, SDL_FPoint -#include // Para clamp, max +#include // Para clamp, min, max #include // Para M_PI, cos, sin -#include +#include // Para basic_string +#include // Para move -#include "animated_sprite.hpp" // Para MovingSprite +#include "animated_sprite.hpp" // Para AnimatedSprite #include "moving_sprite.hpp" // Para MovingSprite #include "param.hpp" // Para Param, ParamBackground, param #include "resource.hpp" // Para Resource #include "screen.hpp" // Para Screen #include "sprite.hpp" // Para Sprite #include "texture.hpp" // Para Texture -#include "utils.hpp" // Para funciones de easing +#include "utils.hpp" // Para easeOutCubic // Constructor Background::Background(float total_progress_to_complete) @@ -191,7 +192,7 @@ void Background::setState(State new_state) { // Si entra en estado completado, inicializar variables de transición if (new_state == State::COMPLETED && state_ != State::COMPLETED) { completion_initial_progress_ = progress_; - completion_transition_timer_ = 0.0f; + completion_transition_timer_ = 0.0F; } state_ = new_state; @@ -209,8 +210,8 @@ void Background::reset() { moon_index_ = 0; // Resetear variables de transición de completado - completion_transition_timer_ = 0.0f; - completion_initial_progress_ = 0.0f; + completion_transition_timer_ = 0.0F; + completion_initial_progress_ = 0.0F; // Notifica el cambio si hay callback if (progress_callback_ && progress_ != old_progress) { @@ -274,9 +275,9 @@ void Background::updateProgression(float delta_time) { completion_transition_timer_ += delta_time; // Calcular progreso normalizado de la transición (0.0 a 1.0) - float t = std::min(completion_transition_timer_ / COMPLETION_TRANSITION_DURATION_S, 1.0f); + float t = std::min(completion_transition_timer_ / COMPLETION_TRANSITION_DURATION_S, 1.0F); - if (t < 1.0f) { + if (t < 1.0F) { // Usar easeOutCubic para transición suave (rápido al inicio, lento al final) float eased_t = easeOutCubic(static_cast(t)); @@ -342,12 +343,12 @@ void Background::updateCloudsSpeed() { } // Actualiza las nubes -void Background::updateClouds(float deltaTime) { +void Background::updateClouds(float delta_time) { // Mueve las nubes - top_clouds_sprite_a_->update(deltaTime); - top_clouds_sprite_b_->update(deltaTime); - bottom_clouds_sprite_a_->update(deltaTime); - bottom_clouds_sprite_b_->update(deltaTime); + top_clouds_sprite_a_->update(delta_time); + top_clouds_sprite_b_->update(delta_time); + bottom_clouds_sprite_a_->update(delta_time); + bottom_clouds_sprite_b_->update(delta_time); // Calcula el offset de las nubes if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth()) { diff --git a/source/background.hpp b/source/background.hpp index 5344518..118e751 100644 --- a/source/background.hpp +++ b/source/background.hpp @@ -117,8 +117,8 @@ class Background { bool manual_mode_ = false; // Si está en modo manual // --- Variables para transición suave de completado --- - float completion_transition_timer_ = 0.0f; // Timer para la transición de completado - float completion_initial_progress_ = 0.0f; // Progreso inicial al entrar en estado completado + float completion_transition_timer_ = 0.0F; // Timer para la transición de completado + float completion_initial_progress_ = 0.0F; // Progreso inicial al entrar en estado completado // --- Métodos internos --- void initializePaths(); // Inicializa las rutas del sol y la luna @@ -133,7 +133,7 @@ class Background { void renderBottomClouds(); // Dibuja las nubes inferiores void fillCanvas(); // Compone todos los elementos en la textura void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación - void updateClouds(float deltaTime); // Actualiza el movimiento de las nubes (time-based) + void updateClouds(float delta_time); // Actualiza el movimiento de las nubes (time-based) void createSunPath(); // Precalcula el recorrido del sol void createMoonPath(); // Precalcula el recorrido de la luna }; \ No newline at end of file diff --git a/source/balloon.cpp b/source/balloon.cpp index 2427ece..444d194 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -131,7 +131,7 @@ void Balloon::render() { // Renderizado para el resto de globos if (isBeingCreated()) { // Renderizado con transparencia - sprite_->getTexture()->setAlpha(255 - (int)((float)creation_counter_ * (255.0F / (float)creation_counter_ini_))); + sprite_->getTexture()->setAlpha(255 - (int)(creation_counter_ * (255.0F / creation_counter_ini_))); sprite_->render(); sprite_->getTexture()->setAlpha(255); } else { @@ -142,19 +142,19 @@ void Balloon::render() { } // Actualiza la posición y estados del globo (time-based) -void Balloon::move(float deltaTime) { +void Balloon::move(float delta_time) { if (isStopped()) { return; } - handleHorizontalMovement(deltaTime); - handleVerticalMovement(deltaTime); - applyGravity(deltaTime); + handleHorizontalMovement(delta_time); + handleVerticalMovement(delta_time); + applyGravity(delta_time); } -void Balloon::handleHorizontalMovement(float deltaTime) { +void Balloon::handleHorizontalMovement(float delta_time) { // DeltaTime en segundos: velocidad (pixels/s) * tempo * tiempo (s) - x_ += vx_ * game_tempo_ * deltaTime; + x_ += vx_ * game_tempo_ * delta_time; const int CLIP = 2; const float MIN_X = play_area_.x - CLIP; @@ -165,9 +165,9 @@ void Balloon::handleHorizontalMovement(float deltaTime) { } } -void Balloon::handleVerticalMovement(float deltaTime) { +void Balloon::handleVerticalMovement(float delta_time) { // DeltaTime en segundos: velocidad (pixels/s) * tempo * tiempo (s) - y_ += vy_ * game_tempo_ * deltaTime; + y_ += vy_ * game_tempo_ * delta_time; if (shouldCheckTopCollision()) { handleTopCollision(); @@ -222,37 +222,37 @@ void Balloon::handleBottomCollision() { } } -void Balloon::applyGravity(float deltaTime) { +void Balloon::applyGravity(float delta_time) { // DeltaTime en segundos: aceleración (pixels/s²) * tempo * tiempo (s) - vy_ += gravity_ * game_tempo_ * deltaTime; + vy_ += gravity_ * game_tempo_ * delta_time; } -void Balloon::playBouncingSound() { +void Balloon::playBouncingSound() const { if (sound_.enabled && sound_.bouncing_enabled) { Audio::get()->playSound(sound_.bouncing_file); } } -void Balloon::playPoppingSound() { +void Balloon::playPoppingSound() const { if (sound_.enabled && sound_.poping_enabled) { Audio::get()->playSound(sound_.popping_file); } } // Actualiza al globo a su posicion, animación y controla los contadores (time-based) -void Balloon::update(float deltaTime) { - move(deltaTime); - updateState(deltaTime); +void Balloon::update(float delta_time) { + move(delta_time); + updateState(delta_time); updateBounceEffect(); shiftSprite(); shiftColliders(); - sprite_->update(deltaTime); + sprite_->update(delta_time); // Contador interno con deltaTime en segundos - counter_ += deltaTime; + counter_ += delta_time; } // Actualiza los estados del globo (time-based) -void Balloon::updateState(float deltaTime) { +void Balloon::updateState(float delta_time) { // Si se está creando if (isBeingCreated()) { // Actualiza el valor de las variables @@ -262,13 +262,13 @@ void Balloon::updateState(float deltaTime) { if (creation_counter_ > 0) { // Desplaza lentamente el globo hacia abajo y hacia un lado // Cada 10/60 segundos (equivalente a 10 frames a 60fps) - movement_accumulator_ += deltaTime; + movement_accumulator_ += delta_time; - constexpr float MOVEMENT_INTERVAL_S = 10.0f / 60.0f; // 10 frames = ~0.167s + constexpr float MOVEMENT_INTERVAL_S = 10.0F / 60.0F; // 10 frames = ~0.167s if (movement_accumulator_ >= MOVEMENT_INTERVAL_S) { movement_accumulator_ -= MOVEMENT_INTERVAL_S; y_++; - x_ += vx_ / 60.0f; // Convierte de pixels/segundo a pixels/frame para movimiento discreto + x_ += vx_ / 60.0F; // Convierte de pixels/segundo a pixels/frame para movimiento discreto // Comprueba no se salga por los laterales const int MIN_X = play_area_.x; @@ -276,12 +276,12 @@ void Balloon::updateState(float deltaTime) { if (x_ < MIN_X || x_ > MAX_X) { // Corrige y cambia el sentido de la velocidad - x_ -= vx_ / 60.0f; + x_ -= vx_ / 60.0F; vx_ = -vx_; } } - creation_counter_ -= deltaTime; - if (creation_counter_ < 0) creation_counter_ = 0; + creation_counter_ -= delta_time; + creation_counter_ = std::max(creation_counter_, 0); } else { diff --git a/source/balloon.hpp b/source/balloon.hpp index 73ad5c1..278cc27 100644 --- a/source/balloon.hpp +++ b/source/balloon.hpp @@ -77,7 +77,7 @@ class Balloon { Size size = Size::EXTRALARGE; float vel_x = VELX_POSITIVE; float game_tempo = GAME_TEMPO.at(0); - float creation_counter = 0.0f; + float creation_counter = 0.0F; SDL_FRect play_area = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; std::shared_ptr texture = nullptr; std::vector animation; @@ -91,8 +91,8 @@ class Balloon { // --- Métodos principales --- void alignTo(int x); // Centra el globo en la posición X void render(); // Pinta el globo en la pantalla - void move(float deltaTime); // Actualiza la posición y estados del globo (time-based) - void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based) + void move(float delta_time); // Actualiza la posición y estados del globo (time-based) + void update(float delta_time); // Actualiza el globo (posición, animación, contadores) (time-based) void stop(); // Detiene el globo void start(); // Pone el globo en movimiento void pop(bool should_sound = false); // Explota el globo @@ -268,7 +268,7 @@ class Balloon { Uint8 menace_; // Amenaza que genera el globo Uint32 counter_ = 0; // Contador interno float game_tempo_; // Multiplicador de tempo del juego - float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime) + float movement_accumulator_ = 0.0F; // Acumulador para movimiento durante creación (deltaTime) Uint8 power_; // Poder que alberga el globo SDL_FRect play_area_; // Zona de movimiento del globo Sound sound_; // Configuración de sonido del globo @@ -279,14 +279,14 @@ class Balloon { void shiftSprite(); // Alinea el sprite en pantalla // --- Animación y sonido --- - void setAnimation(); // Establece la animación correspondiente - void playBouncingSound(); // Reproduce el sonido de rebote - void playPoppingSound(); // Reproduce el sonido de reventar + void setAnimation(); // Establece la animación correspondiente + void playBouncingSound() const; // Reproduce el sonido de rebote + void playPoppingSound() const; // Reproduce el sonido de reventar // --- Movimiento y física --- - void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based) - void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based) - void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based) + void handleHorizontalMovement(float delta_time); // Maneja el movimiento horizontal (time-based) + void handleVerticalMovement(float delta_time); // Maneja el movimiento vertical (time-based) + void applyGravity(float delta_time); // Aplica la gravedad al objeto (time-based) // --- Rebote --- void enableBounceEffect(); // Activa el efecto de rebote @@ -301,5 +301,5 @@ class Balloon { void handleBottomCollision(); // Maneja la colisión inferior // --- Lógica de estado --- - void updateState(float deltaTime); // Actualiza los estados del globo (time-based) + void updateState(float delta_time); // Actualiza los estados del globo (time-based) }; \ No newline at end of file diff --git a/source/balloon_formations.cpp b/source/balloon_formations.cpp index da1ab77..59ec769 100644 --- a/source/balloon_formations.cpp +++ b/source/balloon_formations.cpp @@ -235,10 +235,10 @@ void BalloonFormations::createFloaterVariants() { #ifdef _DEBUG void BalloonFormations::addTestFormation() { std::vector test_params = { - {10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s - {140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s + {10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334F}, // 200 frames ÷ 60fps = 3.334s + {50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334F}, // 200 frames ÷ 60fps = 3.334s + {90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334F}, // 200 frames ÷ 60fps = 3.334s + {140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334F}}; // 200 frames ÷ 60fps = 3.334s formations_.at(99) = Formation(test_params); } diff --git a/source/balloon_formations.hpp b/source/balloon_formations.hpp index c67891d..e2b1e7d 100644 --- a/source/balloon_formations.hpp +++ b/source/balloon_formations.hpp @@ -1,14 +1,14 @@ #pragma once -#include // Para copy, max -#include // Para size_t -#include // Para map -#include // Para optional -#include // Para string -#include // Para pair -#include // Para vector +#include // Para size_t +#include // Para pair +#include // Para map +#include // Para optional +#include // Para string +#include // Para pair +#include // Para vector -#include "balloon.hpp" // Para Balloon +#include "balloon.hpp" // for Balloon // --- Clase BalloonFormations --- class BalloonFormations { @@ -20,7 +20,7 @@ class BalloonFormations { float vel_x = 0.0F; // Velocidad inicial en el eje X Balloon::Type type = Balloon::Type::BALLOON; // Tipo de globo Balloon::Size size = Balloon::Size::SMALL; // Tamaño de globo - float creation_counter = 0.0f; // Temporizador para la creación del globo + float creation_counter = 0.0F; // Temporizador para la creación del globo // Constructor por defecto SpawnParams() = default; @@ -82,8 +82,8 @@ class BalloonFormations { private: // --- Constantes --- static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos - static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) - static constexpr float DEFAULT_CREATION_TIME = 3.334f; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s) + static constexpr float CREATION_TIME = 5.0F; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) + static constexpr float DEFAULT_CREATION_TIME = 3.334F; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s) // --- Variables --- std::vector formations_; // Vector con todas las formaciones disponibles diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index a0ab18b..2fd5e07 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -63,12 +63,12 @@ void BalloonManager::init() { } // Actualiza (time-based) -void BalloonManager::update(float deltaTime) { +void BalloonManager::update(float delta_time) { for (const auto& balloon : balloons_) { - balloon->update(deltaTime); + balloon->update(delta_time); } - updateBalloonDeployCounter(deltaTime); - explosions_->update(deltaTime); + updateBalloonDeployCounter(delta_time); + explosions_->update(delta_time); } // Renderiza los objetos @@ -82,7 +82,7 @@ void BalloonManager::render() { // Crea una formación de globos void BalloonManager::deployRandomFormation(int stage) { // Solo despliega una formación enemiga si el timer ha llegado a cero - if (balloon_deploy_counter_ <= 0.0f) { + if (balloon_deploy_counter_ <= 0.0F) { // En este punto se decide entre crear una powerball o una formación enemiga if ((rand() % 100 < 15) && (canPowerBallBeCreated())) { createPowerBall(); // Crea una powerball @@ -114,7 +114,7 @@ void BalloonManager::deployRandomFormation(int stage) { .size = balloon.size, .vel_x = balloon.vel_x, .game_tempo = balloon_speed_, - .creation_counter = creation_time_enabled_ ? balloon.creation_counter : 0.0f}; + .creation_counter = creation_time_enabled_ ? balloon.creation_counter : 0.0F}; createBalloon(config); } @@ -163,9 +163,9 @@ void BalloonManager::freeBalloons() { } // Actualiza el timer de despliegue de globos (time-based) -void BalloonManager::updateBalloonDeployCounter(float deltaTime) { +void BalloonManager::updateBalloonDeployCounter(float delta_time) { // DeltaTime en segundos - timer decrementa hasta llegar a cero - balloon_deploy_counter_ -= deltaTime; + balloon_deploy_counter_ -= delta_time; } // Indica si se puede crear una powerball diff --git a/source/balloon_manager.hpp b/source/balloon_manager.hpp index c43256b..813980b 100644 --- a/source/balloon_manager.hpp +++ b/source/balloon_manager.hpp @@ -2,19 +2,18 @@ #include // Para SDL_FRect -#include // Para max -#include // Para array -#include // Para shared_ptr, unique_ptr -#include // Para string -#include // Para vector +#include // Para array +#include // Para shared_ptr, unique_ptr +#include // Para basic_string, string +#include // Para vector -#include "balloon.hpp" // Para BALLOON_SPEED, Balloon, Balloon::Size (ptr only), Balloon::Type (ptr only) -#include "balloon_formations.hpp" // Para BalloonFormations -#include "explosions.hpp" // Para Explosions -#include "param.hpp" // Para Param, ParamGame, param -#include "stage_interface.hpp" // Para IStageInfo -#include "utils.hpp" // Para Zone +#include "balloon.hpp" // for Balloon +#include "balloon_formations.hpp" // for BalloonFormations +#include "explosions.hpp" // for Explosions +#include "param.hpp" // for Param, ParamGame, param +#include "utils.hpp" // for Zone +class IStageInfo; class Texture; // --- Types --- @@ -28,8 +27,8 @@ class BalloonManager { ~BalloonManager() = default; // --- Métodos principales --- - void update(float deltaTime); // Actualiza el estado de los globos (time-based) - void render(); // Renderiza los globos en pantalla + void update(float delta_time); // Actualiza el estado de los globos (time-based) + void render(); // Renderiza los globos en pantalla // --- Gestión de globos --- void freeBalloons(); // Libera globos que ya no sirven @@ -49,7 +48,7 @@ class BalloonManager { void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos - void updateBalloonDeployCounter(float deltaTime); // Actualiza el contador de despliegue (time-based) + void updateBalloonDeployCounter(float delta_time); // Actualiza el contador de despliegue (time-based) auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla @@ -82,9 +81,9 @@ class BalloonManager { private: // --- Constantes --- - static constexpr float DEFAULT_BALLOON_DEPLOY_DELAY = 5.0f; // 300 frames = 5 segundos - static constexpr float POWERBALL_DEPLOY_DELAY = 0.167f; // 10 frames = 0.167 segundos - static constexpr float BALLOON_POP_DELAY = 0.333f; // 20 frames = 0.333 segundos + static constexpr float DEFAULT_BALLOON_DEPLOY_DELAY = 5.0F; // 300 frames = 5 segundos + static constexpr float POWERBALL_DEPLOY_DELAY = 0.167F; // 10 frames = 0.167 segundos + static constexpr float BALLOON_POP_DELAY = 0.333F; // 20 frames = 0.333 segundos // --- Objetos y punteros --- Balloons balloons_; // Vector con los globos activos diff --git a/source/bullet.cpp b/source/bullet.cpp index def7764..d267ca3 100644 --- a/source/bullet.cpp +++ b/source/bullet.cpp @@ -1,10 +1,9 @@ #include "bullet.hpp" -#include // Para allocator, unique_ptr, make_unique -#include // Para char_traits, basic_string, operator+, string +#include // Para unique_ptr, make_unique +#include // Para basic_string, string #include "param.hpp" // Para Param, ParamGame, param -#include "player.hpp" // Para Player::Id #include "resource.hpp" // Para Resource // Constructor @@ -79,20 +78,20 @@ void Bullet::render() { } // Actualiza el estado del objeto -auto Bullet::update(float deltaTime) -> MoveStatus { - sprite_->update(deltaTime); - return move(deltaTime); +auto Bullet::update(float delta_time) -> MoveStatus { + sprite_->update(delta_time); + return move(delta_time); } // Implementación del movimiento usando MoveStatus -auto Bullet::move(float deltaTime) -> MoveStatus { - pos_x_ += vel_x_ * deltaTime; +auto Bullet::move(float delta_time) -> MoveStatus { + pos_x_ += vel_x_ * delta_time; if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) { disable(); return MoveStatus::OUT; } - pos_y_ += VEL_Y * deltaTime; + pos_y_ += VEL_Y * delta_time; if (pos_y_ < param.game.play_area.rect.y - HEIGHT) { disable(); return MoveStatus::OUT; diff --git a/source/bullet.hpp b/source/bullet.hpp index a13ff54..8034de1 100644 --- a/source/bullet.hpp +++ b/source/bullet.hpp @@ -40,9 +40,9 @@ class Bullet { ~Bullet() = default; // Destructor // --- Métodos principales --- - void render(); // Dibuja la bala en pantalla - auto update(float deltaTime) -> MoveStatus; // Actualiza el estado del objeto (time-based) - void disable(); // Desactiva la bala + void render(); // Dibuja la bala en pantalla + auto update(float delta_time) -> MoveStatus; // Actualiza el estado del objeto (time-based) + void disable(); // Desactiva la bala // --- Getters --- [[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa @@ -70,7 +70,7 @@ class Bullet { // --- Métodos internos --- void shiftColliders(); // Ajusta el círculo de colisión void shiftSprite(); // Ajusta el sprite - auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) + auto move(float delta_time) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación }; diff --git a/source/bullet_manager.cpp b/source/bullet_manager.cpp index d9a743a..e68e8eb 100644 --- a/source/bullet_manager.cpp +++ b/source/bullet_manager.cpp @@ -1,10 +1,11 @@ #include "bullet_manager.hpp" #include // Para remove_if +#include #include "bullet.hpp" // Para Bullet -#include "param.hpp" // Para param -#include "player.hpp" // Para Player +#include "param.hpp" // Para Param, ParamGame, param +#include "utils.hpp" // Para Circle, Zone // Constructor BulletManager::BulletManager() @@ -12,10 +13,10 @@ BulletManager::BulletManager() } // Actualiza el estado de todas las balas -void BulletManager::update(float deltaTime) { +void BulletManager::update(float delta_time) { for (auto& bullet : bullets_) { if (bullet->isEnabled()) { - processBulletUpdate(bullet, deltaTime); + processBulletUpdate(bullet, delta_time); } } } @@ -36,14 +37,9 @@ void BulletManager::createBullet(int x, int y, Bullet::Type type, Bullet::Color // Libera balas que ya no están habilitadas void BulletManager::freeBullets() { - if (!bullets_.empty()) { - // Elimina las balas deshabilitadas del vector - bullets_.erase( - std::remove_if(bullets_.begin(), bullets_.end(), [](const std::shared_ptr& bullet) { - return !bullet->isEnabled(); - }), - bullets_.end()); - } + std::erase_if(bullets_, [](const std::shared_ptr& bullet) { + return !bullet->isEnabled(); + }); } // Elimina todas las balas @@ -72,24 +68,24 @@ void BulletManager::checkCollisions() { // Establece el callback para colisión con Tabe void BulletManager::setTabeCollisionCallback(CollisionCallback callback) { - tabe_collision_callback_ = callback; + tabe_collision_callback_ = std::move(callback); } // Establece el callback para colisión con globos void BulletManager::setBalloonCollisionCallback(CollisionCallback callback) { - balloon_collision_callback_ = callback; + balloon_collision_callback_ = std::move(callback); } // Establece el callback para balas fuera de límites void BulletManager::setOutOfBoundsCallback(OutOfBoundsCallback callback) { - out_of_bounds_callback_ = callback; + out_of_bounds_callback_ = std::move(callback); } // --- Métodos privados --- // Procesa la actualización individual de una bala -void BulletManager::processBulletUpdate(const std::shared_ptr& bullet, float deltaTime) { - auto status = bullet->update(deltaTime); +void BulletManager::processBulletUpdate(const std::shared_ptr& bullet, float delta_time) { + auto status = bullet->update(delta_time); // Si la bala salió de los límites, llama al callback if (status == Bullet::MoveStatus::OUT && out_of_bounds_callback_) { @@ -98,7 +94,7 @@ void BulletManager::processBulletUpdate(const std::shared_ptr& bullet, f } // Verifica si la bala está fuera de los límites del área de juego -auto BulletManager::isBulletOutOfBounds(const std::shared_ptr& bullet) -> bool { +auto BulletManager::isBulletOutOfBounds(const std::shared_ptr& bullet) const -> bool { auto collider = bullet->getCollider(); return (collider.x < play_area_.x || diff --git a/source/bullet_manager.hpp b/source/bullet_manager.hpp index 32eccce..556f6a0 100644 --- a/source/bullet_manager.hpp +++ b/source/bullet_manager.hpp @@ -3,18 +3,14 @@ #include // Para SDL_FRect #include // Para function -#include // Para shared_ptr, unique_ptr +#include // Para shared_ptr #include // Para vector -#include "bullet.hpp" // Para Bullet -#include "utils.hpp" // Para Circle +#include "bullet.hpp" // for Bullet // --- Types --- using Bullets = std::vector>; -// --- Forward declarations --- -class Player; - // --- Clase BulletManager: gestiona todas las balas del juego --- // // Esta clase se encarga de la gestión completa de las balas del juego, @@ -40,8 +36,8 @@ class BulletManager { ~BulletManager() = default; // --- Métodos principales --- - void update(float deltaTime); // Actualiza el estado de las balas (time-based) - void render(); // Renderiza las balas en pantalla + void update(float delta_time); // Actualiza el estado de las balas (time-based) + void render(); // Renderiza las balas en pantalla // --- Gestión de balas --- void createBullet(int x, int y, Bullet::Type type, Bullet::Color color, int owner); // Crea una nueva bala @@ -74,6 +70,6 @@ class BulletManager { OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites // --- Métodos internos --- - void processBulletUpdate(const std::shared_ptr& bullet, float deltaTime); // Procesa actualización individual - auto isBulletOutOfBounds(const std::shared_ptr& bullet) -> bool; // Verifica si la bala está fuera de límites + void processBulletUpdate(const std::shared_ptr& bullet, float delta_time); // Procesa actualización individual + auto isBulletOutOfBounds(const std::shared_ptr& bullet) const -> bool; // Verifica si la bala está fuera de límites }; \ No newline at end of file diff --git a/source/color.cpp b/source/color.cpp index f37d1dc..f0e2c40 100644 --- a/source/color.cpp +++ b/source/color.cpp @@ -43,7 +43,7 @@ auto Color::fromHex(const std::string& hex_str) -> Color { } // Implementaciones de métodos estáticos de Color -constexpr auto Color::rgbToHsv(Color color) -> HSV { +constexpr auto Color::RGB_TO_HSV(Color color) -> HSV { float r = color.r / 255.0F; float g = color.g / 255.0F; float b = color.b / 255.0F; @@ -73,7 +73,7 @@ constexpr auto Color::rgbToHsv(Color color) -> HSV { return {.h = h, .s = s, .v = v}; } -constexpr auto Color::hsvToRgb(HSV hsv) -> Color { +constexpr auto Color::HSV_TO_RGB(HSV hsv) -> Color { float c = hsv.v * hsv.s; float x = c * (1 - std::abs(std::fmod(hsv.h / 60.0F, 2) - 1)); float m = hsv.v - c; @@ -133,7 +133,7 @@ auto getColorLikeKnightRider(const std::vector& colors, int counter) -> C auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle { Cycle result{}; - HSV base_hsv = Color::rgbToHsv(base); + HSV base_hsv = Color::RGB_TO_HSV(base); for (size_t i = 0; i < CYCLE_SIZE; ++i) { float t = static_cast(i) / (CYCLE_SIZE - 1); // 0 → 1 @@ -176,7 +176,7 @@ auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle { .s = fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)), .v = fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))}; - Color c = Color::hsvToRgb(adjusted); + Color c = Color::HSV_TO_RGB(adjusted); result[i] = c; result[(2 * CYCLE_SIZE) - 1 - i] = c; // espejo } diff --git a/source/color.hpp b/source/color.hpp index 2a84cfd..5baecf1 100644 --- a/source/color.hpp +++ b/source/color.hpp @@ -72,8 +72,8 @@ struct Color { static auto fromHex(const std::string& hex_str) -> Color; // Conversiones de formato de color - [[nodiscard]] constexpr static auto rgbToHsv(Color color) -> HSV; - [[nodiscard]] constexpr static auto hsvToRgb(HSV hsv) -> Color; + [[nodiscard]] constexpr static auto RGB_TO_HSV(Color color) -> HSV; + [[nodiscard]] constexpr static auto HSV_TO_RGB(HSV hsv) -> Color; [[nodiscard]] constexpr auto IS_EQUAL_TO(const Color& other) const -> bool { return r == other.r && g == other.g && b == other.b && a == other.a; @@ -98,11 +98,11 @@ struct Color { // Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target) [[nodiscard]] constexpr auto LERP(const Color& target, float t) const -> Color { // Asegurar que t esté en el rango [0.0, 1.0] - t = std::clamp(t, 0.0f, 1.0f); + t = std::clamp(t, 0.0F, 1.0F); // Interpolación lineal para cada componente auto lerp_component = [t](Uint8 start, Uint8 end) -> Uint8 { - return static_cast(start + (end - start) * t); + return static_cast(start + ((end - start) * t)); }; return Color( diff --git a/source/define_buttons.cpp b/source/define_buttons.cpp index 2ca5c64..82a920f 100644 --- a/source/define_buttons.cpp +++ b/source/define_buttons.cpp @@ -1,15 +1,13 @@ #include "define_buttons.hpp" -#include // Para __all_of_fn, all_of -#include // Para identity -#include // Para allocator, unique_ptr, shared_ptr, make_unique, operator== +#include // Para __all_of_fn, all_of +#include // Para unique_ptr, allocator, shared_ptr, operator==, make_unique -#include "color.hpp" // Para Color #include "input.hpp" // Para Input #include "input_types.hpp" // Para InputAction #include "lang.hpp" // Para getText #include "options.hpp" // Para Gamepad -#include "param.hpp" // Para Param, ParamGame, param +#include "param.hpp" // Para Param, param, ParamGame, ParamServiceMenu #include "resource.hpp" // Para Resource #include "ui/window_message.hpp" // Para WindowMessage #include "utils.hpp" // Para Zone @@ -234,7 +232,7 @@ void DefineButtons::checkEnd() { // Solo marcar que ya mostramos el mensaje message_shown_ = true; - message_timer_ = 0.0f; + message_timer_ = 0.0F; } } diff --git a/source/define_buttons.hpp b/source/define_buttons.hpp index 6f45a4b..2377770 100644 --- a/source/define_buttons.hpp +++ b/source/define_buttons.hpp @@ -48,7 +48,7 @@ class DefineButtons { private: // --- Constantes --- - static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0f; // Cuánto tiempo mostrar el mensaje en segundos + static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0F; // Cuánto tiempo mostrar el mensaje en segundos // --- Objetos y punteros --- Input* input_ = nullptr; // Entrada del usuario @@ -59,7 +59,7 @@ class DefineButtons { std::vector