Advertisement
Peaser

(Nonfunctional) Threaded game example

Sep 6th, 2014
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. #An example of the threading module
  2. #This "Game" doesn't really work, is more of a tech demo
  3. from threading import Thread
  4. import msvcrt
  5. import time
  6. import sys
  7. import random
  8.  
  9. log = ""
  10.  
  11. def out(s, spaces=True):
  12.     global log
  13.     if spaces: extra = " "*(79-len(s))
  14.     else: extra = ""
  15.  
  16.     sys.stdout.write("\r{0}{1}".format(s,extra))
  17.     sys.stdout.flush()
  18.     log += s+"\n"
  19.  
  20. out("It's time.")
  21.  
  22. timer  = 0
  23. pts = 0
  24.  
  25.  
  26. def up():
  27.     out("UP")
  28. def down():
  29.     out("DOWN")
  30. def left():
  31.     out("LEFT")
  32. def right():
  33.     out("RIGHT")
  34. def dtime():
  35.     out("Seconds Active: {0}".format(timer))
  36. def points():
  37.     out("Points: {0}".format(pts))
  38.  
  39.  
  40. events = {
  41. 'w': up,
  42. 'a': left,
  43. 's': down,
  44. 'd': right,
  45. 't': dtime,
  46. 'p': points,
  47. }
  48.  
  49.  
  50.  
  51. def time_manager():
  52.     global timer
  53.     while True:
  54.         time.sleep(1)
  55.         timer += 1
  56.  
  57. def keyEvent():
  58.     while True:
  59.         key = msvcrt.getch()
  60.         if key in events.keys():
  61.             events[key]()
  62.         elif key.encode('hex') == '03':
  63.             with open('Log.txt', 'w') as ld:
  64.                 ld.write(log)
  65.             raise KeyboardInterrupt
  66.  
  67. def getEvent():
  68.     mats = "abcdefghijklmnopqrstuvwxyz"
  69.     event = ''.join(random.choice(mats) for i in range(random.randint(3,7)))
  70.     out("A wild fucking {0} is totes about to fuck you up.".format(event))
  71.  
  72.  
  73. def randomEvent():
  74.     while True:
  75.         e = random.randint(1,100)
  76.         if 1 <= e <= 5:
  77.             getEvent()
  78.         time.sleep(1)
  79.  
  80. if __name__ == "__main__":
  81.     try:
  82.         Thread(target = keyEvent).start()
  83.         Thread(target = time_manager).start()
  84.         Thread(target = randomEvent).start()
  85.     except Exception, e:
  86.         out("Error: {0}".format(e))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement