Skip to content

Commit 8a73a27

Browse files
committed
update to nebual code
1 parent 7626fd1 commit 8a73a27

14 files changed

+403
-251
lines changed

client.py

+27-14
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,43 @@
33
import socket
44
from threading import Thread, Event, Lock
55
import struct
6+
from warnings import warn
67
# Third-party packages
78

89
# Modules from this project
9-
from warnings import warn
1010
import blocks
1111
from globals import BLOCKS_DIR, SECTOR_SIZE
1212
from savingsystem import null2, structuchar2, sector_to_blockpos
13-
from get_ip import get_lan_ip
14-
HOST = "0.0.0.0" #""127.0.0.1"
1513

1614
class PacketReceiver(Thread):
17-
HOST = get_lan_ip()
18-
print HOST
19-
def __init__ (self, world, controller, ipport=(HOST, 1486)): # was "neb.nebtown.info" , nebual's server
15+
def __init__ (self, world, controller, sock):
2016
Thread.__init__(self)
2117
self.world = world
2218
self.controller = controller
2319
self._stop = Event()
2420
self.lock = Lock()
21+
self.sock = sock
22+
23+
def run(self):
2524
try:
26-
self.sock = socket.socket()
27-
self.sock.connect(ipport)
25+
self.loop()
2826
except socket.error as e:
29-
print "Socket Error:", e
27+
if e[0] in (10053, 10054):
28+
#TODO: GUI tell the client they were disconnected
29+
print "Disconnected from server."
30+
self.controller.back_to_main_menu.set()
31+
else:
32+
raise e
3033

31-
def run(self):
34+
def loop(self):
3235
packetcache, packetsize = "", 0
3336

3437
main_thread = self.world.sector_packets.append
3538
while 1:
3639
resp = self.sock.recv(16384)
3740
if self._stop.isSet() or not resp:
3841
print "Client PacketReceiver:",self._stop.isSet() and "Shutting down" or "We've been disconnected by the server"
42+
self.sock.shutdown(SHUT_RDWR)
3943
return
4044

4145
packetcache += resp
@@ -65,6 +69,9 @@ def run(self):
6569
elif packetid == 5: # Print Chat
6670
with self.lock:
6771
main_thread((packetid, (packet[:-4], struct.unpack("BBBB", packet[-4:]))))
72+
elif packetid == 255: # Spawn Position
73+
with self.lock:
74+
main_thread((packetid, struct.unpack("iii", packet)))
6875
else:
6976
warn("Received unknown packetid %s" % packetid)
7077
packetcache = packetcache[packetsize:]
@@ -104,15 +111,21 @@ def dequeue_packet(self):
104111
self.world._remove_block(packet)
105112
elif packetid == 5: # Chat Print
106113
self.controller.write_line(packet[0], color=packet[1])
114+
elif packetid == 255: # Spawn Position
115+
self.controller.player.position = packet
116+
#Now that we know where the player should be, we can enable .update again
117+
self.controller.update = self.controller.update_disabled
107118

108119
def request_sector(self, sector):
109-
self.sock.send("\1"+struct.pack("iii", *sector))
120+
self.sock.sendall("\1"+struct.pack("iii", *sector))
110121
def add_block(self, position, block):
111-
self.sock.send("\3"+struct.pack("iiibb", *(position+(block.id.main, block.id.sub))))
122+
self.sock.sendall("\3"+struct.pack("iiiBB", *(position+(block.id.main, block.id.sub))))
112123
def remove_block(self, position):
113-
self.sock.send("\4"+struct.pack("iii", *position))
124+
self.sock.sendall("\4"+struct.pack("iii", *position))
114125
def send_chat(self, msg):
115-
self.sock.send("\5"+struct.pack("i", len(msg))+msg)
126+
self.sock.sendall("\5"+struct.pack("i", len(msg))+msg)
127+
def request_spawnpos(self):
128+
self.sock.sendall(struct.pack("B", 255))
116129

