Pierre Surply avatar Pierre Surply committed 9dd5f41

basic: Added interruptions and keyboard events

Comments (0)

Files changed (7)

-Basic-robots
+BASIC-RoBots
 ============
 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ##
 ## Started on  Wed May  9 17:54:23 2012 Pierre Surply
-## Last update Wed Aug  1 17:48:08 2012 Pierre Surply
+## Last update Sun Aug 12 16:44:39 2012 Pierre Surply
 ##
 
 import pygame

src/robot/basic.py

 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ## 
 ## Started on  Sat May  5 13:04:41 2012 Pierre Surply
-## Last update Sat Aug 11 19:15:50 2012 Pierre Surply
+## Last update Thu Aug 16 18:44:53 2012 Pierre Surply
 ##
 
 import random
 import time
 
+KeyInterrupt =  0
+KeyPressed =    1
+
 class Basic:
     func = {"rand" : (lambda: random.randint(0, 255)),\
                 "time" : (lambda: int(time.time()) % 256)}
-    def __init__(self, current_dir, src, mem, mem_ro, robot, terminal):
+    def __init__(self, current_dir, src, robot, terminal):
         self.current_dir = current_dir
         self.src = src
         self.terminal = terminal
-        self.mem = mem
-        self.mem_stack = robot.mem_stack
-        self.mem_ro = mem_ro
         self.robot = robot
+        self.mem = robot.mem
+        self.mem_stack = robot.mem_stack
         self.ext_cmd = self.robot.ext_cmd
         self.callstack = []
         self.whilestack = []
     def read(self, var, line):
         if var in self.mem:
             if not self.terminal.act_prompt:
-                self.terminal.start_prompt("?")
+                self.terminal.start_prompt(var + "?")
             cmd = self.terminal.prompt()
             if cmd != None:
                 try:
     def set_mem(self, var, val, line):
         if var in self.mem:
             self.mem[var] = val
+            self.mem["O"] = 0
             if self.mem[var] > 255:
-                self.mem[var] = 255
+                self.mem[var] %= 0x100
+                self.mem["O"] = 1
             elif self.mem[var] < 0:
                 self.mem[var] = 0
+                self.mem["O"] = 1
             return line
         else:
             return self.raise_error_reg(var, line)
     def goto_label(self, label, line):
         return self.goto(label, "LABEL", line)
 
-    def goto(self, label, cmd, line):
+    def goto_interrupt(self, label, line):
+        return self.goto(label, "LABEL", line, False)
+
+    def goto(self, label, cmd, line, verb=True):
         i = 0
         while i < len(self.opr) and\
                 (len(self.opr[i]) < 1  or \
             i += 1
         if i < len(self.opr):
             return i
+        elif verb:
+            return self.raise_error("The " + cmd.lower() + " \"" + label +"\" can not be found", line)
         else:
-            return self.raise_error("The " + cmd.lower() + " \"" + label +"\" can't be found", line)
+            return -1
 
+    def interrupt(self, interrupt):
+        new_line = self.line
+        if interrupt == KeyInterrupt:
+            new_line = self.goto_interrupt(":KeyInterrupt", self.line)
+        elif interrupt == KeyPressed:
+            new_line = self.goto_interrupt(":KeyPressed", self.line)
+        if new_line != -1:
+            self.line = new_line
+        elif interrupt == KeyInterrupt:
+            self.terminal.write_line("Killed")
+            self.line = len(self.opr)
+            
     def alt(self, opr, line):
         boolean = []
         label_then = ""
     def eval_exp(self, exp, line):
         try:
             return int(eval(exp, {"__builtins__":None}, dict(self.mem, \
-                                                                 **dict(self.func, **self.mem_ro))))
+                                                                 **dict(self.func, **self.robot.get_mem_ro()))))
         except:
             self.raise_warning("Invalid Expression", line)
             return 0
     def call(self, function, reg, line):
         if function in self.ext_cmd:
             if reg == None:
-                self.ext_cmd[function][0]()
+                self.robot.run_ext_cmd(self.ext_cmd[function][0], \
+                                           self.ext_cmd[function][3])
                 return line
             else:
                 return self.set_mem(reg, self.robot.run_ext_cmd(self.ext_cmd[function][0], \

src/robot/robot.py

 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ## 
 ## Started on  Sun Jul  1 15:34:10 2012 Pierre Surply
-## Last update Sat Aug 11 20:24:15 2012 Pierre Surply
+## Last update Thu Aug 16 18:37:05 2012 Pierre Surply
 ##
 
 import os
 import random
+from collections import deque
+from pygame.locals import *
 
 import robotsos
+import basic
 import inventory
 
 class Robot:
         self.world = world
         self.events = events
         self.cannot_move = [2, 4, 6]
-        self.energy = 255
-        self.shield = 255
+        self.energy = 0xFF
+        self.shield = 0xFF
+        self.keys = 0
         self.inv = inventory.Inventory("saves/"+self.world+"/robots/"+self.name+"/inv", 10000)
         if new:
             self.new()
         self.mem = {"A" : 0,\
                         "B" : 0,\
                         "C" : 0,\
-                        "D" : 0}
+                        "D" : 0,\
+                        "O" : 0}
         self.mem_stack = []
+        self.msg_recv = deque([])
         self.ext_cmd = {"forward" : (self.forward, \
                                          "Move the robot forward", \
                                          "1 if the robot can move, 0 otherwise",\
                                          "Give an item from inventory to other robot",\
                                          "1 if the item is given, 0 otherwise",\
                                          (0, []),\
-                                         {"A" : "item id"})}
+                                         {"A" : "item id"}),\
+                            "sendmsg": (self.sendmsg, \
+                                         "Send a message (1 byte) to all robots in a small area",\
+                                         "Number of robots which received the message",\
+                                         (5, []),\
+                                         {"A" : "message"}),\
+                            "recvmsg": (self.recvmsg, \
+                                         "Read a message sent by other robot",\
+                                         "Content of the message if received, 0 otherwise ",\
+                                         (0, []),\
+                                         {})}
         self.os = robotsos.RoBotsOS(self, "saves/"+world+"/robots/"+self.name+"/fs", \
                                         self.mem, \
                                         events)
     def get_pos(self):
         return (self.pos_x, self.pos_y)
 
+    def get_mem_ro(self):
+        return {"SH" : self.shield,\
+                    "EN" : self.energy,\
+                    "OR" : self.orient,\
+                    "X" : self.pos_x,\
+                    "Y" : self.pos_y, \
+                    "K" : self.keys}
+
     def update(self, selected, display, events):
+        if selected:
+            self.handle_events(events)
         self.os.update(selected, display, events)
 
+    def handle_events(self, events):
+        if events.key[K_LCTRL]:
+            if events.key[K_LALT] and \
+                    events.get_key_once(K_r):
+                self.os = robotsos.RoBotsOS(self, "saves/"+self.world+"/robots/"+self.name+"/fs", \
+                                            self.mem, \
+                                            events)
+            if self.os.task == 1 and events.get_key_once(K_c):
+                self.os.basic.interrupt(basic.KeyInterrupt)
+
+        if self.os.task == 1:
+            keys = self.keys
+            self.keys = int(events.key[K_1]) | \
+                int(events.key[K_2]) << 1 | \
+                int(events.key[K_3]) << 2 | \
+                int(events.key[K_4]) << 3 | \
+                int(events.key[K_5]) << 4 | \
+                int(events.key[K_6]) << 5 | \
+                int(events.key[K_7]) << 6 | \
+                int(events.key[K_8]) << 7
+            if keys < self.keys:
+                self.os.basic.interrupt(basic.KeyPressed)
+
     def save_pos(self):
         f = open("saves/"+self.world+"/robots/"+self.name+"/pos", 'w')
         buf = str(self.pos_x) + "-" + str(self.pos_y) + "-" + str(self.orient)
                 i.add_item(id_item, qty)
                 return 1
         return 0
+
+    def sendmsg(self):
+        msg = self.mem["A"]
+        nbr_robots = 0
+        for i in self.env.robots:
+            if (i.pos_x != self.pos_x  or i.pos_y != self.pos_y):
+                i.msg_recv.append(msg)
+                nbr_robots += 1
+        return nbr_robots
+
+    def recvmsg(self):
+        if len(self.msg_recv) > 0:
+            return self.msg_recv.popleft()
+        else:
+            return 0

src/robot/robotsos.py

 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ##  
 ## Started on  Wed May  9 22:56:00 2012 Pierre Surply
-## Last update Sun Aug 12 10:14:56 2012 Pierre Surply
+## Last update Thu Aug 16 18:18:08 2012 Pierre Surply
 ##
 
 import os
                            ("inv", "", "list inventory", lambda o, a: o.ls_inv(a)),\
                            ("let", "REG VALUE", "set register value", lambda o, a: o.let(a)),\
                            ("stack", "", "print stack", lambda o, a: o.stack(a)),\
+                           ("tree", "", "", lambda o, a: o.tree(a)),\
                            ("clear", "", "clear screen", lambda o, a: o.clear(a))])
         if self.robot.energy > 0:
             self.welcome(None)
-        self.terminal.start_prompt(">")
+        self.start_prompt()
         self.task = 0
 
     def get_path(self, path):
         return self.path + path
 
-    def get_short_path(self):
-        return self.current_dir.split("/")[-2]
+    def start_prompt(self):
+        self.terminal.start_prompt(self.current_dir.split("/")[-2] + "\xaf")
 
     def set_cmds(self, cmds):
         self.cmds = []
                         if i != "":
                             self.command(i)
                     if self.task == 0 and self.robot.energy > 0:
-                        self.terminal.start_prompt(self.get_short_path() + ">")
-                info = (self.mem, 10)
+                        self.start_prompt()
+                info = (self.mem, 8)
             elif self.task == 1:
-                if not self.basic.eval_line() or \
-                        (selected and events.key[K_LCTRL] and \
-                             events.get_key_once(K_c)):
+                if not self.basic.eval_line():
                     self.task = 0
                     if self.robot.energy > 0:
-                        self.terminal.start_prompt(self.get_short_path() + ">")
-                info = (self.mem, 10)
+                        self.start_prompt()
+                info = (self.mem, 8)
             elif self.task == 2 and selected:
                 if not self.terminal.edit(self, h):
                     self.task = 0
-                    self.terminal.start_prompt(self.get_short_path() + ">")
+                    self.start_prompt()
                 info = ({"CTRL+S" : "Save", \
                              "CTRL+C" : "Close"}, 15)
         else:
                 found = True
         if not found:
             if cmd[0] in self.ext_cmd:
-                self.robot.run_ext_cmd(self.ext_cmd[cmd[0]][0], \
+                ret = self.robot.run_ext_cmd(self.ext_cmd[cmd[0]][0], \
                                            self.ext_cmd[cmd[0]][3])
+                if ret != None:
+                    self.terminal.write_line(cmd[0] + "\x1a " + str(ret))
                 found = True
         if not found and cmd[0] != "":
             self.terminal.write_line("'" + cmd[0] + "' : command not found")
             self.terminal.write("  ")
             self.terminal.write(i, 1)
             self.terminal.write(": " + hex(self.robot.mem[i]))
-        self.terminal.write_line("")
-        
+        self.terminal.write_line("")        
 
     def help(self, arg):
         if len(arg) > 0:
                 f = open(self.get_path(self.current_dir) + arg[0], 'r')
                 self.basic = basic.Basic(self.get_path(self.current_dir),\
                                              f.read(), \
-                                             self.mem,\
-                                             {"SH" : self.robot.shield,\
-                                                  "EN" : self.robot.energy,\
-                                                  "X" : self.robot.pos_x,\
-                                                  "Y" : self.robot.pos_y},\
                                              self.robot,\
                                              self.terminal)
                 f.close()
     def let(self, arg):
         self.basic = basic.Basic(self.get_path(self.current_dir),\
                                      "LET " + " ".join(arg), \
-                                     self.mem,\
-                                     {"SH" : self.robot.shield,\
-                                          "EN" : self.robot.energy,\
-                                          "X" : self.robot.pos_x,\
-                                          "Y" : self.robot.pos_y},\
                                      self.robot,\
                                      self.terminal)
         self.task = 1
             for i in self.robot.mem_stack:
                 self.terminal.write("|" + hex(i))
             self.terminal.write_line(" <-")
+
+    def tree(self, arg):
+        self.rec_tree(True, 0, self.get_path(self.current_dir))
+
+    def rec_tree(self, last, dec, path):
+        self.terminal.write_line(path.split("/")[-2], 4)
+        if last:
+            c = "   "
+        else:
+            c = "\xb3  "
+        l = os.listdir(path)
+        if len(l) > 0:
+            for i in range(len(l)-1):
+                if os.path.isdir(path+l[i]):
+                    self.terminal.write(c * dec + "\xc3\xc4\xc4")
+                    self.rec_tree(False, dec+1, path+l[i]+"/")
+                else:
+                    self.terminal.write_line(c * dec + "\xc3\xc4\xc4" + l[i])
+            if os.path.isdir(path+l[-1]):
+                self.terminal.write(c * dec + "\xc0\xc4\xc4")
+                self.rec_tree(True, dec+1, path+l[-1]+"/")
+            else:
+                self.terminal.write_line(c * dec + "\xc0\xc4\xc4" + l[-1])

src/robot/thermalpowerstation.py

 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ## 
 ## Started on  Mon Jul 23 11:55:10 2012 Pierre Surply
-## Last update Sat Aug 11 22:09:28 2012 Pierre Surply
+## Last update Thu Aug 16 12:23:48 2012 Pierre Surply
 ##
 
 import robot
         return 0
 
     def disten(self):
+        nbr_robots = 0
         for i in self.env.robots:
             if ((i.pos_x - self.pos_x) ** 2 + \
                     (i.pos_y - self.pos_y) ** 2 < 100) and \
                     i.energy < 0xFF:
                 i.incr_energy(1)
                 self.incr_energy(-1)
+                nbr_robots += 1
+        return nbr_robots
 ##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
 ## 
 ## Started on  Wed May  9 18:57:29 2012 Pierre Surply
-## Last update Sun Aug 12 10:27:12 2012 Pierre Surply
+## Last update Sun Aug 12 17:00:28 2012 Pierre Surply
 ##
 
 import time
                 else:
                     val = str(info_bottom[0][i])
                 self.display_line(display, \
-                                      self.str2charlist(i+": "+val, 1), (org_x+x, h))
+                                      self.str2charlist(i+":"+val, 1), (org_x+x, h))
                 x += info_bottom[1]
         if info_top != None:
             x = w-16
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.