utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import gettext as gettext_module
  2. import os
  3. import sys
  4. import warnings
  5. from collections import OrderedDict
  6. from typing import Any
  7. import pygame
  8. import yaml
  9. from pygame.locals import *
  10. from jogai import exceptions as exc
  11. from jogai import logger, settings
  12. from jogai.translations import gettext as _
  13. def _load_image(directory: str, filename: str) -> list:
  14. if not isinstance(directory, str) or not isinstance(filename, str):
  15. raise TypeError(
  16. _('Both the directory and the filename must be strings.')
  17. )
  18. path = os.path.join(directory, filename)
  19. try:
  20. image = pygame.image.load(path)
  21. except FileNotFoundError as fnfe:
  22. raise FileNotFoundError(_('Image filename not found'))
  23. except pygame.error as pe:
  24. raise exc.UnsupportedFileFormatError(filename)
  25. rect = image.get_rect()
  26. return [image, rect]
  27. def _load_yaml(stream: str) -> OrderedDict:
  28. """Create an OrderedDict from a yaml string.
  29. Parameters:
  30. stream: data input stream
  31. Return:
  32. An OrderedDict with the input data.
  33. """
  34. class OrderedLoader(yaml.SafeLoader):
  35. pass
  36. def construct_mapping(loader, node):
  37. loader.flatten_mapping(node)
  38. return OrderedDict(loader.construct_pairs(node))
  39. OrderedLoader.add_constructor(
  40. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping
  41. )
  42. return yaml.load(stream, OrderedLoader)
  43. def _load_yaml_from_filename(
  44. filename: str, directory=settings.DATA_DIR
  45. ) -> OrderedDict:
  46. path = os.path.join(directory, filename)
  47. with open(path) as file:
  48. content = file.read()
  49. return _load_yaml(content)
  50. def _convert_function_arguments_to_string(arguments: Any) -> str:
  51. """
  52. Convert function arguments from yaml data to string.
  53. Parameters:
  54. arguments: The function arguments from yaml item.
  55. Returns:
  56. A string with the input arguments
  57. Examples:
  58. >>> _convert_function_arguments_to_string({'x': 200, 'y': 400, 'key': 'a'})
  59. "x=200, y=400, key='a'"
  60. >>> _convert_function_arguments_to_string(['foo', 'bar'])
  61. "'foo', 'bar'"
  62. """
  63. if not isinstance(arguments, list) and not isinstance(arguments, dict):
  64. arguments = [arguments]
  65. if isinstance(arguments, list):
  66. processed_arguments = ', '.join([repr(v) for v in arguments])
  67. if isinstance(arguments, dict):
  68. processed_arguments = ', '.join(
  69. ['='.join((str(k), repr(v))) for k, v in arguments.items()]
  70. )
  71. return processed_arguments
  72. def _get_events() -> list:
  73. return pygame.event.get()
  74. def _get_keys() -> list:
  75. return pygame.key.get_pressed()
  76. def eval_key(key: str) -> int:
  77. """
  78. Evaluate a string as a pygame key.
  79. Parameters:
  80. key: string representation of a key with or without 'K_' prefix
  81. Examples:
  82. >>> key = eval_key('K_a')
  83. >>> key = eval_key('a')
  84. Returns:
  85. The integer representing the input key.
  86. """
  87. if not isinstance(key, str):
  88. raise exc.KeyPressedNotFoundError
  89. try:
  90. if key.startswith('K_'):
  91. return eval(key)
  92. else:
  93. return eval(f'K_{key}')
  94. except NameError:
  95. raise exc.KeyPressedNotFoundError