improve calc.py

This commit is contained in:
jomo
2015-01-02 01:07:01 +01:00
parent 0448386fa7
commit 0dcffd0ff3

69
calc.py
View File

@@ -1,53 +1,43 @@
from helpers import * from helpers import *
evals_toggle_list = [] evals_toggle_list = []
math_operators = ["+", "-", "*", "/", "&", "|"]
ignore_operators = ["**", "&&", "||"] # ** may be too intensive, the others cause syntax errors
calc_perm = "utils.calc" calc_perm = "utils.calc"
def lex(msg): def calc(text):
fullmessage = msg expression = ""
msg = list(msg) should_calc = False
tok = "" for char in text:
expression = False if char.isdigit() or char in [".", " "]:
counter = 0 expression += char
startPos = 0 elif char in math_operators:
startPos_set = False # calculation must include at least 1 operator
endPos = 0 should_calc = True
for char in msg: expression += char
counter += 1 elif should_calc and char.isalpha():
if char.isnumeric(): # don't include any more text in the calculation
if not expression: break
startPos = counter if should_calc and not any(op in expression for op in ignore_operators):
# expression = True try:
tok += char result = str(eval(expression))
elif char == "+" or char == "-" or char == "*" or char == "/": except:
expression = True # we can run into all kinds of errors here
tok += char # most probably SyntaxError
elif tok == " ": return None
if not expression: return (expression, result)
tok = "" return None
else:
tok += char
if char.isalpha() or counter >= len(msg):
if expression:
msg = "".join(msg)
result = str(eval(tok))
expression = False
return result
else:
tok = ""
return False
@hook.event("player.AsyncPlayerChatEvent", "monitor")
@hook.event("player.AsyncPlayerChatEvent", "high")
def on_calc_chat(event): def on_calc_chat(event):
sender = event.getPlayer() sender = event.getPlayer()
message = event.getMessage() message = event.getMessage()
if sender.getName() not in evals_toggle_list: if not event.isCancelled() and sender.getName() in evals_toggle_list and sender.hasPermission(calc_perm):
return output = calc(message)
output = lex(message)
if output: if output:
msg(sender, "&2=== Calc: "+output) msg(sender, "&2=== Calc: &e" + output[0] + " = &c" + output[1])
@hook.command("calc", description="Toggles chat calculations") @hook.command("calc", description="Toggles chat calculations")
def on_calc_command(sender, args): def on_calc_command(sender, args):
@@ -71,7 +61,6 @@ def on_calc_command(sender, args):
msg(target, "&6We just &e%s&6 Chat Calculator for you!" % status) msg(target, "&6We just &e%s&6 Chat Calculator for you!" % status)
msg(sender, "&6We &e%s&6 this player's Chat Calculator" % status) msg(sender, "&6We &e%s&6 this player's Chat Calculator" % status)
return return
status = "disabled" status = "disabled"