117130
def stop(self):
118131
self._stop.set()

controllers.py

+43-17
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
# Python packages
44
from binascii import hexlify
5+
import socket
6+
import time
57
import datetime
68
from functools import partial
79
from itertools import imap
@@ -11,6 +13,7 @@
1113
import random
1214

1315
# Third-party packages
16+
import threading
1417
from pyglet.gl import *
1518

1619
# Modules from this project
@@ -117,7 +120,12 @@ def __init__(self, window):
117120
self.hour_deg = 15.0
118121
self.clock = 6
119122

123+
self.back_to_main_menu = threading.Event()
124+
120125
def update(self, dt):
126+
if self.back_to_main_menu.isSet():
127+
self.switch_controller_class(MainMenuController)
128+
return
121129
self.update_sector(dt)
122130
self.update_player(dt)
123131
self.update_mouse(dt)
@@ -199,8 +207,19 @@ def init_gl(self):
199207
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
200208

201209
def setup(self):
210+
try:
211+
#Make sure the address they want to connect to works
212+
ipport = G.IP_ADDRESS.split(":")
213+
if len(ipport) == 1: ipport.append(1486)
214+
sock = socket.socket()
215+
sock.connect(tuple(ipport))
216+
except socket.error as e:
217+
print "Socket Error:", e
218+
#Otherwise back to the main menu we go
219+
return False
220+
202221
self.init_gl()
203-
222+
204223
sky_rotation = -20.0 # -20.0
205224
print 'loading sky'
206225
self.skydome = Skydome(
@@ -223,12 +242,18 @@ def setup(self):
223242
# open_world(self, G.game_dir, G.SAVE_FILENAME)
224243

225244
self.world = World()
226-
self.packetreceiver = PacketReceiver(self.world, self)
245+
self.packetreceiver = PacketReceiver(self.world, self, sock)
227246
self.world.packetreceiver = self.packetreceiver
228247
self.packetreceiver.start()
229-
#TODO: Get our position from the server
230-
#self.player = Player((0,self.world.terraingen.get_height(0,0)+2,0), (-20, 0),
231-
self.player = Player((0,50,0), (-20, 0),
248+
249+
#Get our position from the server
250+
self.packetreceiver.request_spawnpos()
251+
#Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall
252+
self.update_disabled = self.update
253+
self.update = lambda dt: None
254+
#We'll re-enable it when the server tells us where we should be
255+
256+
self.player = Player((0,0,0), (-20, 0),
232257
game_mode=G.GAME_MODE)
233258
print('Game mode: ' + self.player.game_mode)
234259
self.item_list = ItemSelector(self, self.player, self.world)
@@ -256,6 +281,7 @@ def setup(self):
256281
pyglet.clock.schedule_interval_soft(self.world.process_queue,
257282
1.0 / G.MAX_FPS)
258283
pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 1.0, self.player)
284+
return True
259285

260286
def update_time(self):
261287
"""
@@ -525,7 +551,8 @@ def text_input_callback(self, symbol, modifier):
525551
if symbol == G.VALIDATE_KEY:
526552
txt = self.text_input.text.replace('\n', '')
527553
self.text_input.clear()
528-
self.world.packetreceiver.send_chat(txt)
554+
if txt:
555+
self.world.packetreceiver.send_chat(txt)
529556
return pyglet.event.EVENT_HANDLED
530557

531558
def on_text_input_toggled(self):
@@ -548,19 +575,18 @@ def toggle_text_input(self):
548575
self.window.remove_handlers(self.text_input)
549576

550577
def push_handlers(self):
551-
self.setup()
552-
self.window.push_handlers(self.camera)
553-
self.window.push_handlers(self.player)
554-
self.window.push_handlers(self)
555-
self.window.push_handlers(self.item_list)
556-
self.window.push_handlers(self.inventory_list)
578+
if self.setup():
579+
self.window.push_handlers(self.camera)
580+
self.window.push_handlers(self.player)
581+
self.window.push_handlers(self)
582+
self.window.push_handlers(self.item_list)
583+
self.window.push_handlers(self.inventory_list)
584+
else:
585+
self.switch_controller_class(MainMenuController)
557586

558587
def pop_handlers(self):
559-
self.window.pop_handlers()
560-
self.window.pop_handlers()
561-
self.window.pop_handlers()
562-
self.window.pop_handlers()
563-
self.window.pop_handlers()
588+
while self.window._event_stack:
589+
self.window.pop_handlers()
564590

565591
def on_close(self):
566592
self.world.packetreceiver.stop() # Disconnect from the server so the process can close

entity.py

+67
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,44 @@ def __init__(self, position, rotation, velocity=0, health=0, max_health=0,
3434
# it to check if monsters can see player
3535
self.sight_range = sight_range
3636
self.attack_range = attack_range
37+
self.entity_id = None
38+
39+
def can_handle(self, msg_type):
40+
return False
41+
42+
def handle_message(self, msg_type, *args, **kwargs):
43+
pass
44+
45+
#
46+
# Message type
47+
#
48+
MSG_PICKUP, \
49+
MSG_REDSTONE_ACTIVATE, MSG_REDSTONE_DEACTIVATE, \
50+
= range(3)
51+
52+
class EntityManager(object):
53+
def __init__(self):
54+
self.last_id = 0
55+
self.entities = {}
56+
57+
def add_entity(self, entity):
58+
self.last_id = self.last_id + 1
59+
self.entities[self.last_id] = entity
60+
self.entities[self.last_id].entity_id = self.last_id
61+
62+
def remove_entity(self, entity_id):
63+
del self.entities[entity_id]
64+
65+
def broadcast(self, msg_type, *args, **kwargs):
66+
for entity in self.entities:
67+
if entity.can_handle(msg_type):
68+
entity.handle_message(msg_type, *args, **kwargs)
69+
70+
def send_message(self, receiver, msg_type, *args, **kwargs):
71+
if self.entities[receiver].can_handle(msg_type):
72+
self.entities[receiver].handle_message(msg_type, *args, **kwargs)
73+
74+
entity_manager = EntityManager()
3775

3876
class TileEntity(Entity):
3977
"""
@@ -163,3 +201,32 @@ def smelt(self):
163201
self.fuel_task = G.main_timer.add_task(burning_time, self.remove_fuel)
164202
# smelting task
165203
self.smelt_task = G.main_timer.add_task(smelting_time, self.smelt_done)
204+
205+
class RedstoneTorchEntity(TileEntity):
206+
def __init__(self, world, position):
207+
super(RedstoneTorchEntity, self).__init__(world, position)
208+
self.activated = True
209+
210+
entity_manager.broadcast(MSG_REDSTONE_ACTIVATE, position=self.position)
211+
212+
def can_handle(self, msg_type):
213+
return msg_type == MSG_REDSTONE_ACTIVATE or msg_type == MSG_REDSTONE_DEACTIVATE
214+
215+
def handle_message(self, msg_type, *args, **kwargs):
216+
pass
217+
218+
class DroppedBlockEntity(Entity):
219+
def __init__(self, world, position, item):
220+
super(TileEntity, self).__init__(position, rotation=(0,0))
221+
self.world = world
222+
self.item_stack = item
223+
224+
def can_handle(self, msg_type):
225+
return msg_type == MSG_PICKUP
226+
227+
# argument: player
228+
def handle_message(self, msg_type, *args, **kwargs):
229+
if msg_type == MSG_PICKUP:
230+
pass
231+
# entity_manager.remove_entity(self.entity_id)
232+

globals.py

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
DEBUG = False
2828

29+
IP_ADDRESS = "neb.nebtown.info" # The IP Address to connect to
2930

3031
#
3132
# Game modes

0 commit comments

Comments
 (0)