Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Many fixes and improvements #213

Merged
merged 18 commits into from Jan 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion spockbot/mcdata/__init__.py
Expand Up @@ -3,7 +3,7 @@
from spockbot.mcdata.utils import find_by


def get_item_or_block(find, meta=None, init=True):
def get_item_or_block(find, meta=0, init=True):
ret = None
if isinstance(find, int): # by id
ret = find_by(find, items.items, blocks.blocks)
Expand Down
6 changes: 5 additions & 1 deletion spockbot/mcdata/blocks.py
Expand Up @@ -14,7 +14,7 @@
_block_exts = {}


def get_block(block, meta=None, init=True):
def get_block(block, meta=0, init=True):
ret = None
if isinstance(block, int): # by id
ret = find_by(block, blocks)
Expand Down Expand Up @@ -51,6 +51,10 @@ def __init__(self, meta=None):
if self.id in _block_exts:
_block_exts[self.id](self)

def __str__(self):
return '%s %i:%i' % (self.display_name, self.id,
getattr(self, 'metadata', 0))


def _convert_boundingbox(bb):
if bb == 'block':
Expand Down
1 change: 1 addition & 0 deletions spockbot/mcdata/constants.py
Expand Up @@ -8,6 +8,7 @@
###########

CLIENT_TICK_RATE = 0.05
PLAYER_EYE_HEIGHT = 1.62
PLAYER_HEIGHT = 1.80
PLAYER_WIDTH = 0.6

Expand Down
6 changes: 5 additions & 1 deletion spockbot/mcdata/items.py
Expand Up @@ -8,7 +8,7 @@
items_name = {}


def get_item(item, meta=None, init=True):
def get_item(item, meta=0, init=True):
ret = None
if isinstance(item, int): # by id
ret = find_by(item, items)
Expand All @@ -34,6 +34,10 @@ def __init__(self, meta=None):
# TODO: apply other all possible variations
self.display_name = self.variations[self.metadata]["display_name"]

def __str__(self):
return '%s %i:%i' % (self.display_name, self.id,
getattr(self, 'metadata', 0))


def _make_item(item_dict):
cls_name = '%sItem' % camel_case(str(item_dict['name']))
Expand Down
74 changes: 44 additions & 30 deletions spockbot/mcdata/windows.py
Expand Up @@ -5,6 +5,7 @@
from minecraft_data.v1_8 import windows_list

from spockbot.mcdata import constants, get_item_or_block
from spockbot.mcdata.blocks import Block
from spockbot.mcdata.items import Item
from spockbot.mcdata.utils import camel_case, snake_case

Expand All @@ -23,10 +24,17 @@ def make_slot_check(wanted):
if isinstance(wanted, int):
item, meta = wanted, None
elif isinstance(wanted, Slot):
item, meta = wanted.item_id, wanted.damage
# TODO compare NBT
else: # wanted is list of (id, meta)
item, meta = wanted
item, meta = wanted.item_id, wanted.damage # TODO compare NBT
elif isinstance(wanted, (Item, Block)):
item, meta = wanted.id, wanted.metadata
elif isinstance(wanted, str):
item_or_block = get_item_or_block(wanted, init=True)
item, meta = item_or_block.id, item_or_block.metadata
else: # wanted is (id, meta)
try:
item, meta = wanted
except TypeError:
raise ValueError('Illegal args for make_slot_check(): %s' % wanted)

return lambda slot: item == slot.item_id and meta in (None, slot.damage)

Expand All @@ -40,7 +48,6 @@ def __init__(self, window, slot_nr, id=constants.INV_ITEMID_EMPTY,
self.damage = damage
self.amount = amount
self.nbt = enchants

self.item = get_item_or_block(self.item_id, self.damage) or Item()

def move_to_window(self, window, slot_nr):
Expand Down Expand Up @@ -83,20 +90,16 @@ def __bool__(self):
return not self.is_empty

def __repr__(self):
vals = {
'name': self.item.display_name,
'max': self.item.stack_size,
}
vals.update(self.__dict__)
if self.is_empty:
s = 'empty'
else:
s = '%(amount)i/%(max)i %(item_id)i:%(damage)i %(name)s' % vals
item = self.item
s = '%i/%i %s' % (self.amount, item.stack_size, str(item))

if self.slot_nr != -1:
s += ' at %(slot_nr)i' % self.__dict__
s += ' at %i' % self.slot_nr
if self.window:
s += ' in %(window)s' % self.__dict__
s += ' in %s' % self.window
return '<Slot: %s>' % s


Expand Down Expand Up @@ -196,8 +199,11 @@ def __init__(self, slot, button=constants.INV_BUTTON_LEFT):
'Clicking with button %s not implemented' % button)

