13 Commits
4 changed files with 105 additions and 39 deletions
+53 -11
View File
@@ -1,29 +1,67 @@
from helpers import *
import threading
import time
calc_users = open_json_file("calc", [])
math_operators = ["+", "-", "*", "/", "&", "|"]
ignore_operators = ["**", "&&", "||"] # ** may be too intensive, the others cause syntax errors
math_operators = ["+", "-", "*", "/", "%", ">", "<", "^", "&", "|"]
allowed_strings = ["0b", "0x", "(", ")", "hex(", "bin(", "abs(", "int(", "min(", "max(", "round(", "float("]
allowed_alpha = ["a", "b", "c", "d", "e", "f"]
calc_perm = "utils.calc"
calc_perm_power = "utils.calc.power"
def calc(text):
def calc(sender, text):
"""
extracts a mathematical expression from `text`
returns (expression, result) or None
"""
expression = ""
should_calc = False
for char in text:
if char.isdigit() or (expression and char == ".") or (should_calc and char == " "):
i = 0
while True:
if i >= len(text):
break
char = text[i]
if i < len(text) - 5 and str(char + text[i+1] + text[i+2] + text[i+3] + text[i+4] + text[i+5]) in allowed_strings:
expression += char
elif char in math_operators:
expression += text[i + 1]
expression += text[i + 2]
expression += text[i + 3]
expression += text[i + 4]
expression += text[i + 5]
i += 5
should_calc = True
elif i < len(text) - 3 and str(char + text[i+1] + text[i+2] + text[i+3]) in allowed_strings:
expression += char
expression += text[i + 1]
expression += text[i + 2]
expression += text[i + 3]
i += 3
should_calc = True
elif i < len(text) - 1 and str(char + text[i + 1]) in allowed_strings:
expression += char
expression += text[i + 1]
i += 1
should_calc = True
elif char.isdigit() or char in allowed_alpha or (expression and char == ".") or (should_calc and char == " ") or (should_calc and char == ","):
expression += char
should_calc = True
elif char in math_operators or char in ["(", ")"]:
# calculation must include at least 1 operator
should_calc = True
expression += char
elif should_calc and char.isalpha():
# don't include any more text in the calculation
break
if should_calc and not any(op in expression for op in ignore_operators):
i += 1
last_char = ' '
for char in expression:
if last_char == '*' and char == '*':
if sender.hasPermission(calc_perm_power):
break
else:
return None
last_char = char
if should_calc:
try:
result = str(eval(expression)) # pylint: disable = W0123
except: # pylint: disable = W0702
@@ -33,15 +71,19 @@ def calc(text):
return (expression, result)
return None
def thread_calc(message, sender):
output = calc(sender, message)
if output and sender.isOnline():
msg(sender, "&2=== Calc: &e" + output[0] + " &2= &c" + output[1])
@hook.event("player.AsyncPlayerChatEvent", "monitor")
def on_calc_chat(event):
sender = event.getPlayer()
message = event.getMessage()
if not event.isCancelled() and uid(sender) in calc_users and sender.hasPermission(calc_perm):
output = calc(message)
if output:
msg(sender, "&2=== Calc: &e" + output[0] + " &2= &c" + output[1])
thread = threading.Thread(target=thread_calc, args=(message, sender))
thread.daemon = True
thread.start()
@hook.command("calc", description="Toggles chat calculations")
+3 -3
View File
@@ -15,8 +15,6 @@ except:
print("[RedstonerUtils] ERROR: Failed to import helpers:")
print(print_traceback())
@hook.enable
def on_enable():
info("RedstonerUtils enabled!")
@@ -79,7 +77,9 @@ shared["load_modules"] = [
# Replacement for LoginSecurity
"loginsecurity",
# Centralized Player class
"playermanager"
"playermanager",
# Plots
"plotter"
]
shared["modules"] = {}
for module in shared["load_modules"]:
+45 -21
View File
@@ -5,26 +5,50 @@
on hold because the PlotMe developer continued to develop PlotMe
"""
import sys
x_plot_size = 3
z_plot_size = 3
padding = 1
def base_coords(x, z):
pid = plot_id(x, z)
return [pid[0] * (x_plot_size + padding), pid[1] * (z_plot_size + padding)]
def bounds(x, z):
base = base_coords(x, z)
return [base, [base[0] + x_plot_size, base[1] + z_plot_size]]
def plot_id(x, z):
return [x // (x_plot_size + padding), z // (z_plot_size + padding)]
from helpers import *
from basecommands import simplecommand
x = int(sys.argv[1])
z = int(sys.argv[2])
print "id: %s" % plot_id(x, z)
print "base: %s" % base_coords(x, z)
print "bounds: %s" % bounds(x, z)
@simplecommand("plotter",
aliases = ["pt"],
senderLimit = 0,
description = "Plot commands")
def plotter_command(sender, command, label, args):
loc = sender.getLocation()
x = loc.getX()
z = loc.getZ()
plot = Plot.get(x, z)
if plot:
msg(sender, "id: %s" % [plot.idx, plot.idz])
msg(sender, "bottom: %s" % [plot.bottomx, plot.bottomz])
msg(sender, "top: %s" % [plot.topx, plot.topz])
else:
msg(sender, "&cThis is not a plot.")
class Plot:
plot_size = 20
padding = 3
padded_size = plot_size + padding
def __init__(self, x, z):
x = int(x)
z = int(z)
self.idx = x
self.idz = z
self.bottomx = x * self.padded_size
self.bottomz = z * self.padded_size
self.topx = self.bottomx + self.plot_size
self.topz = self.bottomz + self.plot_size
@staticmethod
def is_border(x, z):
xborder = Plot.plot_size < x % Plot.padded_size < Plot.padded_size
zborder = Plot.plot_size < z % Plot.padded_size < Plot.padded_size
return xborder or zborder
@staticmethod
def get(x, z):
idx = x // Plot.padded_size
idz = z // Plot.padded_size
return None if Plot.is_border(x, z) else Plot(idx, idz)
+4 -4
View File
@@ -359,11 +359,11 @@ class Arena(object):
return data
def load(self, data):
self.explosion_damage = float(data["explosion"])
self.player_limit = int(data["players"])
self.refill = int(data["refill"])
self.explosion_damage = None if str(data["explosion"]) == "None" else float(data["explosion"])
self.player_limit = None if str(data["players"]) == "None" else int(data["players"])
self.refill = None if str(data["refill"]) == "None" else int(data["refill"])
self.arena_type = str(data["type"])
self.match_goal = int(data["goal"])
self.match_goal = None if str(data["goal"]) == "None" else int(data["goal"])
self.corner1 = Coords(None).load(data["corners"][0]) if not data["corners"][0] == None else None
self.corner2 = Coords(None).load(data["corners"][1]) if not data["corners"][1] == None else None
self.tpp = Coords(None).load(data["corners"][2]) if not data["corners"][2] == None else None