def main(path_to_file): try: # this ensures that the window is only killed once (in case a new game has been added) window.destroy() print "Your choice: " + path_to_file except: pass while 1: try: # check if game.txt already exists fileobj = open(path_to_file, "r") temptime = fileobj.read() # read time in file... except: # create a new file if game.txt doesn't exist fileobj = open(path_to_file, "w") fileobj.write("0") fileobj.close() main(path_to_file) start = time.time() print "\n\nTimer started. Press any key to pause." getch() end = time.time() gametime = ((end - start) / 3600) # time played in hours fileobj = open(path_to_file, "r") temptime = fileobj.read() # read time in file... fileobj.close totaltime = (float(temptime) + gametime) # ...and add time played (converted to a float) fileobj = open(path_to_file, "w") fileobj.write(str(totaltime)) # write sum in file (converted to a string) fileobj.close() print "\nTimer paused. Press any key to continue." getch() # implementation of a pause feature
def ready(): print("Ready...") k0 = getch() k1 = getch() s0 = taste_zu_spieler(k0) s1 = taste_zu_spieler(k1) if s0 >= 0 and s1 >= 0 and s0 != s1: print(" OK") else: print("!Ungültig!")
def ready(tasten): print("Ready... ", end="") sys.stdout.flush() # damit die Ausgabe sofort erscheint k0 = getch() k1 = getch() s0 = taste_zu_spieler(tasten, k0) s1 = taste_zu_spieler(tasten, k1) if s0 >= 0 and s1 >= 0 and s0 != s1: print("OK\n") else: print("!Ungültig!")
def fight(tasten, spieler, objekte, punkte, bilder): print("Go...") print("") k0 = getch() k1 = getch() s0 = taste_zu_spieler(tasten, k0) s1 = taste_zu_spieler(tasten, k1) if s0 >= 0 and s1 >= 0 and s0 != s1: obj0 = taste_zu_objekt(tasten, k0) obj1 = taste_zu_objekt(tasten, k1) if s0 == 1: swap = obj1 obj1 = obj0 obj0 = swap print("{0:40}{1:40}".format(spieler[0], spieler[1])) print("{0:40}{1:40}".format("v", "v")) print("{0:40}{1:40}".format(objekte[obj0], objekte[obj1])) print("-" * 80) s = auswertung(obj0, obj1) if s >= 0: if s == 0: print_bild(bilder, obj0, 0) else: print_bild(bilder, obj1, 40) # Punktestand anpassen punkte[s] = punkte[s] + 1 ga = None if s == 0: ga = gewinn_aktion(obj0, obj1) else: ga = gewinn_aktion(obj1, obj0) print(">> {0} hat gewonnen, denn {1}".format(spieler[s], ga)) else: print(">> UNENTSCHIEDEN") print(" Punktestand:") print("{0:40}{1:40}".format(spieler[0] + " ({0})".format(punkte[0]), spieler[1] + " ({0})".format(punkte[1]))) else: print("!Ungültig!")
def start(self): print ("CONTROLLER IS READY") c = getch() while ord(c) != ESC: pitch = self.pitchMap.get(c) func = self.funcMap.get(c) if pitch != None: pitch += self.octave*PITCHES_PER_OCTAVE self.playNote(self.channel, pitch, self.velocity, self.sustain, self.monophonic) elif func != None and str(func).isalnum(): eval("self." + str(func) + "()") c = getch() self.close()
def buy_upgrades(self): system('clear') print('1. Buy fuel_tank') print('2. Buy cargo_bay') print('3. Buy engine') print('4. Buy drill') print('5. Buy hull') print('0. Return') char = getch().lower() if char == '1': i = self.printy('fuel tank') if i is not 0: self.buy_fuel_tank(i) elif char == '2': i = self.printy('cargo bay') if i is not 0: self.buy_cargo_bay(i) elif char == '3': i = self.printy('engine') if i is not 0: self.buy_engine(i) elif char == '4': i = self.printy('drill') if i is not 0: self.buy_drill(i) elif char == '5': i = self.printy('hull') if i is not 0: self.buy_hull(i) elif char == '0': self.menu() else: self.buy_upgrades()
def InterfaceKeyboard(): global run what = getch() if what == "m": run = False time.sleep(1) exit()
def interface_getch(): global setpoint global Controller global stop what = getch() if what == "g": setpoint.x = setpoint.x + 0.1 if what == "t": setpoint.x = setpoint.x - 0.1 if what == "h": setpoint.y = setpoint.y + 0.1 if what == "f": setpoint.y = setpoint.y - 0.1 if what == "i": setpoint.z = setpoint.z + 0.1 if what == "k": setpoint.z = setpoint.z - 0.1 if what == "m": stop = True sys.exit("SHUTDOWN") task = Controller.getCurrentTask()
def process_action(self): print(self.process_vars["action_msg_1"]) PrintPrettyAttrs( self.args, self.process_vars["action_attrs"], GetPrettyAttrs(self.process_vars["action_attrs"], self.process_vars["action_attrs_translations"])) print() print("Press \"y\" to continue", end=' ') sys.stdout.flush() keystroke = "y" if getattr(self.args, "y", False) else getch() if keystroke in ["y", "Y"]: print("[Ok]") print(self.process_vars["action_msg_2"], end=' ') sys.stdout.flush() try: if "action_settrans" in self.process_vars: self.dbc.execute( "SET TRANSACTION ISOLATION LEVEL {}".format( self.process_vars["action_settrans"])) self.dbc.callproc(self.process_vars["action_proc"], self.process_vars["action_params"]) except psycopg2.Error: self.handle_pg_exception(sys.exc_info()) else: self.db.commit() print("Done") else: print("[Cancel]")
def InterfaceKeyboard(): global run what = getch() if what == "q": run = False time.sleep(1) exit() rospy.loginfo("Reports sent : %s", reports_count)
def InterfaceKeyboard(): global run what = getch() if what == "q": run = False time.sleep(1) exit() rospy.loginfo("Reports sent : %s", reports_count )
def input_handler(): global firstcoord global secondcoord global minecounter global size global gameover global mark global markcounter # input print(colors['YELLOW'] + "Remaining mines: ", minecounter, "Remaining marks: ", markcounter, colors['END']) if markcounter > 0: print( colors['YELLOW'] + "Do you want to mark the the next target (M-mark, C-check, anything else-exit)? " + colors['END']) mark = getch() if mark == 'm': mark = True elif mark == 'c': mark = False else: gameover = True else: mark = False wrong_input = True if gameover is False: while wrong_input is True: try: firstcoord = int( input( colors['YELLOW'] + "Please give the number of the row you want to check: " + colors['END'])) - 1 secondcoord = int( input( colors['YELLOW'] + "Please give the number of the column you want to check: " + colors['END'])) - 1 if firstcoord >= 0 and secondcoord >= 0 and firstcoord <= size - 1 and secondcoord <= size - 1: wrong_input = False else: print(colors['RED'] + "Wrong input, please taget an existing field!" + colors['END']) except (ValueError): print(colors['RED'] + "Wrong input, please taget an existing field!" + colors['END']) print("")
def promptInput(prompt,history=None): import getch line = '' print(prompt,end='') while True: c = getch()
def move(self): char = getch().lower() if char == 'a': self._do_move(-1, 0) elif char == 'w': self._do_move(0, -1) elif char == 'd': self._do_move(1, 0) elif char == 's': self._do_move(0, 1)
def menu(): print('1. Sell all') print('2. Refill') print('3. Buy upgrades') print('0. Return') char = getch().lower() if char == 3: buy_upgrades() else: menu()
def playGame(self): g = '' while g != "Q": if self.player.isOverlap(self.minotaur): g = self.loseGame() elif self.player.getpos() == self.exit: g = self.winGame() else: g = getch().upper() if self.processMove(g): self.displayBoard()
def input_to(timeout=1): signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(timeout) try: text = getch() signal.alarm(0) return text except AlarmException: (" ") signal.signal(signal.SIGALRM, signal.SIG_IGN) return ''
def fight(): print("Go...") k0 = getch() k1 = getch() s0 = taste_zu_spieler(k0) s1 = taste_zu_spieler(k1) if s0 >= 0 and s1 >= 0 and s0 != s1: obj0 = taste_zu_objekt(k0) obj1 = taste_zu_objekt(k1) if s0 == 1: swap = obj1 obj1 = obj0 obj0 = swap print(" {0} {1}".format(spieler[0], spieler[1])) print(" # {0} # # {1} #".format(objekte[obj0], objekte[obj1])) else: print("!Ungültig!")
def getDirection(): c = getch() if c == 'w': return 1 elif c == 's': return 4 elif c == 'a': return 2 elif c == 'd': return 3 elif c == ' ': return 0
def user_input(board, current_group): """Get one character of the user's input without echoing to the screen, then take the appropriate action. Return True if move was made """ s = getch() if s in map(str, range(1, 7)): paint_cells(board, current_group, s) return True elif s == 'q': sys.exit('Goodbye') return False
def cmd_move(args=[]): if not mb.isConnected(): print("Machine not connected") return if len(args) == 3: mb.move(args[1], args[2]) else: print("Keys :") print(" keyboard arrows : move the tool") print(" A/Q : raise/lower the buildplate") print(" +/- : increase/decrease the step") fifo = [0, 0, 0] speed = 1000 step = 2 steps = [0.1, 0.5, 1, 2, 5, 10] while True: sys.stdout.write("\rstep : " + str(steps[step]) + "mm, X : " + str(mb.position['x']) + "mm, Y : " + str(mb.position['y']) + "mm, Z : " + str(mb.position['z']) + "mm ") mb.wait() key = ord(getch()) fifo[2] = fifo[1] fifo[1] = fifo[0] fifo[0] = key if key in [3, 13, 22]: #mb.stop() print("") break elif fifo[2] == 27 and fifo[1] == 91: # Escaping sequence if fifo[0] == 65: # Up mb.move(0, steps[step], speed=speed, relative=True) elif fifo[0] == 66: # Down mb.move(0, -steps[step], speed=speed, relative=True) elif fifo[0] == 67: # Right mb.move(steps[step], 0, speed=speed, relative=True) elif fifo[0] == 68: # Left mb.move(-steps[step], 0, speed=speed, relative=True) elif key in [ord("a"), ord("A")]: mb.moveZ(steps[step], speed=speed / 2, relative=True) elif key in [ord("q"), ord("Q")]: mb.moveZ(-steps[step], speed=speed / 2, relative=True) elif key == ord("+"): if step < len(steps) - 1: step += 1 elif key == ord("-"): if step > 0: step -= 1
def ask_dir(): getch = _GetchWindows() d = getch() if d == b"w": return 1 elif d == b"s": return 2 elif d == b"a": return 3 elif d == b"d": return 4 else: return -1
def promtForNote(): #The drawNotes function can only handel certain notes, so we have to limit the selection. possibleNotes = [ 'E,2', 'F,2', 'G,2', 'A,2', 'B,2', 'C,3', 'D,3', 'E,3', 'F,3', 'G,3', 'A,3', 'B,3', 'C,4', 'D,4', 'E,4', 'F,4', 'G,4', 'A,4', 'B,4', 'C,5', 'D,5', 'E,5', 'F,5', 'G,5', 'A,5' ] randomNote, randomOctave = random.choice(possibleNotes).split( ',') #Break the note, octave pair apart. randomOctave = int(randomOctave) notesToPrint = [] notesToPrint.append(note(randomNote, randomOctave, 'natural', 'green')) drawNotes(notesToPrint) #Function with all the fun ACSII art. notesToPrint.clear() print('What note is this? ', end="", flush=True) answer = getch().upper() print(answer, end="", flush=True) correctAnswer = False answerCount = 0 while not correctAnswer: if answer == 'Q': return 0 elif answer == randomNote: correctAnswer = True print("") return 1 + answerCount else: CURSOR_UP_ONE = '\x1b[1A' #These two strings manipulate the terminal we're drawing to. ERASE_LINE = '\x1b[2K' #Second string answerCount += 1 print(CURSOR_UP_ONE, end="\n", flush=True) print('Wrong!! Try again! ', end="", flush=True) answer = getch().upper() print(answer, end="", flush=True)
def next_direction(self): # pip install py-getch import getch while True: from getch.getch import getch if self.stdout != sys.stdout: print self.current_board where = getch() if where in HumanGameStrategy.KEYS: return HumanGameStrategy.KEYS[where] if where in ('e','q'): raise Exception("Finish requested by user")
def fight(): print("Go...") k0 = getch() k1 = getch() s0 = taste_zu_spieler(k0) s1 = taste_zu_spieler(k1) if s0 >= 0 and s1 >= 0 and s0 != s1: obj0 = taste_zu_objekt(k0) obj1 = taste_zu_objekt(k1) if s0 == 1: swap = obj1 obj1 = obj0 obj0 = swap print(" {0} {1}".format( spieler[0], spieler[1])) print(" # {0} # # {1} #".format( objekte[obj0], objekte[obj1])) s = auswertung(obj0, obj1) if s >= 0: ga = None if s == 0: ga = gewinn_aktion(obj0, obj1) else: ga = gewinn_aktion(obj1, obj0) print(" __{0}__ hat gewonnen, denn {1}".format( spieler[s], ga)) else: print(" UNENTSCHIEDEN") else: print("!Ungültig!")
def printy(thing): print('1. Buy reinforced {} 100$'.format(thing)) print('2. Buy improved {} 1000$'.format(thing)) print('3. Buy advanced {} 5000$'.format(thing)) print('4. Buy military class 20000$ {}'.format(thing)) print('0. Return') char = getch().lower() print(char) if char == 0: buy_upgrades() elif char in range(4): buy_fuel_tank(char) else: printy(thing)
def get_choice(available, special=None): print "\n Selection: ", while True: choice = getch() if special is not None and choice == special: print logger.debug("Selected option: %s" % choice) return special elif choice in available or choice == 'q' or choice == 'Q': if choice == '0' or choice == 'q' or choice == 'Q': print logger.debug("Selected option: 0") return '0' else: print logger.debug("Selected option: %s" % choice) return choice
def printy(self, thing): system('clear') print('1. Buy reinforced {} 100$'.format(thing)) print('2. Buy improved {} 1000$'.format(thing)) print('3. Buy advanced {} 5000$'.format(thing)) print('4. Buy military class {} 20000$ '.format(thing)) print('0. Return') char = getch() print(char) if char == '0': self.buy_upgrades() return 0 elif char in ['1', '2', '3', '4']: return (char) else: self.printy(thing) return 0
def navigate(self): self.isRunning = True while(self.isRunning): ch = getch() try: cmdTuple = self.keyMap[ch] self.execCommand(*cmdTuple) except KeyError: pass self.bot.brake()
def remote_input(remote): print "Current Remote: " + remote.name print "w for help; q to exit" commands = Controller.commands # Dictionary holding possible commands while 1: # Take commands till exit key = getch() if key == 'q': break if key == 'w': print print "Key - Command" for keys, values in commands.items(): print keys + " -- " + values[values.index('/') + 1:] for keys, values in commands.items(): if keys == key: thread = Controller(remote, values) thread.start()
def menu(self): print('1. Sell all') print('2. Refill') print('3. Buy upgrades') print('0. Return') char = getch() if char == '1': self.sell() object_game.console(print=True) if char == '2': temp = self.player.fuel_tank.size - self.player.fuel_tank.fuel_amount self.player.money -= 2 * temp self.player.fuel_tank.fuel_amount = self.player.fuel_tank.size self.player.money = int(self.player.money) object_game.console(print=True) if char == '3': self.buy_upgrades() if char == '0': object_game.console(print=True)
def talker(): pub = rospy.Publisher('/mobile_base/commands/velocity', Twist, queue_size=1) rospy.init_node('keyboard_inputs_node', anonymous=True) linspeed = rospy.get_param("linspeed", default=0.1) msg = Twist() while not rospy.is_shutdown(): char = getch() #retrieves the value of the pressed key. linspeed = rospy.get_param("linspeed", default=0.1) # We ask the robot to do different movements accordingly to the pressed key. if char in [ str(x) for x in range(1, 10) ]: # If the key is 1-9 we set up the linear speed accordingly. new_linspeed = float(char) / 10 rospy.set_param("linspeed", new_linspeed) rospy.set_param("fwd_linear_speed_x", new_linspeed) rospy.set_param("bckwd_linear_speed_x", -new_linspeed) elif char == 't' or char == 'T': # If the key is 'T' (or 't') we ask the robot to go straight forward at the set up linear speed. msg.linear.x = rospy.get_param("fwd_linear_speed_x", default=0.0) msg.angular.z = rospy.get_param("fwd_angular_speed_z", default=0.0) rospy.loginfo(msg) pub.publish(msg) elif char == 'g' or char == 'G': # If the key is 'G' (or 't') we ask the robot to go backward at the set up linear speed. msg.linear.x = rospy.get_param("bckwd_linear_speed_x", default=0.0) msg.angular.z = rospy.get_param("bckwd_angular_speed_z", default=0.0) rospy.loginfo(msg) pub.publish(msg) elif char == 'h' or char == 'H': # If the key is 'H' (or 'h') we ask the robot to do a clockwise rotation at 0.5 m/s of angular speed. msg.linear.x = rospy.get_param("clw_linear_speed_x", default=0.0) msg.angular.z = rospy.get_param("clw_angular_speed_z", default=0.0) rospy.loginfo(msg) pub.publish(msg) elif char == 'f' or char == 'F': # If the key is 'F' (or 'f') we ask the robot to do a counter-clockwise rotation at 0.5 m/s of angular speed. msg.linear.x = rospy.get_param("counclw_linear_speed_x", default=0.0) msg.angular.z = rospy.get_param("counclw_angular_speed_z", default=0.0) rospy.loginfo(msg) pub.publish(msg)
def buy_upgrades(): print('1. Buy fuel_tank') print('2. Buy cargo_bay') print('3. Buy engine') print('4. Buy drill') print('5. Buy hull') print('0. Return') char = getch().lower() if char == 1: printy('fuel_tank') elif char == 2: printy('cargo_bay') elif char == 3: printy('engine') elif char == 4: printy('drill') elif char == 5: printy('hull') elif char == 0: menu() else: buy_upgrades()
def loop(prevtime): text = getch() gettime = time.time() if gettime - prevtime < bomberman_time\ and text in ['w', 'a', 's', 'd']: return prevtime if text == 'q': sys.exit(0) elif text == 'w': bomb1.moveUp(a, self.score) elif text == 's': bomb1.moveDown(a, self.score) elif text == 'a': bomb1.moveLeft(a, self.score) elif text == 'd': bomb1.moveRight(a, self.score) elif text == 'b' and bombact.flag == 0: self.t = 3 bombact.time = 3 bombact.flag = 1 a[bomb1.posx][bomb1.posy] = 5 for i in enemies: i.moveenemy(a, self.score, enemy_time) if bombact.flag == 1 or bombact.flag == 2: bombact.checkexplode(a, bomb1.posx, bomb1.posy) # if t == 2: # bombact.time -= 1 if bombact.time == 0 and bombact.flag == 1: self.score = bombact.\ explode(a, enemies, bomb1.posx, bomb1.posy, self.score) bombact.time = 1 if bombact.time == 0 and bombact.flag == 2: self.score = bombact.\ explode(a, enemies, bomb1.posx, bomb1.posy, self.score) bombact.time = 3 os.system('clear') print("You are at Level:", level_number) bomber.printboard(self.score, a, bombact.time) return gettime
def getpass(label): print label, passwor = '' while True: inp = getch() if inp == '\n': break elif inp == '\x7f': print "\033[2K\033[1A" del passwor passwor = '' print label, elif inp == '\003': raise KeyboardInterrupt elif inp == '\04': raise EOFError else: sys.stdout.write(set_echo) passwor += inp print "\n", return passwor
print("") print("Es gelten folgende Tasten:") print("") print("{0} = {1} {2} = {3}".format( tasten[0][0], objekte[0], tasten[1][0], objekte[0])) print("{0} = {1} {2} = {3}".format( tasten[0][1], objekte[1], tasten[1][1], objekte[1])) print("{0} = {1} {2} = {3}".format( tasten[0][2], objekte[2], tasten[1][2], objekte[2])) print("") print( "Tastentest \n - Jeder Spieler drückt seine Tasten (gerne auch ungültige Tasten):" ) print(" - Q zum Beenden") print("") while True: k = getch() s = taste_zu_spieler(k) if s >= 0: o = taste_zu_objekt(k) print("Die Taste gehört zum {0} von {1}".format( objekte[o], spieler[s])) else: print("Taste: " + k) if k == 'q': print("Beenden...") break
def InterfaceKeyboard(): # Input data global pose, laser_position_count # Output data global setpoint, yawSetPoint, run, position_control # Publishers global arming_client, set_mode_client what = getch() if what == "t": setpoint.x = setpoint.x - 0.1 if what == "g": setpoint.x = setpoint.x + 0.1 if what == "f": setpoint.y = setpoint.y - 0.1 if what == "h": setpoint.y = setpoint.y + 0.1 if what == "i": setpoint.z = setpoint.z + 0.1 if what == "k": setpoint.z = setpoint.z - 0.1 if what == "b": yawSetPoint = yawSetPoint + 1 if what == "n": yawSetPoint = yawSetPoint - 1 if what == "c": setpoint.x = pose.pose.position.x setpoint.y = pose.pose.position.y setpoint.z = pose.pose.position.z if what == "p": setpoint.x = pose.pose.position.x setpoint.y = pose.pose.position.y position_control = True if what == "l": position_control = False if what == "q": arming_client(False) if what == "a": arming_client(True) if what == "e": set_mode_client(custom_mode="OFFBOARD") if what == "m": run = False time.sleep(1) exit() Q = (pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w) euler = tf.transformations.euler_from_quaternion(Q) rospy.loginfo("MODE POSITION: ") rospy.loginfo("true" if position_control else "false") rospy.loginfo("Positions sent : %i", ) rospy.loginfo("Position x: %s y: %s z: %s", pose.pose.position.x, pose.pose.position.y, pose.pose.position.z) rospy.loginfo("Setpoint is now x:%s, y:%s, z:%s", setpoint.x, setpoint.y, setpoint.z) rospy.loginfo("IMU :") rospy.loginfo("roll : %s", rad2degf(euler[0])) rospy.loginfo("pitch : %s", rad2degf(euler[1])) rospy.loginfo("yaw : %s", rad2degf(euler[2])) rospy.loginfo("wanted yaw : %s", yawSetPoint)
cp.append('%s/lucene/build/core/classes/java' % LUCENE_HOME) cp.append('%s/lucene/build/suggest/classes/java' % LUCENE_HOME) cp.append('%s/lucene/build/analysis/common/classes/java' % LUCENE_HOME) cp.append('%s/lucene/build/analysis/icu/classes/java' % LUCENE_HOME) cp.append('%s/lucene/analysis/icu/lib/icu4j-49.1.jar' % LUCENE_HOME) cmd = 'java -Xmx3g -cp %s FreeDBSuggest %s -server' % (':'.join(cp), sys.argv[1]) p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) print p.stdout.readline().strip() getch = getch._Getch() query = [] while True: c = getch() if c == '': break if c == '\r': break elif c == '\x7f': query = query[:-1] else: query.append(c) q = ''.join(query) t0 = time.time() p.stdin.write('%2d' % len(q)) p.stdin.write(q) x = int(p.stdout.read(5)) result = p.stdout.read(x)
def main(): while True: print("All levels :") os.system( "ls ./levels/ | grep -oP '^((?!Enemy).)*$' | sed -e 's/\.txt$//'" ) print() print("Enter level : ", end='') levelname = input() try: level = Level(0, 0, "./levels/" + levelname + ".txt") break except FileNotFoundError: print( "Level does not Exist!\nCreate your level by command 'python3 levelGenerator.py'" ) mario = Mario(3, 2, 10, "./designs/mario1.txt", "./designs/mario2.txt", "./designs/mario3.txt") mario.cannotCross = ['T', '|', '/', '\\', '`'] lives = Element(3, 0) coins = Element(26, 0) kills = Element(49, 0) score = Element(72, 0) boss = Boss(10, 277, 12, "./designs/boss.txt") boss.design[0] = boss.health boss.cannotCross = ['T', '|', '/', '\\', '`'] enemies = [boss] try: file = open("./levels/" + levelname + "Enemy.txt", "r") for line in file: goomba = eval(line) goomba.cannotCross = ['T', '|', '/', '\\', '`'] enemies.append(goomba) except: pass while True: if mario.x == 321: mario.cannotCross = ['T'] winTime = time.time() if mario.x == 379: print("YOU WIN!!!") break mario.gravity(level) # moving of all the enemies and missile collision index = 0 for enemy in enemies: enemy.gravity(level) enemy.move(level) mario.kill(enemy, level) for missile in mario.missiles: missile.attack(enemy) if enemy.life <= 0: del (enemies[index]) mario.kills += 1 index += 1 # moving of all the missiles index = 0 for missile in mario.missiles: if not missile.moveRight( level ) or missile.life <= 0 or missile.x > level.pos + 80: del (mario.missiles[index]) index += 1 # moving of all the fires if level.pos > 200: if boss.life > 0: boss.attack() index = 0 for fire in boss.fires: fire.attack(mario) if not fire.moveLeft( level) or fire.life <= 0 or fire.x < boss.x - 70: del (boss.fires[index]) index += 1 boss.design[0] = boss.health[:boss.life + 2] lives.design = ["LIVES", str(mario.life)] coins.design = ["COINS", str(mario.coins)] kills.design = ["KILLS", str(mario.kills)] score.design = [ "SCORE", str(mario.kills * 50 + mario.coins * 10 + level.pos) ] lives.x = level.pos + 3 coins.x = lives.x + 23 kills.x = coins.x + 23 score.x = kills.x + 23 # os.system("clear") level.printOnTop(mario, *enemies, *mario.missiles, *boss.fires, lives, coins, kills, score) if mario.life <= 0: print("GAME OVER") break choice = getch() if choice is 'a': if mario.x > level.pos: mario.moveLeft(level) elif choice is 'd': if mario.x < level.pos + (40) - mario.width: mario.moveRight(level) else: if mario.moveRight(level): level.pos += 1 elif choice is 'w': if mario.velocity is 0: mario.velocity = 20 elif choice is 'f': mario.attack() elif choice is 'h': level.pos += 5 mario.spawn(level) elif choice is 'q': break
def InterfaceKeyboard(): # Input data global pose, laser_position_count # Output data global setpoint, yawSetPoint, run, position_control # Publishers global arming_client, set_mode_client what = getch() if what == "t": setpoint.x = setpoint.x - 0.1 if what == "g": setpoint.x = setpoint.x + 0.1 if what == "f": setpoint.y = setpoint.y - 0.1 if what == "h": setpoint.y = setpoint.y + 0.1 if what == "i": setpoint.z = setpoint.z + 0.1 if what == "k": setpoint.z = setpoint.z - 0.1 if what == "b": yawSetPoint = yawSetPoint + 1 if what == "n": yawSetPoint = yawSetPoint - 1 if what == "c": setpoint.x = pose.pose.position.x setpoint.y = pose.pose.position.y setpoint.z = pose.pose.position.z if what == "p": setpoint.x = pose.pose.position.x setpoint.y = pose.pose.position.y position_control = True if what == "l": position_control = False if what == "q": arming_client(False) if what == "a": arming_client(True) if what == "e": set_mode_client(custom_mode = "OFFBOARD") if what == "m": run = False time.sleep(1) exit() Q = ( pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w) euler = tf.transformations.euler_from_quaternion(Q) rospy.loginfo("MODE POSITION: ") rospy.loginfo("true" if position_control else "false") rospy.loginfo("Positions sent : %i", ) rospy.loginfo("Position x: %s y: %s z: %s", pose.pose.position.x, pose.pose.position.y, pose.pose.position.z) rospy.loginfo("Setpoint is now x:%s, y:%s, z:%s", setpoint.x, setpoint.y, setpoint.z) rospy.loginfo("IMU :") rospy.loginfo("roll : %s", rad2degf(euler[0])) rospy.loginfo("pitch : %s", rad2degf(euler[1])) rospy.loginfo("yaw : %s", rad2degf(euler[2])) rospy.loginfo("wanted yaw : %s", yawSetPoint)
spieler2 = "Lea" spieler = [ spieler1, spieler2 ] print("Spieler 1 Spieler 2") print("{0} {1}".format(spieler[0], spieler[1])) print("") print("Es gelten folgende Tasten:") print("") print("{0} = {1} {2} = {3}".format(tasten[0][0], objekte[0], tasten[1][0], objekte[0])) print("{0} = {1} {2} = {3}".format(tasten[0][1], objekte[1], tasten[1][1], objekte[1])) print("{0} = {1} {2} = {3}".format(tasten[0][2], objekte[2], tasten[1][2], objekte[2])) print("") print("Tastentest \n - Jeder Spieler drückt seine Tasten (gerne auch ungültige Tasten):") print(" - Q zum Beenden") print("") while True: k = getch() s = taste_zu_spieler(k) if s >= 0: o = taste_zu_objekt(k) print("Die Taste gehört zum {0} von {1}".format(objekte[o], spieler[s])) else: print("Taste: " + k) if k == 'q': print("Beenden...") break
def main(args): if len(args) < 2: while True: try: size = int(raw_input('What size of board would you like to play?\n> ')) break except NameError: print 'Please enter a number.' # Add 1 if even size += not size % 2 board = [] for i in range(size): board.append([]) for j in range(size): board[-1].append(random.choice('123456')) else: with open(args[1]) as f: board = boardformat(f.read()) # Ensure that the input is a square with odd dimensions if len(set(map(len, board) + [len(board)])) != 1: sys.exit('Error: The board must be square.') if not len(board) % 2: sys.exit('Error: The board must have odd dimensions.') sys.stdout.write('\033[2J') moves = 0 unsolved = [b[:] for b in board] try: solution = ai_solve(board) except RuntimeError: solution = '' # Game loop while True: if colour: sys.stdout.write('\033[H') else: os.system('cls') # Non-ansi way to clear screen if solution: print 'The computer solved it in {} moves.'.format(len(solution)) print 'Can you do better?' else: print 'The computer isn\'t smart enough to solve a board this large.' print 'You\'re welcome to try, though!' print boardstring(board) current_group = adjacent_equal(board) print textwrap.dedent("""\ Moves: {} Matched: {}% """.format( moves, len(current_group)/(len(board)**2)*100)) # Break when every cell is the same if len(set(sum(board, []))) == 1: break moves += user_input(board, current_group) print 'Congratulations!' print print 'You solved the puzzle in {} moves.'.format(moves) if not solution: sys.exit() print 'The computer solved it in {} moves.'.format(len(solution)) print 'Your solution was {} moves {}.'.format( abs(moves - len(solution)), 'faster' if moves <= len(solution) else 'slower') print print 'Press any key to watch the computer\'s solution.' getch() if colour: sys.stdout.write('\033[2J\033[H') else: os.system('cls') # Non-ansi way to clear screen board = unsolved for m in solution: if colour: sys.stdout.write('\033[H') else: os.system('cls') # Non-ansi way to clear screen print boardstring(board) time.sleep(0.5) paint_cells(board, adjacent_equal(board), m) if colour: sys.stdout.write('\033[H') else: os.system('cls') # Non-ansi way to clear screen print boardstring(board)
def winGame(self): print "You win! (R)eset, (U)ndo, (Q)uit?" while True: g = getch().upper() if g in "RUQ": return g
def fight(tasten, spieler, objekte, punkte, bilder): print("Go...") print("") k0 = getch() k1 = getch() s0 = taste_zu_spieler(tasten, k0) s1 = taste_zu_spieler(tasten, k1) if s0 >= 0 and s1 >= 0 and s0 != s1: obj = [ None, None ] obj[0] = taste_zu_objekt(tasten, k0) obj[1] = taste_zu_objekt(tasten, k1) if s0 == 1: swap = obj[1] obj[1] = obj[0] obj[0] = swap # obj0 gehört nun zu spieler0 # Cheat: other = [ obj[1], obj[0] ] for i in range(2): if obj[i] == 3: # Cheat-Taste if other[i] == 0: obj[i] = 1 elif other[i] == 1: obj[i] = 2 elif other[i] == 2: obj[i] = 0 else: obj[i] = 0 # beide haben geschummelt => unentschieden print("{0:40}{1:40}".format(spieler[0], spieler[1])) print("{0:40}{1:40}".format(" |", " |")) print("{0:40}{1:40}".format(" v", " v")) print("{0:40}{1:40}".format(objekte[obj[0]], objekte[obj[1]])) print("-" * 80) s = auswertung(obj[0], obj[1]) if s >= 0: if s == 0: print_bild(bilder, obj[0], 0) else: print_bild(bilder, obj[1], 40) # Punktestand anpassen punkte[s] = punkte[s] + 1 ga = None if s == 0: ga = gewinn_aktion(obj[0], obj[1]) else: ga = gewinn_aktion(obj[1], obj[0]) print(">> {0} hat gewonnen, denn {1}".format(spieler[s], ga)) else: print(">> UNENTSCHIEDEN") print(" Punktestand:") print("{0:40}{1:40}".format(spieler[0] + " ({0})".format(punkte[0]), spieler[1] + " ({0})".format(punkte[1]))) else: print("!Ungültig!")
def addPrimitives(): varEnv = Environment() varEnv.addBind("it", "Nothing") funEnv = Environment() # arithmetic funEnv.addBind("+", (numArrityTwo, operator.add, 2)) funEnv.addBind("-", (numArrityTwo, operator.sub, 2)) funEnv.addBind("*", (numArrityTwo, operator.mul, 2)) funEnv.addBind("/", (numArrityTwo, operator.div, 2)) funEnv.addBind("%", (numArrityTwo, operator.mod, 2)) funEnv.addBind("^", (numArrityTwo, operator.pow, 2)) funEnv.addBind("random", (numArrityTwo, randint, 2)) funEnv.addBind("!", (numArrityOne, math.factorial, 1)) funEnv.addBind("v/", (numArrityOne, math.sqrt, 1)) # booleans funEnv.addBind("and", (booleans, operator.and_, 2)) funEnv.addBind("or", (booleans, operator.or_, 2)) funEnv.addBind("xor", (booleans, operator.xor, 2)) funEnv.addBind("nand", (booleans, (lambda x, y: not (x and y)), 2)) funEnv.addBind("nor", (booleans, (lambda x, y: not (x or y)), 2)) funEnv.addBind("not", (boolNot, operator.not_, 1)) # comparison funEnv.addBind(">", (comparison, operator.gt, 2)) funEnv.addBind("<", (comparison, operator.lt, 2)) funEnv.addBind(">=", (comparison, operator.ge, 2)) funEnv.addBind("<=", (comparison, operator.le, 2)) funEnv.addBind("=", (equal_nequal, operator.eq, 2)) funEnv.addBind("<>", (equal_nequal, operator.ne, 2)) # range funEnv.addBind("range", (numArrityOne, (lambda x: range(x)), 1)) funEnv.addBind("rangeFrom", (numArrityTwo, (lambda x, y: range(x, y)), 2)) # lists funEnv.addBind("today", (arrityZero, (lambda: today()), 0)) funEnv.addBind("newList", (arrityZero, (lambda: []), 0)) funEnv.addBind("length", (listArrityOne, (lambda x: len(x)), 1)) funEnv.addBind("null?", \ (listArrityOne, (lambda x: "true" if len(x)==0 else "false"), 1)) funEnv.addBind("append", (append_push, (lambda val, ds: ds.append(val)), 2)) funEnv.addBind("push", (append_push, (lambda val, ds: ds.insert(0, val)), 2)) funEnv.addBind("get", (listGet, (lambda pos, ds: ds[pos - today()]), 2)) funEnv.addBind("put", (listPut, \ (lambda val,pos,ds: ds[:pos-today()]+[val]+ds[pos+1-today():] \ if pos-today()+1!=0 \ else ds[:pos-today()]+[val]), 3)) funEnv.addBind("init", (listInit, (lambda val, size: [val] * size), 2)) funEnv.addBind("insert", \ (listInsert, (lambda val,pos,ds: ds.insert(pos-today(),val)), 3)) funEnv.addBind("remove", (listRemove, (lambda pos,ds: ds[:pos-today()]+ds[pos+1-today():] \ if pos-today()+1!=0 \ else ds[:pos-today()]), 2)) # miscellaneous funEnv.addBind("seven", (arrityZero, (lambda: 7), 0)) funEnv.addBind("clear_screen", \ (arrityZero, (lambda: print("\033[H\033[J")), 0)) funEnv.addBind("exit", (arrityZero, (lambda: exit(0)), 0)) funEnv.addBind("wholesomeRemark", (happy, None, 0)) funEnv.addBind("++", (concat, operator.add, 2)) # casting funEnv.addBind("int", (numArrityOne, (lambda x: int(x)), 1)) funEnv.addBind("num", (castNum, \ (lambda x: int(float(x)) if int(float(x))==float(x) else float(x)), 1)) funEnv.addBind("bool", (castBool, None, 1)) funEnv.addBind("str", (castStr, (lambda x: "\"" + x + "\""), 1)) funEnv.addBind("list", (castList, (lambda x: "[" + str(x) + "]"), 1)) funEnv.addBind("nonetype", (castNonetype, None, 1)) # basic operations funEnv.addBind("print", (printVar, (lambda x: print(x)), 1)) funEnv.addBind("write", (printVar, (lambda x: sys.stdout.write(str(x))), 1)) funEnv.addBind("input", (userInput, (lambda x: raw_input(x)), 1)) funEnv.addBind("getch", (getChar, (lambda: getch()), 0)) funEnv.addBind("val", (defineVar, None, 2)) funEnv.addBind("check-error", (check_error, None, 1)) funEnv.addBind("check-expect", (check_expect, None, 2)) funEnv.addBind("empty", (empty, None, 0)) funEnv.addBind("if", (conditional, None, 3)) funEnv.addBind("ifTrue", (condArrityTwo, (lambda: True), 2)) funEnv.addBind("ifFalse", (condArrityTwo, (lambda: False), 2)) funEnv.addBind("while", (wloop, None, 2)) funEnv.addBind("for", (floop, None, 4)) # second argument is the "in" keyword funEnv.addBind("claim", (claim, None, 1)) return (varEnv, funEnv)
ugly and hard to play. The final option is to press any key other than 'c', quit the game and install the colorama python module. This module is designed to allow ANSI codes to be used on systems that don't natively support them. The module can be found here: https://pypi.python.org/pypi/colorama If you really want to play this game, I'd reccomend this. The colours really are worth it. (c)ontinue? """) colour = False if getch() != 'c': sys.exit() def boardformat(board): """Return the board converted to a list of rows, with non-digits and empty lines stripped """ return [filter(str.isdigit,list(row)) for row in board.split('\n') if row] def boardstring(board): """Return a string representing the board in a human-friendly way""" if colour: # Keys = strings reperesenting ints 1-6 # Values = ANSI colour code for that number colour_dict = {