def get_packet(self, inv_plugin):
slot_nr = self.slot.slot_nr
if self.slot == inv_plugin.cursor_slot:
slot_nr = constants.INV_OUTSIDE_WINDOW
return {
'slot': self.slot.slot_nr,
'slot': slot_nr,
'button': self.button,
'mode': 0,
'clicked_item': self.slot.get_dict(),
Expand All @@ -206,13 +212,19 @@ def get_packet(self, inv_plugin):
def apply(self, inv_plugin):
clicked = self.slot
cursor = inv_plugin.cursor_slot
if self.button == constants.INV_BUTTON_LEFT:
if clicked == cursor:
if self.button == constants.INV_BUTTON_LEFT:
clicked.amount = 0
elif self.button == constants.INV_BUTTON_RIGHT:
clicked.amount -= 1
self.cleanup_if_empty(clicked)
elif self.button == constants.INV_BUTTON_LEFT:
if clicked.stacks_with(cursor):
self.transfer(cursor, clicked, cursor.amount)
else:
self.swap_slots(cursor, clicked)
elif self.button == constants.INV_BUTTON_RIGHT:
if cursor.item_id == constants.INV_ITEMID_EMPTY:
if cursor.is_empty:
# transfer half, round up
self.transfer(clicked, cursor, (clicked.amount + 1) // 2)
elif clicked.is_empty or clicked.stacks_with(cursor):
Expand All @@ -230,32 +242,33 @@ def __init__(self, slot, drop_stack=False):
self.drop_stack = drop_stack

def get_packet(self, inv_plugin):
if self.slot == inv_plugin.active_slot:
slot_nr = constants.INV_OUTSIDE_WINDOW # drop cursor slot
elif inv_plugin.cursor_slot.item_id != constants.INV_ITEMID_EMPTY:
return None # can't drop while holding an item
else: # default case
slot_nr = self.slot.slot_nr
if self.slot == inv_plugin.cursor_slot:
raise ValueError("Can't drop cursor slot, use SingleClick")
if not inv_plugin.cursor_slot.is_empty:
raise ValueError("Can't drop other slots: cursor slot is occupied")

return {
'slot': slot_nr,
'slot': self.slot.slot_nr,
'button': 1 if self.drop_stack else 0,
'mode': 4,
'clicked_item': inv_plugin.cursor_slot.get_dict(),
}

def apply(self, inv_plugin):
if inv_plugin.cursor_slot.is_empty:
if self.drop_stack:
self.slot.amount = 0
else:
self.slot.amount -= 1
self.cleanup_if_empty(self.slot)
# else: cursor not empty, can't drop while holding an item
if self.drop_stack:
self.slot.amount = 0
else:
self.slot.amount -= 1
self.cleanup_if_empty(self.slot)


class Window(object):
""" Base class for all inventory types. """

name = None
inv_type = None
inv_data = {}

# the arguments must have the same names as the keys in the packet dict
def __init__(self, window_id, title, slot_count,
inv_type=None, persistent_slots=None, eid=None):
Expand Down Expand Up @@ -324,6 +337,7 @@ def _make_window(window_dict):
'__module__': sys.modules[__name__],
'name': str(window_dict['name']),
'inv_type': str(window_dict['id']),
'inv_data': window_dict,
}

# creates function-local index and size variables
Expand Down
2 changes: 1 addition & 1 deletion spockbot/plugins/core/auth.py
Expand Up @@ -48,7 +48,7 @@ def set_username(self, username):
username = property(get_username, set_username)

def set_password(self, password):
if not self.online_mode:
if password and not self.online_mode:
logger.warning("PASSWORD PROVIDED WITH ONLINE_MODE == FALSE")
logger.warning("YOU PROBABLY DIDN'T WANT TO DO THAT")
self.ygg.password = password
Expand Down
6 changes: 4 additions & 2 deletions spockbot/plugins/core/taskmanager.py
Expand Up @@ -10,8 +10,10 @@ def __init__(self, ploader, settings):
super(TaskManager, self).__init__(ploader, settings)
ploader.provides('TaskManager', self)

def run_task(self, task, parent=None):
def run_task(self, task, parent=None, name=None):
if not isinstance(task, Task):
task = Task(task, parent)
task = Task(task, parent, name)
if parent:
parent.last_child = task
task.run(self)
return task
19 changes: 8 additions & 11 deletions spockbot/plugins/helpers/auxiliary.py
Expand Up @@ -13,6 +13,7 @@
from spockbot.mcp import proto
from spockbot.plugins.base import PluginBase


backend = default_backend()


Expand Down Expand Up @@ -43,7 +44,7 @@ def handshake_and_login_start(self, _, __):
'protocol_version': proto.MC_PROTOCOL_VERSION,
'host': self.net.host,
'port': self.net.port,
'next_state': proto.LOGIN_STATE
'next_state': proto.LOGIN_STATE,
})
self.net.push_packet('LOGIN>Login Start', {'name': self.auth.username})

Expand All @@ -54,13 +55,10 @@ def handle_encrypt_request(self, name, packet):
self.auth.send_session_auth(pubkey_raw, packet.data['server_id'])
pubkey = serialization.load_der_public_key(pubkey_raw, backend)
encrypt = lambda data: pubkey.encrypt(data, padding.PKCS1v15()) # flake8: noqa
self.net.push_packet(
'LOGIN>Encryption Response',
{
'shared_secret': encrypt(self.auth.shared_secret),
'verify_token': encrypt(packet.data['verify_token']),
}
)
self.net.push_packet('LOGIN>Encryption Response', {
'shared_secret': encrypt(self.auth.shared_secret),
'verify_token': encrypt(packet.data['verify_token']),
})
self.net.enable_crypto(self.auth.shared_secret)

# Keep Alive - Reflects data back to server
Expand All @@ -70,6 +68,5 @@ def handle_keep_alive(self, name, packet):

# You be dead
def handle_death(self, name, data):
self.net.push_packet(
'PLAY>Client Status', {'action': constants.CL_STATUS_RESPAWN}
)
self.net.push_packet('PLAY>Client Status',
{'action': constants.CL_STATUS_RESPAWN})
7 changes: 4 additions & 3 deletions spockbot/plugins/helpers/chat.py
Expand Up @@ -24,9 +24,10 @@ def __init__(self, net):
self.net = net

def chat(self, message):
while message:
msg_part, message = message[:100], message[100:]
self.net.push_packet('PLAY>Chat Message', {'message': msg_part})
for line in message.split('\n'):
while line:
part, line = line[:100], line[100:]
self.net.push_packet('PLAY>Chat Message', {'message': part})

def whisper(self, player, message):
self.chat('/tell %s %s' % (player, message))
Expand Down
7 changes: 6 additions & 1 deletion spockbot/plugins/helpers/clientinfo.py
Expand Up @@ -78,8 +78,9 @@ class ClientInfo(object):
game_info (GameInfo): Information about the current world/server
spawn_position (Position): Players initial position
health (PlayerHealth): Player's health, food and saturation
position (PlayerPosition): Player's Current position
position (PlayerPosition): Player's current position
player_list (dict): List of all players in the server
eye_pos (PlayerPosition): Player's eye position

"""
def __init__(self):
Expand All @@ -94,6 +95,10 @@ def __init__(self):
self.position = PlayerPosition()
self.player_list = {}

@property
def eye_pos(self):
return self.position + (0, const.PLAYER_EYE_HEIGHT, 0)

def reset(self):
"""Resets the information in ClientInfo"""
self.__init__()
Expand Down
6 changes: 4 additions & 2 deletions spockbot/plugins/helpers/craft.py
Expand Up @@ -19,8 +19,10 @@ def __init__(self, ploader, settings):

def craft(self, item=None, meta=None, amount=1, recipe=None, parent=None):
"""
Starts a ``craft_task``. Returns the recipe used for crafting.
Either ``item`` or ``recipe`` has to be given.
Starts a ``craft_task``. Either ``item`` or ``recipe`` has to be given.

Returns:
Optional[Recipe]: The recipe used for crafting.
"""
if recipe:
item, meta, _ = recipe.result
Expand Down