Last active
April 26, 2020 13:21
-
-
Save sharmaeklavya2/ccdfa59e61d77f69feb82a66c41873ab to your computer and use it in GitHub Desktop.
Rockets using threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Controls: | |
Press keys A and D to move rocket 1 | |
Press keys H and K to move rocket 2 | |
Press Ctrl+C to exit | |
""" | |
from __future__ import print_function | |
import threading | |
import time | |
import sys | |
def get_getch(): | |
try: | |
import msvcrt | |
if sys.version_info.major == 2: | |
return msvcrt.getch | |
else: | |
return lambda : msvcrt.getch().decode('utf-8') | |
except ImportError: | |
return lambda : sys.stdin.read(1) | |
getch = get_getch() | |
running = False | |
class Console(object): | |
@staticmethod | |
def init(): | |
try: | |
import termios | |
Console.is_unix = True | |
Console.fd = sys.stdin.fileno() | |
Console.oldattr = termios.tcgetattr(Console.fd) | |
newattr = termios.tcgetattr(Console.fd) | |
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO | |
termios.tcsetattr(Console.fd, termios.TCSANOW, newattr) | |
except ImportError: | |
Console.is_unix = False | |
@staticmethod | |
def reset(): | |
if Console.is_unix: | |
import termios | |
termios.tcsetattr(Console.fd, termios.TCSANOW, Console.oldattr) | |
Console.init() | |
class Rocket(object): | |
length = 75 | |
def __init__(self, pos, face, leftkey, rightkey): | |
self.pos = pos | |
self.face = face | |
self.leftkey = leftkey | |
self.rightkey = rightkey | |
def react(self, key): | |
if key==self.leftkey: | |
if self.pos>0: | |
self.pos-=1 | |
elif key==self.rightkey: | |
if self.pos+1<Rocket.length: | |
self.pos+=1 | |
class Stamper(threading.Thread): | |
def __init__(self, rocket_list, sleep_time, name): | |
super(Stamper, self).__init__() | |
self.rocket_list = rocket_list | |
self.sleep_time = sleep_time | |
self.name = name | |
def run(self): | |
while(running): | |
char_array = [" "]*Rocket.length | |
for rocket in self.rocket_list: | |
char_array[rocket.pos] = rocket.face | |
print("".join(char_array)) | |
time.sleep(self.sleep_time) | |
def main(): | |
rocket_list = [Rocket(0, 'O', 'a', 'd'), Rocket(Rocket.length-1, 'H', 'h', 'k')] | |
global running | |
running = True | |
Stamper(rocket_list, 0.1, "stamper").start() | |
while(running): | |
try: | |
inchar = getch() | |
for rocket in rocket_list: | |
rocket.react(inchar) | |
except KeyboardInterrupt: | |
running = False | |
Console.reset() | |
if __name__=="__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment