colour.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. colour.py
  3. NakedMud's base colour module. Contains functions for outbound text processing
  4. to add ASCII colour codes to the text.
  5. """
  6. import mud, mudsock, hooks
  7. # symbols and values we need for processing colours
  8. base_colour_marker = '{'
  9. colour_start = '\x1b['
  10. cDARK = '0'
  11. cLIGHT = '1'
  12. # colour symbols
  13. c_none = 'n'
  14. c_dark = 'd'
  15. c_red = 'r'
  16. c_green = 'g'
  17. c_yellow = 'y'
  18. c_blue = 'b'
  19. c_magenta = 'p'
  20. c_cyan = 'c'
  21. c_white = 'w'
  22. # maps of colour symbols to their ASCII number type thing
  23. base_colours = { c_none : '0',
  24. c_dark : '30',
  25. c_red : '31',
  26. c_green : '32',
  27. c_yellow : '33',
  28. c_blue : '34',
  29. c_magenta : '35',
  30. c_cyan : '36',
  31. c_white : '37' }
  32. ################################################################################
  33. # colour processing hooks
  34. ################################################################################
  35. def process_colour_hook(info):
  36. """When outbound text is being processed, find colour codes and replace them
  37. by the proper colour escape sequences."""
  38. sock, = hooks.parse_info(info)
  39. buf = sock.outbound_text
  40. newbuf = []
  41. # go through our outbound text and process all of the colour codes
  42. i = 0
  43. while i < len(buf):
  44. if buf[i] == base_colour_marker and i + 1 < len(buf):
  45. i = i + 1
  46. char = buf[i]
  47. # upper case is bright, lower case is dark
  48. shade = cLIGHT
  49. if char == char.lower():
  50. shade = cDARK
  51. # if it's a valid colour code, build it
  52. if base_colours.has_key(char.lower()):
  53. newbuf.append(colour_start + shade + ';' + \
  54. base_colours[char.lower()] + 'm')
  55. # if it was an invalid code, ignore it
  56. else:
  57. newbuf.append(base_colour_marker)
  58. if not char == base_colour_marker:
  59. i = i - 1
  60. else:
  61. newbuf.append(buf[i])
  62. i = i + 1
  63. # replace our outbound buffer with the processed text
  64. sock.outbound_text = ''.join(newbuf)
  65. ################################################################################
  66. # initializing and unloading our hooks
  67. ################################################################################
  68. hooks.add("process_outbound_text", process_colour_hook)
  69. hooks.add("process_outbound_prompt", process_colour_hook)
  70. def __unload__():
  71. '''detaches our colour module from the game'''
  72. hooks.remove("process_outbound_text", process_colour_hook)
  73. hooks.remove("process_outbound_prompt", process_colour_hook)