You can subscribe to this list here.
| 2009 |
Jan
|
Feb
(9) |
Mar
(11) |
Apr
|
May
(4) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(9) |
Nov
(5) |
Dec
(18) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2010 |
Jan
(4) |
Feb
|
Mar
|
Apr
(4) |
May
|
Jun
|
Jul
(11) |
Aug
(33) |
Sep
(33) |
Oct
|
Nov
|
Dec
|
|
From: <Blu...@us...> - 2010-09-30 10:18:48
|
Revision: 415
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=415&view=rev
Author: BlueWolf_
Date: 2010-09-30 10:18:42 +0000 (Thu, 30 Sep 2010)
Log Message:
-----------
Server can now check which user can see an other user and will pipe the move-data to those clients
Modified Paths:
--------------
trunk/server/core/functions.py
trunk/server/core/parser.py
trunk/server/core/tick.py
Modified: trunk/server/core/functions.py
===================================================================
--- trunk/server/core/functions.py 2010-09-28 22:00:28 UTC (rev 414)
+++ trunk/server/core/functions.py 2010-09-30 10:18:42 UTC (rev 415)
@@ -147,45 +147,44 @@
return True
-def get_visible_clients(viewport, client, clients):
+def get_visible_users(viewport, client, clients, pos = None):
"""
- Get a list of all visible clients for this user
+ Get a list of all visible users for this user
"""
visible = []
+ if pos == None: pos = get_current_position(client)
- margin = client['speed']*2
+ margin = client['speed']
view = (
- client['pos'][0] - (viewport[0]/2) - margin,
- client['pos'][1] - (viewport[1]/2) - margin,
- viewport[0] + margin,
- viewport[1] + margin
+ pos[0] - (viewport[0]/2) - margin,
+ pos[1] - (viewport[1]/2) - margin,
+ viewport[0] + (margin*2),
+ viewport[1] + (margin*2)
)
for other in clients.values():
if other['status'] != "VP": continue
if client['pos'][2] != other['pos'][2]: continue
- print client['user'], "->", other['user']
+ pos_other = get_current_position(other)
# Create his viewport
- margin_other = other['speed']*2
+ margin_other = other['speed']
view_other = (
- other['pos'][0] - (viewport[0]/2) - margin,
- other['pos'][1] - (viewport[1]/2) - margin,
- viewport[0] + margin,
- viewport[1] + margin
+ pos_other[0] - margin,
+ pos_other[1] - margin,
+ margin*2,
+ margin*2
)
-
- print view, view_other
# Is this without our viewport?
if (view[0]+view[2] >= view_other[0] and view[0] <= view_other[0]+view_other[2]) and \
(view[1]+view[3] >= view_other[1] and view[1] <= view_other[1]+view_other[3]):
visible.append(other)
-
return visible
+
def get_current_position(client):
"""
Returns the current position for this user
@@ -228,15 +227,8 @@
"""
# Check if newpos is valid
- if client['moving'] == False:
- # Just check if it's the same pos
- if client['pos'] != proposed_pos:
- client['con'].send("move", {
- "cid": client['cid'],
- "pos": client['pos']
- })
-
- else:
+ if client['moving'] != False:
+ # Client is moving. CHeck is proposed_pos is near our calculated pos
current_pos = get_current_position(client)
if proposed_pos != None:
@@ -255,11 +247,47 @@
})
else:
current_pos = proposed_pos
+
+ # [TODO] Check for collisions between lastpos and current_pos
+
+ else:
+ # Just check if it's the same pos
+ if proposed_pos != None and client['pos'] != proposed_pos:
+ client['con'].send("move", {
+ "cid": client['cid'],
+ "pos": client['pos']
+ })
+ current_pos = client['pos']
+
+ # Check which other clients see this user
+ new_visible = get_visible_users(sh['config']['viewport'], client,
+ sh['core'].clients, current_pos)
+
+ # Find those who left his/her viewport
+ for other in [cl for cl in client['visible']['users'] \
+ if cl not in new_visible]:
+ client['con'].send("move", {
+ "cid": other['cid'],
+ "pos": None,
+ })
+
+ # Send all the new users who entered his/her viewport
+ for other in [cl for cl in new_visible \
+ if cl not in client['visible']['users']]:
+ data = {
+ "cid": other['cid'],
+ "pos": get_current_position(other),
+ "moving": False
+ }
+ if other['moving']:
+ data['moving'] = True
+ data['direction'] = other['moving'][1]
+ data['speed'] = other['moving'][2]
+
+ client['con'].send("move", data)
+
+ client['visible']['users'] = new_visible
+
+ client['lastpos'] = current_pos
- # Check for collisions between lastpos and current_pos
- # [TODO]
- print "Check", client['lastpos'], "->", current_pos
-
- client['lastpos'] = current_pos
-
Modified: trunk/server/core/parser.py
===================================================================
--- trunk/server/core/parser.py 2010-09-28 22:00:28 UTC (rev 414)
+++ trunk/server/core/parser.py 2010-09-30 10:18:42 UTC (rev 415)
@@ -132,14 +132,12 @@
client['user'] = screenname
client['app'] = tuple(msg['client'])
client['version'] = str(msg['version'])
- client['pos'] = [
- int(random.random()*500-250), # X
- int(random.random()*500-250), # Y
- 0] # Z
+ client['pos'] = [0, 0, 0] # X, Y, Z
client['lastpos'] = client['pos'][:] # Last pos that is checked
client['status'] = "VP"
client['speed'] = self.sh['config']['default_speed']
client['moving'] = False
+ client['visible'] = {'users': [], 'objects': []}
if msg['bot'] == False:
client['bot'] = False
@@ -174,8 +172,9 @@
# Send online clients
userlist = []
- visible = get_visible_clients(self.sh['config']['viewport'], client,
+ visible = get_visible_users(self.sh['config']['viewport'], client,
self.clients)
+ client['visible']['users'] = visible
for cid_o, client_o in self.clients.items():
if client_o['status'] != "VP": continue
@@ -204,12 +203,17 @@
# Is this user visible for this client?
if client_o in visible:
user_o['pos'] = client_o['pos']
+ else:
+ user_o['pos'] = None
+
+ # Is this client visible to the other user?
+ if client in get_visible_users(self.sh['config']['viewport'],
+ client_o, self.clients):
+ client_o['visible']['users'].append(client)
user['pos'] = client['pos']
else:
- user_o['pos'] = None
user['pos'] = None
-
# Send data to other user
if cid != cid_o:
client_o['con'].send("useronline", user)
@@ -264,7 +268,7 @@
def move(self, cid, msg):
"""
- An user is moving to a different position
+ A user is moving to a different position
* moving:
Boolean, if the user is walking or not
@@ -285,4 +289,44 @@
position_check(self.sh, client, msg['pos'])
client['pos'] = msg['pos']
client['moving'] = False
+
+ # Check for the user who could see this client, but can't anymore
+ for other in self.clients.values():
+ if other == client or other['status'] != "VP" or \
+ other['pos'][2] != client['pos'][2]:
+ continue
+ if client not in other['visible']['users']: continue
+
+ if client not in get_visible_users(
+ self.sh['config']['viewport'], other, self.clients):
+ other['visible']['users'].remove(client)
+ other['con'].send("move", {
+ "cid": client['cid'],
+ "pos": None
+ })
+
+ # Send to other clients
+ for other in self.clients.values():
+ if other == client or other['status'] != "VP" or \
+ other['pos'][2] != client['pos'][2]:
+ continue
+
+ if client in get_visible_users(self.sh['config']['viewport'], other,
+ self.clients):
+
+ if client not in other['visible']['users']:
+ other['visible']['users'].append(client)
+
+ data = {
+ "cid": client['cid'],
+ "pos": client['pos'],
+ "moving": False,
+ }
+ if client['moving']:
+ data['moving'] = True
+ data['direction'] = client['moving'][1]
+ data['speed'] = client['moving'][2]
+
+ other['con'].send("move", data)
+
Modified: trunk/server/core/tick.py
===================================================================
--- trunk/server/core/tick.py 2010-09-28 22:00:28 UTC (rev 414)
+++ trunk/server/core/tick.py 2010-09-30 10:18:42 UTC (rev 415)
@@ -79,5 +79,12 @@
amount += 1
position_check(self.sh, client)
- if amount == 0:
- return True
+ if amount == 0: return True
+
+ # Go through all non-moving users to check if someone entered
+ # their viewport
+ for client in self.clients.values():
+ if client['status'] != "VP" or client['moving'] != False:
+ continue
+
+ position_check(self.sh, client)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-28 22:00:34
|
Revision: 414
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=414&view=rev
Author: BlueWolf_
Date: 2010-09-28 22:00:28 +0000 (Tue, 28 Sep 2010)
Log Message:
-----------
Added a tick-module for the core. It will check for the user's position but does not send them to other clients yet
Modified Paths:
--------------
trunk/server/core/functions.py
trunk/server/core/parser.py
trunk/server/core/server.py
Added Paths:
-----------
trunk/server/core/tick.py
Modified: trunk/server/core/functions.py
===================================================================
--- trunk/server/core/functions.py 2010-09-28 21:59:12 UTC (rev 413)
+++ trunk/server/core/functions.py 2010-09-28 22:00:28 UTC (rev 414)
@@ -15,6 +15,8 @@
## along with this program; if not, write to the Free Software
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+import threading, time, random, sys
+
def check_version(version, expr):
"""
Checks whether a version meets certain conditions.
@@ -123,3 +125,141 @@
return False
+def check_double_user(clients, isbot, screenname, data):
+ """
+ Checks for an user or bot with the same name
+ """
+
+ # Check if there isn't already a bot online with this name
+ for i, client in clients.items():
+ if client['status'] == "VP" and client['bot'] == True and \
+ client['user'] == screenname:
+ # Our client cannot log in
+ return "duplicate user"
+
+ if isbot == False:
+ # Check for the same user
+ for i, client in clients.items():
+ if client['status'] == "VP" and client['bot'] == False and \
+ client['user'] == screenname:
+ # Disconnect this user
+ client['con'].close_msg('duplicate')
+
+ return True
+
+def get_visible_clients(viewport, client, clients):
+ """
+ Get a list of all visible clients for this user
+ """
+
+ visible = []
+
+ margin = client['speed']*2
+ view = (
+ client['pos'][0] - (viewport[0]/2) - margin,
+ client['pos'][1] - (viewport[1]/2) - margin,
+ viewport[0] + margin,
+ viewport[1] + margin
+ )
+
+ for other in clients.values():
+ if other['status'] != "VP": continue
+ if client['pos'][2] != other['pos'][2]: continue
+
+ print client['user'], "->", other['user']
+
+ # Create his viewport
+ margin_other = other['speed']*2
+ view_other = (
+ other['pos'][0] - (viewport[0]/2) - margin,
+ other['pos'][1] - (viewport[1]/2) - margin,
+ viewport[0] + margin,
+ viewport[1] + margin
+ )
+
+ print view, view_other
+ # Is this without our viewport?
+ if (view[0]+view[2] >= view_other[0] and view[0] <= view_other[0]+view_other[2]) and \
+ (view[1]+view[3] >= view_other[1] and view[1] <= view_other[1]+view_other[3]):
+ visible.append(other)
+
+
+ return visible
+
+def get_current_position(client):
+ """
+ Returns the current position for this user
+ """
+
+ if client['moving']:
+ starttime, direction, speed = client['moving']
+ pos = client['pos'][:]
+ timeline = time.time() - starttime
+ move = timeline*speed
+
+ if direction == 0:
+ pos[1] = int(pos[1] - move)
+ elif direction == 1:
+ pos[1] = int(pos[1] - (move/1.7))
+ pos[0] = int(pos[0] + (move/1.7))
+ elif direction == 2:
+ pos[0] = int(pos[0] + move)
+ elif direction == 3:
+ pos[0] = int(pos[0] + (move/1.7))
+ pos[1] = int(pos[1] + (move/1.7))
+ elif direction == 4:
+ pos[1] = int(pos[1] + move)
+ elif direction == 5:
+ pos[1] = int(pos[1] + (move/1.7))
+ pos[0] = int(pos[0] - (move/1.7))
+ elif direction == 6:
+ pos[0] = int(pos[0] - move)
+ elif direction == 7:
+ pos[0] = int(pos[0] - (move/1.7))
+ pos[1] = int(pos[1] - (move/1.7))
+
+ return pos
+ else:
+ return client['pos']
+
+def position_check(sh, client, proposed_pos = None):
+ """
+ Check the current position of the user for collisions or inaccurate data
+ """
+
+ # Check if newpos is valid
+ if client['moving'] == False:
+ # Just check if it's the same pos
+ if client['pos'] != proposed_pos:
+ client['con'].send("move", {
+ "cid": client['cid'],
+ "pos": client['pos']
+ })
+
+ else:
+ current_pos = get_current_position(client)
+
+ if proposed_pos != None:
+ # Compare current_pos with proposed_pos how much they differ
+ wrong = False
+ for p1, p2 in zip(current_pos[:2], proposed_pos[:2]):
+ diff = p2-p1
+ if diff < 0: diff = -diff
+ if diff > sh['config']['position_error_margin']:
+ wrong = True
+
+ if wrong: # Send correction
+ client['con'].send("move", {
+ "cid": client['cid'],
+ "pos": current_pos,
+ })
+ else:
+ current_pos = proposed_pos
+
+
+ # Check for collisions between lastpos and current_pos
+ # [TODO]
+ print "Check", client['lastpos'], "->", current_pos
+
+ client['lastpos'] = current_pos
+
Modified: trunk/server/core/parser.py
===================================================================
--- trunk/server/core/parser.py 2010-09-28 21:59:12 UTC (rev 413)
+++ trunk/server/core/parser.py 2010-09-28 22:00:28 UTC (rev 414)
@@ -28,7 +28,7 @@
self.call = sh['call']
self.core = sh['core']
- # Shortkeys
+ # Shortcut
self.clients = self.core.clients
def __call__(self, cid, msg):
@@ -41,57 +41,6 @@
if (func):
return func(cid, body)
- def _check_double_user(self, isbot, screenname, data):
- """
- Checks for an user or bot with the same name
- """
-
- # Check if there isn't already a bot online with this name
- for id, cl in self.clients.items():
- if cl['status'] == "VP" and cl['bot'] == True and \
- cl['user'] == screenname:
- # Our client cannot log in
- data.send("error", {
- "reason": "duplicate user"
- })
- return False
-
- if isbot == False:
- # Check for the same user
- for id, cl in self.clients.items():
- if cl['status'] == "VP" and cl['bot'] == False and \
- cl['user'] == screenname:
- # Disconnect this user
- cl['con'].close_msg('duplicate')
-
- return True
-
- def _is_client_visible(self, client1, client2):
- """
- Checks if client1 can see client2
- """
-
- client1 = client1['pos']
- client2 = client2['pos']
-
- # Check height
- if client1[2] != client2[2]: return False
-
- # Check horizontal
- if client1[0]-client2[0] > self.sh['config']['viewport'][0]/2 \
- or client1[0]-client2[0] < -self.sh['config']['viewport'][0]/2:
- return False
-
- # Check vertical
- if client1[1]-client2[1] > self.sh['config']['viewport'][1]/2 \
- or client1[1]-client2[1] < -self.sh['config']['viewport'][1]/2:
- return False
-
- # Clients see each other!
- return True
-
-
-
def login(self, cid, msg):
"""
Send when the users wants to log in
@@ -164,12 +113,18 @@
# Check for double logins
if msg['bot'] == False: # Just an ordinary user
- if self._check_double_user(False, username, data) == False:
- return
+ resp = check_double_user(self.clients, False, username, data)
+ if resp != True:
+ data.send("error", {
+ "reason": resp
+ })
else: # Client is a bot
- if self._check_double_user(True, screenname, data) == False:
- return
+ resp = check_double_user(self.clients, True, screenname, data)
+ if resp != True:
+ data.send("error", {
+ "reason": resp
+ })
# Log the client in
@@ -177,8 +132,14 @@
client['user'] = screenname
client['app'] = tuple(msg['client'])
client['version'] = str(msg['version'])
- client['pos'] = [0, 0, 0] # XYZ
+ client['pos'] = [
+ int(random.random()*500-250), # X
+ int(random.random()*500-250), # Y
+ 0] # Z
+ client['lastpos'] = client['pos'][:] # Last pos that is checked
client['status'] = "VP"
+ client['speed'] = self.sh['config']['default_speed']
+ client['moving'] = False
if msg['bot'] == False:
client['bot'] = False
@@ -202,7 +163,6 @@
# TODO: Send world
-
user = {} # This will be send to others
user['cid'] = cid
user['user'] = client['user']
@@ -214,6 +174,9 @@
# Send online clients
userlist = []
+ visible = get_visible_clients(self.sh['config']['viewport'], client,
+ self.clients)
+
for cid_o, client_o in self.clients.items():
if client_o['status'] != "VP": continue
@@ -239,7 +202,7 @@
# Positions
# Is this user visible for this client?
- if self._is_client_visible(client, client_o):
+ if client_o in visible:
user_o['pos'] = client_o['pos']
user['pos'] = client['pos']
else:
@@ -298,4 +261,28 @@
"""
self.call.custom(cid, msg['header'], msg['body'])
+
+ def move(self, cid, msg):
+ """
+ An user is moving to a different position
+ * moving:
+ Boolean, if the user is walking or not
+ * pos:
+ Current position of the user
+ * direction
+ Current direction of this user (None when moving = False)
+ """
+
+ client = self.clients[cid]
+
+ if msg['moving']:
+ position_check(self.sh, client, msg['pos'])
+ client['pos'] = msg['pos']
+ client['moving'] = (time.time(), msg['direction'], client['speed'])
+ self.sh['tick'].start("moving")
+ else:
+ position_check(self.sh, client, msg['pos'])
+ client['pos'] = msg['pos']
+ client['moving'] = False
+
Modified: trunk/server/core/server.py
===================================================================
--- trunk/server/core/server.py 2010-09-28 21:59:12 UTC (rev 413)
+++ trunk/server/core/server.py 2010-09-28 22:00:28 UTC (rev 414)
@@ -15,10 +15,11 @@
## along with this program; if not, write to the Free Software
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-import simplejson, socket, threading, time, random, sys, hashlib, select
+import simplejson, socket, hashlib, select
from functions import *
from parser import Parser
+from tick import Tick
import rsa
@@ -78,11 +79,16 @@
because it's used to calculate which objects and people the client
is able to see. By default this is (1000, 700).
- -max_speed:
- The amount of pixels a user may move in a certain time.
- The default is (50, 1.0) which basically means 50px per 1 second.
- When a user exceeds this, the server will just reset his position
- to his last known location.
+ -default_speed:
+ How fast an user may walk by default. By default this is 175. You
+ can change this on the fly with client.change_speed (for example,
+ when the user starts running or uses a vehicle). The viewport for
+ this user will be changed based on the speed. Margin on all sides
+ will be speed*2
+
+ -position_error_margin
+ How much pixels is tolerated by the server before it starts
+ correcting user's positions. Default is 25
"""
@@ -103,6 +109,8 @@
self.clients = {}
self.__parse = Parser(self.__sh)
+ self.__sh['tick'] = Tick(self.__sh)
+
threading.Thread.__init__(self)
def __config_default(self, config):
@@ -115,7 +123,9 @@
config['rsa_bits'] = int(config.get('rsa_bits', 64))
config['bot_names'] = str(config.get('bot_names', "[%s]"))
config['viewport'] = tuple(config.get('viewport', (1000,700)))
- config['max_speed'] = tuple(config.get('max_speed', (50, 1.0)))
+ config['default_speed'] = int(config.get('max_speed', 175))
+ config['position_error_margin'] = int(config.get(
+ "position_error_margin", 25))
def start_server(self):
@@ -194,6 +204,7 @@
str(random.random())).hexdigest()[:8]
self.clients[cid] = {
+ "cid": cid,
"status": "",
"con": Client(cid, sock, self.__sh, self.__parse)
}
Added: trunk/server/core/tick.py
===================================================================
--- trunk/server/core/tick.py (rev 0)
+++ trunk/server/core/tick.py 2010-09-28 22:00:28 UTC (rev 414)
@@ -0,0 +1,83 @@
+#!/usr/bin/env python
+
+## This file is part of Virtual Playground
+## Copyright (c) 2010 Jos Ratsma + Koen Koning
+
+## This program is free software; you can redistribute it and/or
+## modify it under the terms of the GNU General Public License
+## as published by the Free Software Foundation; either
+## version 2 of the License, or (at your option) any later version.
+
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+from functions import *
+
+TICK_SPEED = 1
+
+class Tick():
+ """
+ This will tick every second when needed
+ """
+ def __init__(self, sh):
+ self.sh = sh
+ self.call = sh['call']
+ self.core = sh['core']
+
+ # Shortcut
+ self.clients = self.core.clients
+
+ self.callers = []
+ self.timer = None
+
+ def start(self, name, *extra):
+ # Start a timer for this call
+
+ if name in self.callers: return
+ self.callers.append(name)
+
+ if self.timer == None: # Start a timer
+ self.timer = threading.Timer(TICK_SPEED, self.update)
+ self.timer.start()
+
+ def stop(self, name):
+ try: self.callers.remove(name)
+ except: pass
+
+ if self.callers == [] and self.timer:
+ self.timer.cancel()
+ self.timer = None
+
+ def update(self):
+ # Execute stuff
+ for name in self.callers:
+ if self.tick(name):
+ try: self.callers.remove(name)
+ except: pass # This can happen due to threading. It's not bad
+
+ # Start the next timer
+ if self.callers != []:
+ self.timer = threading.Timer(TICK_SPEED, self.update)
+ self.timer.start()
+ else:
+ self.timer = None
+
+ def tick(self, name):
+ if name == "moving":
+ # Find which users are moving
+ amount = 0
+ for client in self.clients.values():
+ if client['status'] != "VP" or client['moving'] == False:
+ continue
+
+ amount += 1
+ position_check(self.sh, client)
+
+ if amount == 0:
+ return True
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-28 21:59:18
|
Revision: 413
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=413&view=rev
Author: BlueWolf_
Date: 2010-09-28 21:59:12 +0000 (Tue, 28 Sep 2010)
Log Message:
-----------
Client will now send all move-events to the server the way it should. It does't process the response from the server though
Modified Paths:
--------------
trunk/client/core/client.py
trunk/client/downloader.py
trunk/client/login.py
trunk/client/playground.py
Modified: trunk/client/core/client.py
===================================================================
--- trunk/client/core/client.py 2010-09-27 22:02:49 UTC (rev 412)
+++ trunk/client/core/client.py 2010-09-28 21:59:12 UTC (rev 413)
@@ -274,12 +274,12 @@
"version": __version__
})
- def move(self, moving, pos, direction = None, speed = None):
- data = {"moving": moving, "pos": pos}
- if moving:
- data['direction'] = direction
- data['speed'] = speed
- self.send("move", data)
+ def move(self, moving, pos, direction = None):
+ self.send("move", {
+ "moving": moving,
+ "pos": pos,
+ "direction": direction
+ })
def send(self, data_header, data_body = {}):
Modified: trunk/client/downloader.py
===================================================================
--- trunk/client/downloader.py 2010-09-27 22:02:49 UTC (rev 412)
+++ trunk/client/downloader.py 2010-09-28 21:59:12 UTC (rev 413)
@@ -74,7 +74,7 @@
def remove_usage(self, filename):
try: load = self.loaded_files[filename]
- except: pass
+ except: return
load['usages'] -= 1
if load['usages'] == 0:
Modified: trunk/client/login.py
===================================================================
--- trunk/client/login.py 2010-09-27 22:02:49 UTC (rev 412)
+++ trunk/client/login.py 2010-09-28 21:59:12 UTC (rev 413)
@@ -52,6 +52,7 @@
if data['status'] == "login":
if self.status != "login":
# Load the data for the login
+ sh['timer'].stop("login-transit")
self.surf.set_alpha(None)
self.background = load_image(False, "images", "loginbg.png")
self.loginbox = load_image(True, "images", "loginbox.png")
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-27 22:02:49 UTC (rev 412)
+++ trunk/client/playground.py 2010-09-28 21:59:12 UTC (rev 413)
@@ -70,18 +70,23 @@
elif keys[3]:
direction = 6
+ if direction == None and self.direction == None:
+ # Not moving and nothing has changed (this can happen
+ # in some circumstances. Faulty window manager
+ return
+
if direction == None and self.direction != None:
# Stop the timer. We are not walking
self.direction = None
- sh['client'].move(False, self.this_user['pos'][0:2])
+ sh['client'].move(False, self.this_user['pos'])
sh['timer'].stop("playground-walk")
elif self.direction == None or \
direction != self.direction[0]:
# We started walking or changed direction
- sh['client'].move(True, self.this_user['pos'][0:2],
- direction, MOVE_SPEED)
+ sh['client'].move(True, self.this_user['pos'],
+ direction)
self.direction = (direction, time.time(),
self.this_user['pos'][:])
@@ -94,6 +99,7 @@
if data['status'] == "login" and self.status == "playground":
# Unload data from the playground
sh['timer'].stop("playground-move")
+ sh['timer'].stop("playground-viewport-move")
self.background.reset()
self.viewport = None
self.viewport_float = None
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-27 22:02:55
|
Revision: 412
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=412&view=rev
Author: BlueWolf_
Date: 2010-09-27 22:02:49 +0000 (Mon, 27 Sep 2010)
Log Message:
-----------
Sending move-events to the server
Modified Paths:
--------------
trunk/client/core/client.py
trunk/client/playground.py
Modified: trunk/client/core/client.py
===================================================================
--- trunk/client/core/client.py 2010-09-26 22:16:14 UTC (rev 411)
+++ trunk/client/core/client.py 2010-09-27 22:02:49 UTC (rev 412)
@@ -274,6 +274,12 @@
"version": __version__
})
+ def move(self, moving, pos, direction = None, speed = None):
+ data = {"moving": moving, "pos": pos}
+ if moving:
+ data['direction'] = direction
+ data['speed'] = speed
+ self.send("move", data)
def send(self, data_header, data_body = {}):
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-26 22:16:14 UTC (rev 411)
+++ trunk/client/playground.py 2010-09-27 22:02:49 UTC (rev 412)
@@ -20,8 +20,6 @@
from playground_avatar import Avatar
from playground_background import Background
-POS_UPDATE_DELAY = 1 # Determines when a pos-update should be send.
- # Every x seconds.
MOVE_SPEED = 175 # How fast the avatar shoud walk
@@ -75,12 +73,16 @@
if direction == None and self.direction != None:
# Stop the timer. We are not walking
self.direction = None
+ sh['client'].move(False, self.this_user['pos'][0:2])
sh['timer'].stop("playground-walk")
elif self.direction == None or \
direction != self.direction[0]:
# We started walking or changed direction
+ sh['client'].move(True, self.this_user['pos'][0:2],
+ direction, MOVE_SPEED)
+
self.direction = (direction, time.time(),
self.this_user['pos'][:])
sh['timer'].start("playground-walk",
@@ -139,6 +141,7 @@
if data['action'] == "update":
self.background.update_landscapes(sh['landscapes'])
+
def update(self, rect = None, doupdate = True):
# This will blit and update the screen at rect
@@ -283,7 +286,3 @@
sh['update']()
if self.viewport_float == desired_pos: return True
-
-
- elif name == "playground-pos-update":
- pass
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-26 22:16:22
|
Revision: 411
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=411&view=rev
Author: BlueWolf_
Date: 2010-09-26 22:16:14 +0000 (Sun, 26 Sep 2010)
Log Message:
-----------
And we have a background which you can walk on! Next step: Sending and receiving user positions
Modified Paths:
--------------
trunk/client/callback.py
trunk/client/playground.py
trunk/client/playground_avatar.py
trunk/client/timer.py
Added Paths:
-----------
trunk/client/playground_background.py
Modified: trunk/client/callback.py
===================================================================
--- trunk/client/callback.py 2010-09-25 21:16:57 UTC (rev 410)
+++ trunk/client/callback.py 2010-09-26 22:16:14 UTC (rev 411)
@@ -144,6 +144,13 @@
sh['main'].call("filetable", {
"action": "update"
})
+
+ elif header == "landscapes": # How the background should look like
+ sh['landscapes'] = body
+
+ sh['main'].call("landscapes", {
+ "action": "update"
+ })
def userlist(self, userlist):
if len(userlist) == 1:
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-25 21:16:57 UTC (rev 410)
+++ trunk/client/playground.py 2010-09-26 22:16:14 UTC (rev 411)
@@ -18,6 +18,7 @@
from functions import *
import gui
from playground_avatar import Avatar
+from playground_background import Background
POS_UPDATE_DELAY = 1 # Determines when a pos-update should be send.
# Every x seconds.
@@ -32,7 +33,7 @@
self.status = None
self.statuswhere = None
- self.backgrounds = {}
+ self.background = Background(self)
self.viewport_float = None
self.viewport = None
self.direction = None
@@ -84,8 +85,6 @@
self.this_user['pos'][:])
sh['timer'].start("playground-walk",
self.timer_walk)
- #sh['timer'].start("playground-pos-update",
- # self.timer_walk, time.time())
def call(self, name, data):
@@ -93,12 +92,13 @@
if data['status'] == "login" and self.status == "playground":
# Unload data from the playground
sh['timer'].stop("playground-move")
- for name in self.backgrounds.keys():
- sh['downloader'].remove_usage(name)
- self.backgrounds = {}
+ self.background.reset()
self.viewport = None
self.viewport_float = None
self.direction = None
+
+ for avatar in self.avatars.values():
+ avatar.stop()
self.avatars = {}
self.this_user = None
@@ -135,6 +135,9 @@
sh['downloader'].get_file("bg-grass.png", "img", self.download,\
"background", counter)
+ elif name == "landscapes":
+ if data['action'] == "update":
+ self.background.update_landscapes(sh['landscapes'])
def update(self, rect = None, doupdate = True):
# This will blit and update the screen at rect
@@ -145,7 +148,7 @@
rect = Rect(rect)
# Blit the background
- #self.background.update(self.surf, self.viewport, rect)
+ self.background.update(self.surf, self.viewport, rect)
# Blit the users
for avatar in self.avatars.values():
@@ -157,7 +160,7 @@
def download(self, filename, cache, name, *arg):
if name == "background":
- self.backgrounds[filename] = cache
+ self.background.add_background(filename, cache)
counter = arg[0]
counter['counter'] -= 1
@@ -172,6 +175,9 @@
def timer_walk(self, name, starttime = None):
if name == "playground-walk":
+ if self.direction == None:
+ return True # No direction. We aren't moving
+
direction, starttime, startpos = self.direction
timeline = time.time() - starttime
speed = MOVE_SPEED
@@ -247,6 +253,33 @@
self.viewport[1] += real_move[1]
self.surf.scroll(-real_move[0], -real_move[1])
+
+ # Blit the 2 sides that now appear
+
+ if real_move[0] < 0: # Left side
+ rect = Rect(0, 0, -real_move[0], 700)
+ self.update(rect, doupdate=False)
+ elif real_move[0] > 0: # Right side
+ rect = Rect(1000-real_move[0], 0, real_move[0], 700)
+ self.update(rect, doupdate=False)
+
+ if real_move[1] < 0: # Top
+ rect = Rect(0, 0, 1000, -real_move[1])
+ if real_move[0] < 0 : # And to the left
+ rect.left = -real_move[0]
+ rect.width = 1000 + real_move[0]
+ elif real_move[0] > 0: # And to the right
+ rect.width = 1000 - real_move[0]
+ self.update(rect, doupdate=False)
+ elif real_move[1] > 0: # Bottom
+ rect = Rect(0, 700-real_move[1], 1000, real_move[1])
+ if real_move[0] < 0 : # And to the left
+ rect.left = -real_move[0]
+ rect.width = 1000 + real_move[0]
+ elif real_move[0] > 0: # And to the right
+ rect.width = 1000 - real_move[0]
+ self.update(rect, doupdate=False)
+
sh['update']()
if self.viewport_float == desired_pos: return True
Modified: trunk/client/playground_avatar.py
===================================================================
--- trunk/client/playground_avatar.py 2010-09-25 21:16:57 UTC (rev 410)
+++ trunk/client/playground_avatar.py 2010-09-26 22:16:14 UTC (rev 411)
@@ -28,30 +28,45 @@
sh['downloader'].get_file("happyblock.png", "img", self.download)
+ def stop(self):
+ # Playground is quiting. Stop everything
+ sh['downloader'].remove_usage("happyblock.png")
+
def move(self, pos):
+ # Move the avatar to this place
lastpos = self.user['pos']
self.user['pos'] = pos
- self.update_parent()
+ rect = self.get_rect(pos)
+ rect_old = self.get_rect(lastpos)
+ rect.union_ip(rect_old)
+
+ self.update_parent(rect)
def download(self, filename, cache):
+ # Callback for the avatar-downloader
self.avatar = cache
self.update_parent()
-
- def update_parent(self):
- # Update ourself. Send it to our parent
- self_rect = Rect(
- self.user['pos'][0] - self.playground.viewport[0] -
- self.center[0],
- self.user['pos'][1] - self.playground.viewport[1] -
- self.center[1],
+
+ def get_rect(self, pos):
+ # Get a rect, pased on the position
+ return Rect(
+ pos[0] - self.playground.viewport[0] - self.center[0],
+ pos[1] - self.playground.viewport[1] - self.center[1],
self.size[0],
self.size[1])
+
+ def update_parent(self, rect = None):
+ if self.playground.viewport == None:
+ return # Without viewport, we can't update (this can happen due to
+ # threading
+
+ if rect == None:
+ rect = self.get_rect(self.user['pos'])
- if not Rect(0, 0, 1000, 700).colliderect(self_rect): return
-
- self.playground.update(self_rect)
+ if not Rect(0, 0, 1000, 700).colliderect(rect): return
+ self.playground.update(rect)
def update(self, surf, viewport, rect):
if not self.avatar: return
Added: trunk/client/playground_background.py
===================================================================
--- trunk/client/playground_background.py (rev 0)
+++ trunk/client/playground_background.py 2010-09-26 22:16:14 UTC (rev 411)
@@ -0,0 +1,77 @@
+## This file is part of Virtual Playground
+## Copyright (c) 2009 Jos Ratsma + Koen Koning
+
+## This program is free software; you can redistribute it and/or
+## modify it under the terms of the GNU General Public License
+## as published by the Free Software Foundation; either
+## version 2 of the License, or (at your option) any later version.
+
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+from functions import *
+
+class Background():
+ def __init__(self, playground):
+ self.playground = playground
+ self.backgrounds = {}
+ self.landscapes = {}
+
+ def add_background(self, filename, surface):
+ self.backgrounds[filename] = surface
+
+ def update_landscapes(self, landscapes):
+ self.landscapes = landscapes
+
+ def reset(self):
+ # Reset everything because the client has been signed off
+
+ # Remove backgrounds
+ for name in self.backgrounds.keys():
+ sh['downloader'].remove_usage(name)
+ self.backgrounds = {}
+
+ # Remove landscapes
+ self.landscapes = {}
+
+ def update_parent(self):
+ self.playground.update(Rect(0, 0, 1000, 700))
+
+ def update(self, surf, viewport, rect):
+ # Blit the background
+ viewport_left = viewport[0]
+ viewport_top = viewport[1]
+ viewport_width = 1000
+ viewport_height = 700
+
+ # Calculate the start and end positions of the background
+ bg_offset = (-viewport_left%250, -viewport_top%250)
+ x_min = bg_offset[0]-250
+ if x_min == -250: x_min = 0
+ x_max = x_min + 250 * ((float(viewport_width) / 250)+1)
+ x_max = int(x_max)
+ y_min = bg_offset[1]-250
+ if y_min == -250: y_min = 0
+ y_max = y_min + 250 * ((float(viewport_height) / 250)+1)
+ y_max = int(y_max)
+
+ # Find the blocks that are within rect
+ for y in range(y_min, y_max, 250):
+ for x in range(x_min, x_max, 250):
+ bg_rect = Rect(x, y, 250, 250)
+ if bg_rect.colliderect(rect):
+
+ background = self.backgrounds['bg-grass.png']
+ bg_area = Rect(
+ rect.left - bg_rect.left,
+ rect.top - bg_rect.top,
+ rect.width,
+ rect.height)
+
+ surf.blit(background, rect, bg_area)
Modified: trunk/client/timer.py
===================================================================
--- trunk/client/timer.py 2010-09-25 21:16:57 UTC (rev 410)
+++ trunk/client/timer.py 2010-09-26 22:16:14 UTC (rev 411)
@@ -53,7 +53,8 @@
# Do stuff
for name, info in self.callers.items():
if info[0](name, *info[1]):
- del self.callers[name]
+ try: del self.callers[name]
+ except: pass # This can happen due to threading. It's not bad
# Force one big update
sh['main'].updatewaiting = False
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-25 21:17:04
|
Revision: 410
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=410&view=rev
Author: BlueWolf_
Date: 2010-09-25 21:16:57 +0000 (Sat, 25 Sep 2010)
Log Message:
-----------
Finally made a proper engine for the viewport mover when walking with the avatar. Background temporary removed as it will be placed in a seperated file as well. Beware of weird effects while walking! :D
Modified Paths:
--------------
trunk/client/playground.py
trunk/client/playground_avatar.py
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-17 18:10:18 UTC (rev 409)
+++ trunk/client/playground.py 2010-09-25 21:16:57 UTC (rev 410)
@@ -19,6 +19,11 @@
import gui
from playground_avatar import Avatar
+POS_UPDATE_DELAY = 1 # Determines when a pos-update should be send.
+ # Every x seconds.
+MOVE_SPEED = 175 # How fast the avatar shoud walk
+
+
class Playground():
def __init__(self):
@@ -28,11 +33,11 @@
self.statuswhere = None
self.backgrounds = {}
+ self.viewport_float = None
self.viewport = None
self.direction = None
self.avatars = {}
self.this_user = None
- self.avatar_offset = None
def event(self, ev):
@@ -68,6 +73,7 @@
if direction == None and self.direction != None:
# Stop the timer. We are not walking
+ self.direction = None
sh['timer'].stop("playground-walk")
elif self.direction == None or \
@@ -77,7 +83,9 @@
self.direction = (direction, time.time(),
self.this_user['pos'][:])
sh['timer'].start("playground-walk",
- self.playground_walk)
+ self.timer_walk)
+ #sh['timer'].start("playground-pos-update",
+ # self.timer_walk, time.time())
def call(self, name, data):
@@ -89,10 +97,10 @@
sh['downloader'].remove_usage(name)
self.backgrounds = {}
self.viewport = None
+ self.viewport_float = None
self.direction = None
self.avatars = {}
self.this_user = None
- self.avatar_offset = None
elif data['status'] == "playground" and self.status != "playground":
# Load the data for the playground
@@ -101,26 +109,18 @@
self.this_user = sh['client'].userlist[sh['client'].cid]
for user in sh['client'].userlist.values():
if user['pos'] != None:
- self.avatars[user['cid']] = Avatar(user)
-
- to_center = (
- (self.surf.get_width()/2) - \
- (self.avatars[self.this_user['cid']].size[0]/2),
- (self.surf.get_height()/2) - \
- (self.avatars[self.this_user['cid']].size[1]/2),
- )
- self.avatar_offset = (
- self.this_user['pos'][0] - to_center[0],
- self.this_user['pos'][1] - to_center[1],\
- )
+ self.avatars[user['cid']] = Avatar(user, self)
- self.viewport = Rect(
- self.avatar_offset[0],
- self.avatar_offset[1],
- 1000,
- 700)
-
- self.playground_render()
+ avatar = self.avatars[self.this_user['cid']]
+ self.viewport_float = [
+ (self.this_user['pos'][0] - avatar.center[0]) - (1000/2),
+ (self.this_user['pos'][1] - avatar.center[1]) - (700/2),
+ ]
+ self.viewport = [
+ int(self.viewport_float[0]),
+ int(self.viewport_float[1])
+ ]
+ self.update()
self.status = data['status']
self.statuswhere = data['where']
@@ -136,56 +136,20 @@
"background", counter)
- def playground_render(self, rect = None, doupdate = True):
- # Render the playground
+ def update(self, rect = None, doupdate = True):
+ # This will blit and update the screen at rect
+
if rect == None:
rect = Rect(0, 0, 1000, 700)
else:
rect = Rect(rect)
# Blit the background
- bg_offset = (-self.viewport.left%250, -self.viewport.top%250)
- x_min = bg_offset[0]-250
- if x_min == -250: x_min = 0
- x_max = x_min + 250 * ((float(self.viewport.width) / 250)+1)
- x_max = int(x_max)
- y_min = bg_offset[1]-250
- if y_min == -250: y_min = 0
- y_max = y_min + 250 * ((float(self.viewport.height) / 250)+1)
- y_max = int(y_max)
+ #self.background.update(self.surf, self.viewport, rect)
- # Find the blocks that are within rect
- for y in range(y_min, y_max, 250):
- for x in range(x_min, x_max, 250):
- bg_rect = Rect(x, y, 250, 250)
- if bg_rect.colliderect(rect):
-
- background = self.backgrounds['bg-grass.png']
- bg_area = Rect(
- rect.left - bg_rect.left,
- rect.top - bg_rect.top,
- rect.width,
- rect.height)
-
- self.surf.blit(background, rect, bg_area)
-
# Blit the users
for avatar in self.avatars.values():
- avatar_rect = Rect(
- avatar.user['pos'][0] - self.viewport[0],
- avatar.user['pos'][1] - self.viewport[1],
- avatar.size[0],
- avatar.size[1],
- )
-
- if not rect.colliderect(avatar_rect): continue
-
- avatar_area = Rect(
- rect.left - avatar_rect.left,
- rect.top - avatar_rect.top,
- rect.width,
- rect.height)
- avatar.blit(self.surf, avatar_area)
+ avatar.update(self.surf, self.viewport, rect)
if doupdate:
sh['update'](rect)
@@ -206,35 +170,87 @@
})
- def playground_walk(self, name):
- direction, starttime, startpos = self.direction
- timeline = time.time() - starttime
- speed = 175
- move = timeline*speed
+ def timer_walk(self, name, starttime = None):
+ if name == "playground-walk":
+ direction, starttime, startpos = self.direction
+ timeline = time.time() - starttime
+ speed = MOVE_SPEED
+ move = timeline*speed
+
+ pos = self.this_user['pos'][:]
+ if direction == 0:
+ pos[1] = int(startpos[1] - move)
+ elif direction == 1:
+ pos[1] = int(startpos[1] - (move/1.7))
+ pos[0] = int(startpos[0] + (move/1.7))
+ elif direction == 2:
+ pos[0] = int(startpos[0] + move)
+ elif direction == 3:
+ pos[0] = int(startpos[0] + (move/1.7))
+ pos[1] = int(startpos[1] + (move/1.7))
+ elif direction == 4:
+ pos[1] = int(startpos[1] + move)
+ elif direction == 5:
+ pos[1] = int(startpos[1] + (move/1.7))
+ pos[0] = int(startpos[0] - (move/1.7))
+ elif direction == 6:
+ pos[0] = int(startpos[0] - move)
+ elif direction == 7:
+ pos[0] = int(startpos[0] - (move/1.7))
+ pos[1] = int(startpos[1] - (move/1.7))
+
+ avatar = self.avatars[self.this_user['cid']]
+ avatar.move(pos)
+ sh['timer'].start("playground-viewport-move",
+ self.timer_walk)
- if direction == 0:
- self.this_user['pos'][1] = startpos[1] - move
- elif direction == 1:
- self.this_user['pos'][1] = startpos[1] - (move/1.7)
- self.this_user['pos'][0] = startpos[0] + (move/1.7)
- elif direction == 2:
- self.this_user['pos'][0] = startpos[0] + move
- elif direction == 3:
- self.this_user['pos'][0] = startpos[0] + (move/1.7)
- self.this_user['pos'][1] = startpos[1] + (move/1.7)
- elif direction == 4:
- self.this_user['pos'][1] = startpos[1] + move
- elif direction == 5:
- self.this_user['pos'][1] = startpos[1] + (move/1.7)
- self.this_user['pos'][0] = startpos[0] - (move/1.7)
- elif direction == 6:
- self.this_user['pos'][0] = startpos[0] - move
- elif direction == 7:
- self.this_user['pos'][0] = startpos[0] - (move/1.7)
- self.this_user['pos'][1] = startpos[1] - (move/1.7)
- self.viewport.topleft = (
- self.this_user['pos'][0]+self.avatar_offset[0],
- self.this_user['pos'][1]+self.avatar_offset[1],
- )
- self.playground_render()
+ elif name == "playground-viewport-move":
+ # Move the viewport in a smooth way
+
+ # First get the current viewport pos and the desired pos
+ pos = self.viewport_float
+ avatar = self.avatars[self.this_user['cid']]
+ desired_pos = [
+ (self.this_user['pos'][0] - avatar.center[0]) - (1000/2),
+ (self.this_user['pos'][1] - avatar.center[1]) - (700/2)
+ ]
+
+ # Calculate the differences between these two positions.
+ # Hello Pythagoras!
+ distance = math.sqrt(
+ (pos[0] - desired_pos[0])**2 +
+ (pos[1] - desired_pos[1])**2)
+
+ if distance < 1:
+ self.viewport_float = desired_pos
+ else:
+ # Calculate how much we should move
+ speed = (distance/100000)
+
+ if speed > 0.9: speed = 0.9
+ speed += 0.05
+ move = [0,0]
+
+ move[0] = (desired_pos[0] - pos[0]) * speed
+ move[1] = (desired_pos[1] - pos[1]) * speed
+
+ self.viewport_float[0] += move[0]
+ self.viewport_float[1] += move[1]
+
+ # Keep in mind that pygame only likes integers, not floats
+ real_move = [
+ int(self.viewport_float[0] - self.viewport[0]),
+ int(self.viewport_float[1] - self.viewport[1])
+ ]
+ self.viewport[0] += real_move[0]
+ self.viewport[1] += real_move[1]
+
+ self.surf.scroll(-real_move[0], -real_move[1])
+ sh['update']()
+
+ if self.viewport_float == desired_pos: return True
+
+
+ elif name == "playground-pos-update":
+ pass
Modified: trunk/client/playground_avatar.py
===================================================================
--- trunk/client/playground_avatar.py 2010-09-17 18:10:18 UTC (rev 409)
+++ trunk/client/playground_avatar.py 2010-09-25 21:16:57 UTC (rev 410)
@@ -18,17 +18,55 @@
from functions import *
class Avatar():
- def __init__(self, user):
+ def __init__(self, user, playground):
self.user = user
- self.lastpos = user['pos']
+ self.playground = playground
self.avatar = None
self.size = (40,40)
+ self.center = (20, 40)
+
sh['downloader'].get_file("happyblock.png", "img", self.download)
+ def move(self, pos):
+ lastpos = self.user['pos']
+ self.user['pos'] = pos
+
+ self.update_parent()
+
def download(self, filename, cache):
self.avatar = cache
- def blit(self, surf, area):
- if self.avatar:
- surf.blit(self.avatar, (0,0), area)
+ self.update_parent()
+
+ def update_parent(self):
+ # Update ourself. Send it to our parent
+ self_rect = Rect(
+ self.user['pos'][0] - self.playground.viewport[0] -
+ self.center[0],
+ self.user['pos'][1] - self.playground.viewport[1] -
+ self.center[1],
+ self.size[0],
+ self.size[1])
+
+ if not Rect(0, 0, 1000, 700).colliderect(self_rect): return
+
+ self.playground.update(self_rect)
+
+ def update(self, surf, viewport, rect):
+ if not self.avatar: return
+
+ # Check if we collide
+ self_rect = Rect(
+ self.user['pos'][0] - viewport[0] - self.center[0],
+ self.user['pos'][1] - viewport[1] - self.center[1],
+ self.size[0],
+ self.size[1])
+
+ if not rect.colliderect(self_rect): return
+
+ surf.blit(self.avatar, rect, Rect(
+ rect.left - self_rect.left,
+ rect.top - self_rect.top,
+ rect.width,
+ rect.height))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-17 18:10:25
|
Revision: 409
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=409&view=rev
Author: BlueWolf_
Date: 2010-09-17 18:10:18 +0000 (Fri, 17 Sep 2010)
Log Message:
-----------
Moved the login-part to a seperate layer
Modified Paths:
--------------
trunk/client/VP.py
trunk/client/functions.py
trunk/client/gui.py
trunk/client/playground.py
Added Paths:
-----------
trunk/client/login.py
Modified: trunk/client/VP.py
===================================================================
--- trunk/client/VP.py 2010-09-15 19:04:32 UTC (rev 408)
+++ trunk/client/VP.py 2010-09-17 18:10:18 UTC (rev 409)
@@ -24,6 +24,7 @@
from playground import Playground
from layout import Layout
from windows import Windows
+from login import Login
from downloader import Downloader
from timer import Timer
from callback import Callback
@@ -64,6 +65,7 @@
sh['playground'] = Playground()
sh['layout'] = Layout()
sh['windows'] = Windows()
+ sh['login'] = Login()
self.update()
@@ -113,6 +115,7 @@
# Send through all the layers
if sh['windows'].event(ev): continue
if sh['layout'].event(ev): continue
+ if sh['login'].event(ev): continue
if sh['playground'].event(ev): continue
@@ -152,6 +155,7 @@
# The actual updating happens here
sh['screen'].blit(sh['playground'].surf, rect, rect)
+ sh['screen'].blit(sh['login'].surf, rect, rect)
sh['screen'].blit(sh['layout'].surf, rect, rect)
sh['screen'].blit(sh['windows'].surf, rect, rect)
@@ -161,6 +165,7 @@
log("debug", "Call:", name + ' - ' + str(data))
sh['playground'].call(name, data)
+ sh['login'].call(name, data)
sh['layout'].call(name, data)
sh['windows'].call(name, data)
Modified: trunk/client/functions.py
===================================================================
--- trunk/client/functions.py 2010-09-15 19:04:32 UTC (rev 408)
+++ trunk/client/functions.py 2010-09-17 18:10:18 UTC (rev 409)
@@ -22,10 +22,12 @@
from validate import Validator
import core
-# To get colors working in Windows
+# To get colors working in Windows. Though it works partially
if os.name == "nt":
- import colarama
- colarama.init()
+ try: import colarama
+ except: pass
+ else:
+ colarama.init()
VERSION = "0.0.1"
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-15 19:04:32 UTC (rev 408)
+++ trunk/client/gui.py 2010-09-17 18:10:18 UTC (rev 409)
@@ -36,6 +36,7 @@
self.rect = Rect(0, 0, 1000, 700)
self.parent_update = update
self.feedback = feedback
+ self.feedback.gui = self
self.frozen = True # Don't update until everything has been
# loaded
@@ -68,7 +69,10 @@
Append a child to this object
"""
- if feedback == None: feedback = self.feedback
+ if feedback == None:
+ feedback = self.feedback
+ else:
+ feedback.gui = self
obj = Obj(name, rect, self, self, feedback)
self.children.append(obj)
@@ -359,7 +363,10 @@
Append a child to this object
"""
- if feedback == None: feedback = self.feedback
+ if feedback == None:
+ feedback = self.feedback
+ else:
+ feedback.gui = self
obj = Obj(name, rect, self.main_parent, self)
self.children.append(obj)
Added: trunk/client/login.py
===================================================================
--- trunk/client/login.py (rev 0)
+++ trunk/client/login.py 2010-09-17 18:10:18 UTC (rev 409)
@@ -0,0 +1,225 @@
+## This file is part of Virtual Playground
+## Copyright (c) 2009 Jos Ratsma + Koen Koning
+
+## This program is free software; you can redistribute it and/or
+## modify it under the terms of the GNU General Public License
+## as published by the Free Software Foundation; either
+## version 2 of the License, or (at your option) any later version.
+
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+from functions import *
+import gui
+
+class Login():
+ def __init__(self):
+ self.surf = pygame.Surface((1000, 700)).convert()
+
+ self.status = None
+ self.statuswhere = None
+
+ self.transit = None
+ self.background = None
+ self.loginbox = None
+ self.font = None
+ self.gui = None
+
+ def event(self, ev):
+ if self.status == "login":
+
+ # Some temporary debug stuff
+ if ev.type == KEYDOWN and ev.key == K_F1:
+ # Fake signup
+ sh['client'].signup("test123", sha1("test123").hexdigest(),
+ {
+ "realname": "Pietje Precies",
+ "email": "sp...@sp..."
+ })
+
+ if self.gui != None:
+ return self.gui.event(ev)
+
+
+ def call(self, name, data):
+ if name == "status": # A status update
+ if data['status'] == "login":
+ if self.status != "login":
+ # Load the data for the login
+ self.surf.set_alpha(None)
+ self.background = load_image(False, "images", "loginbg.png")
+ self.loginbox = load_image(True, "images", "loginbox.png")
+ self.font = pygame.font.Font(real_path("fonts", \
+ "DejaVuSans.ttf"), 35)
+
+
+ if data['where'] in ["connecting", "waiting", "logging in",
+ "downloading"]:
+ self.drawlogin(data['where'])
+
+ elif data['status'] != "login" and self.status == "login":
+ # Unload data from the login
+ self.background = None
+ self.loginbox = None
+ self.font = None
+ self.gui = None
+ self.transit = 255
+ sh['timer'].start("login-transit", self.timer, time.time())
+
+ self.status = data['status']
+ self.statuswhere = data['where']
+
+ def drawlogin(self, status):
+ self.surf.blit(self.background, (0,0))
+
+ if status == "connecting": # Showing text
+
+ text = self.font.render("Connecting...", True, (132,125,114))
+ posleft = (1000/2)-(text.get_width()/2)
+ self.surf.blit(text, (posleft, 330))
+
+ elif status == "waiting": # Showing loginbox
+ self.surf.blit(self.loginbox, (292,256))
+
+ # Create login-field
+ self.gui = gui.Container(self.gui_draw, LoginFeedback())
+
+ usrlabel = self.gui.add(gui.Label, "usrlabel", \
+ (345, 265, 310, 18))
+ usrlabel.caption = "Username:"
+ usrlabel.align = 1
+ usrlabel.color = [177, 93, 39]
+ usrlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
+
+ usr = self.gui.add(gui.Textbox, "usrtextbox", (345, 285, 310, 37))
+ usr.set_style("login")
+
+ pwdlabel = self.gui.add(gui.Label, "pwdlabel", \
+ (345, 330, 310, 18))
+ pwdlabel.caption = "Password:"
+ pwdlabel.align = 1
+ pwdlabel.color = [177, 93, 39]
+ pwdlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
+
+ pwd = self.gui.add(gui.Textbox, "pwdtextbox", (345, 350, 310, 37))
+ pwd.set_style("login")
+ pwd.set_type("password")
+
+ login = self.gui.add(gui.Button, "loginbutton", (425, 398, 151, 34))
+ login.caption = "Log in!"
+ login.set_style("login")
+
+ signup = self.gui.add(gui.Link, "signuplink", (345, 470, 310, 18))
+ signup.caption = "Don't have an account yet?"
+ signup.align = 1
+ signup.color = [140, 74, 31]
+ signup.color_hover = [177, 93, 39]
+ signup.color_click = [255, 217, 192]
+ signup.set_font(("fonts", "DejaVuSans.ttf"), 12)
+
+ self.gui.give_focus(usr)
+ self.gui.unfreeze()
+
+
+ elif status == "logging in": # Showing text
+ text = self.font.render("Logging in...", True, (132,125,114))
+ posleft = (1000/2)-(text.get_width()/2)
+ self.surf.blit(text, (posleft, 330))
+
+
+ elif status == "downloading": # Showing text
+ text = self.font.render("Downloading...", True, (132,125,114))
+ posleft = (1000/2)-(text.get_width()/2)
+ self.surf.blit(text, (posleft, 330))
+
+ sh['update']()
+
+ def gui_draw(self, rect):
+ if self.gui == None: return
+
+ self.surf.blit(self.background, rect, rect)
+ self.surf.blit(self.loginbox, (292, 256))
+ self.surf.blit(self.gui.surf, rect, rect)
+
+ sh['update'](rect)
+
+
+ def timer(self, name, starttime):
+ if name == "login-transit":
+ length = 1.0
+ timeline = (time.time() - starttime) / length
+ if timeline > 1:
+ self.transit = None
+ self.surf.fill([0,0,0,0])
+ self.surf.set_alpha(0)
+ sh['update']()
+ return True
+ else:
+ self.transit = (1-timeline)*255
+ self.surf.set_alpha(self.transit)
+ sh['update']()
+
+
+class LoginFeedback(gui.Feedback):
+ def keypress(self, obj, ev):
+ if obj.name == "usrtextbox":
+ # Using the enter key in the username field
+ if ev.type == KEYUP and ev.key == K_RETURN:
+ self.gui.give_focus("pwdtextbox")
+
+ elif obj.name == "pwdtextbox":
+ # Using the enter key in the password field
+ if ev.type == KEYDOWN and ev.key == K_RETURN:
+ self.gui['loginbutton'].manualpush(True)
+
+ elif ev.type == KEYUP and ev.key == K_RETURN:
+ self.gui['loginbutton'].manualpush(False)
+ self.gui['loginbutton'].submit()
+
+
+ def submit(self, obj):
+ # Clicking the login button
+ if obj.name == "loginbutton":
+ usr = self.gui['usrtextbox'].input
+ pwd = sha1(self.gui['pwdtextbox'].input).hexdigest()
+
+ sh['main'].call("status", {
+ "status": "login",
+ "where": "logging in"
+ })
+
+ # Save the info so it can be saved if the login succeeds
+ sh['login_info'] = (usr,pwd)
+
+ sh['client'].login(usr, pwd)
+
+ elif obj.name == "signuplink":
+
+ if self.gui.has("signup"): return
+
+ # Create signup window
+ window = self.gui.add(gui.Window, "signup", \
+ Rect(300, 140, 400, 420), SignupFeedback())
+ window.caption = "Signup"
+
+ #window.add(gui.
+
+ window.unfreeze()
+
+
+ def mousedown(self, obj):
+ if obj.name == "usrlabel":
+ self.gui.give_focus('usrtextbox')
+
+ elif obj.name == "pwdlabel":
+ self.gui.give_focus('pwdtextbox')
+
+
+class SignupFeedback(gui.Feedback):
+ pass
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-15 19:04:32 UTC (rev 408)
+++ trunk/client/playground.py 2010-09-17 18:10:18 UTC (rev 409)
@@ -24,20 +24,9 @@
def __init__(self):
self.surf = pygame.Surface((1000, 700)).convert()
- self.surf.fill([0,0,0])
self.status = None
self.statuswhere = None
- self.oldsurf = None
- self.transit = None
-
- # Login stuff
- self.loginbg = None
- self.loginbox = None
- self.loginfont = None
- self.logingui = None
-
- # Playground stuff
self.backgrounds = {}
self.viewport = None
self.direction = None
@@ -47,22 +36,7 @@
def event(self, ev):
- if self.status == "login":
-
- # Some temporary debug stuff
- if ev.type == KEYDOWN and ev.key == K_F1:
- # Fake signup
- sh['client'].signup("test123", sha1("test123").hexdigest(),
- {
- "realname": "Pietje Precies",
- "email": "sp...@sp..."
- })
-
- if self.logingui != None:
- return self.logingui.event(ev)
-
-
- elif self.status == "playground":
+ if self.status == "playground":
if ev.type == KEYDOWN or ev.type == KEYUP:
if ev.key in [K_UP, K_DOWN, K_LEFT, K_RIGHT]:
@@ -108,80 +82,46 @@
def call(self, name, data):
if name == "status": # A status update
- if data['status'] == "login":
- if data['status'] != self.status:
- # Unload data from the playground
- if self.status != None:
- sh['timer'].stop("playground-transit")
- sh['timer'].stop("playground-move")
- for name in self.backgrounds.keys():
- sh['downloader'].remove_usage(name)
- self.backgrounds = {}
- self.viewport = None
- self.direction = None
- self.avatars = {}
- self.this_user = None
- self.avatar_offset = None
-
- # Load the data for the login
- self.loginbg = load_image(False, "images", "loginbg.png")
- self.loginbox = load_image(True, "images", "loginbox.png")
- self.loginfont = pygame.font.Font(real_path("fonts", \
- "DejaVuSans.ttf"), 35)
- self.loginfeedback = LoginFeedback(self)
-
+ if data['status'] == "login" and self.status == "playground":
+ # Unload data from the playground
+ sh['timer'].stop("playground-move")
+ for name in self.backgrounds.keys():
+ sh['downloader'].remove_usage(name)
+ self.backgrounds = {}
+ self.viewport = None
+ self.direction = None
+ self.avatars = {}
+ self.this_user = None
+ self.avatar_offset = None
+
+ elif data['status'] == "playground" and self.status != "playground":
+ # Load the data for the playground
- if data['where'] == "connecting":
- self.drawlogin("connecting")
-
- elif data['where'] == "waiting":
- self.drawlogin("login")
-
- elif data['where'] == "logging in":
- self.drawlogin("logging in")
-
- elif data['where'] == "downloading":
- self.drawlogin("downloading")
+ # Load all users
+ self.this_user = sh['client'].userlist[sh['client'].cid]
+ for user in sh['client'].userlist.values():
+ if user['pos'] != None:
+ self.avatars[user['cid']] = Avatar(user)
+
+ to_center = (
+ (self.surf.get_width()/2) - \
+ (self.avatars[self.this_user['cid']].size[0]/2),
+ (self.surf.get_height()/2) - \
+ (self.avatars[self.this_user['cid']].size[1]/2),
+ )
+ self.avatar_offset = (
+ self.this_user['pos'][0] - to_center[0],
+ self.this_user['pos'][1] - to_center[1],\
+ )
+
+ self.viewport = Rect(
+ self.avatar_offset[0],
+ self.avatar_offset[1],
+ 1000,
+ 700)
+
+ self.playground_render()
- elif data['status'] == "playground":
- if data['status'] != self.status:
- # Unload data from the login
- self.loginbg = None
- self.loginbox = None
- self.loginfont = None
- self.logingui = None
-
- # Load the data for the playground
-
- # Load all users
- self.this_user = sh['client'].userlist[sh['client'].cid]
- for user in sh['client'].userlist.values():
- if user['pos'] != None:
- self.avatars[user['cid']] = Avatar(user)
-
- to_center = (
- (self.surf.get_width()/2) - \
- (self.avatars[self.this_user['cid']].size[0]/2),
- (self.surf.get_height()/2) - \
- (self.avatars[self.this_user['cid']].size[1]/2),
- )
- self.avatar_offset = (
- self.this_user['pos'][0] - to_center[0],
- self.this_user['pos'][1] - to_center[1],\
- )
-
- self.viewport = Rect(
- self.avatar_offset[0],
- self.avatar_offset[1],
- 1000,
- 700)
-
- self.oldsurf = self.surf.copy()
- self.transit = 1
- self.playground_render(None, True)
- sh['timer'].start("playground-transit", self.timer, \
- time.time())
-
self.status = data['status']
self.statuswhere = data['where']
@@ -196,85 +136,6 @@
"background", counter)
- def drawlogin(self, status):
- self.loginstatus = status
- self.surf.blit(self.loginbg, (0,0))
-
- if status == "connecting":
-
- text = self.loginfont.render("Connecting...", True, (132,125,114))
- posleft = (1000/2)-(text.get_size()[0]/2)
- self.surf.blit(text, (posleft, 330))
-
- elif status == "login":
- self.surf.blit(self.loginbox, (292,256))
-
- # Create login-field
- self.logingui = gui.Container(self.logingui_draw, \
- LoginFeedback(self))
- self.logingui.can_lose_focus = False
-
- usrlabel = self.logingui.add(gui.Label, "usrlabel", \
- (345, 265, 310, 18))
- usrlabel.caption = "Username:"
- usrlabel.align = 1
- usrlabel.color = [177, 93, 39]
- usrlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
-
- usr = self.logingui.add(gui.Textbox, "usrtextbox", (345, 285, 310, 37))
- usr.set_style("login")
-
- pwdlabel = self.logingui.add(gui.Label, "pwdlabel", \
- (345, 330, 310, 18))
- pwdlabel.caption = "Password:"
- pwdlabel.align = 1
- pwdlabel.color = [177, 93, 39]
- pwdlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
-
- pwd = self.logingui.add(gui.Textbox, "pwdtextbox", (345, 350, 310, 37))
- pwd.set_style("login")
- pwd.set_type("password")
-
- login = self.logingui.add(gui.Button, "loginbutton", (425, 398, 151, 34))
- login.caption = "Log in!"
- login.set_style("login")
-
- signup = self.logingui.add(gui.Link, "signuplink", (345, 470, 310, 18))
- signup.caption = "Don't have an account yet?"
- signup.align = 1
- signup.color = [140, 74, 31]
- signup.color_hover = [177, 93, 39]
- signup.color_click = [255, 217, 192]
- signup.set_font(("fonts", "DejaVuSans.ttf"), 12)
-
- self.logingui.give_focus(usr)
- self.logingui.unfreeze()
-
-
- elif status == "logging in":
- text = self.loginfont.render("Logging in...", True, (132,125,114))
- posleft = (1000/2)-(text.get_size()[0]/2)
- self.surf.blit(text, (posleft, 330))
-
-
- elif status == "downloading":
- text = self.loginfont.render("Downloading...", True, (132,125,114))
- posleft = (1000/2)-(text.get_size()[0]/2)
- self.surf.blit(text, (posleft, 330))
-
- sh['update']()
-
- def logingui_draw(self, rect):
- if self.logingui == None: return
-
- self.surf.blit(self.loginbg, rect, rect)
- self.surf.blit(self.loginbox, (292, 256))
- self.surf.blit(self.logingui.surf, rect, rect)
-
- sh['update'](rect)
-
-
-
def playground_render(self, rect = None, doupdate = True):
# Render the playground
if rect == None:
@@ -326,11 +187,6 @@
rect.height)
avatar.blit(self.surf, avatar_area)
-
- if self.transit != None: # An transition is happening
- self.oldsurf.set_alpha(self.transit*255)
- self.surf.blit(self.oldsurf, (0,0))
-
if doupdate:
sh['update'](rect)
@@ -348,19 +204,6 @@
"status": "playground",
"where": "playground"
})
-
- def timer(self, name, starttime):
- if name == "playground-transit":
- length = 1
- timeline = (time.time() - starttime) / length
-
- if timeline > 1:
- self.transit = None
- self.playground_render()
- return True
-
- self.transit = 1 - timeline
- self.playground_render()
def playground_walk(self, name):
@@ -394,67 +237,4 @@
self.this_user['pos'][0]+self.avatar_offset[0],
self.this_user['pos'][1]+self.avatar_offset[1],
)
- self.playground_render()
-
-
-class LoginFeedback(gui.Feedback):
- def __init__(self, parent):
- self.parent = parent
-
- def keypress(self, obj, ev):
- if obj.name == "usrtextbox":
- # Using the enter key in the username field
- if ev.type == KEYUP and ev.key == K_RETURN:
- self.parent.logingui.give_focus("pwdtextbox")
-
- elif obj.name == "pwdtextbox":
- # Using the enter key in the password field
- if ev.type == KEYDOWN and ev.key == K_RETURN:
- self.parent.logingui['loginbutton'].manualpush(True)
-
- elif ev.type == KEYUP and ev.key == K_RETURN:
- self.parent.logingui['loginbutton'].manualpush(False)
- self.parent.logingui['loginbutton'].submit()
-
-
- def submit(self, obj):
- # Clicking the login button
- if obj.name == "loginbutton":
- usr = self.parent.logingui['usrtextbox'].input
- pwd = sha1(self.parent.logingui['pwdtextbox'].input).hexdigest()
-
- self.parent.logingui = None
- sh['main'].call("status", {
- "status": "login",
- "where": "logging in"
- })
-
- # Save the info so it can be saved it the login succeeds
- sh['login_info'] = (usr,pwd)
-
- sh['client'].login(usr, pwd)
-
- elif obj.name == "signuplink":
-
- if self.parent.logingui.has("signup"): return
-
- # Create signup window
- window = self.parent.logingui.add(gui.Window, "signup", \
- Rect(300, 140, 400, 420), SignupFeedback())
- window.caption = "Signup"
-
- #window.add(gui.
-
- window.unfreeze()
-
-
- def mousedown(self, obj):
- if obj.name == "usrlabel":
- self.parent.logingui.give_focus('usrtextbox')
-
- elif obj.name == "pwdlabel":
- self.parent.logingui.give_focus('pwdtextbox')
-
-
-class SignupFeedback(gui.Feedback):
- pass
+ self.playground_render()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-15 19:04:39
|
Revision: 408
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=408&view=rev
Author: BlueWolf_
Date: 2010-09-15 19:04:32 +0000 (Wed, 15 Sep 2010)
Log Message:
-----------
error.message is decrepated. Changing it to str(error)
Modified Paths:
--------------
trunk/server/core/parser.py
trunk/server/core/server.py
Modified: trunk/server/core/parser.py
===================================================================
--- trunk/server/core/parser.py 2010-09-15 18:41:24 UTC (rev 407)
+++ trunk/server/core/parser.py 2010-09-15 19:04:32 UTC (rev 408)
@@ -116,7 +116,7 @@
pwd = rsa.decrypt(msg['pwd'], client['rsa'])
except Exception, error:
self.call.error("rsa", error.__class__.__name__ + " - " + \
- error.message)
+ str(error))
return True
@@ -271,7 +271,7 @@
pwd = rsa.decrypt(msg['pwd'], client['rsa'])
except Exception, error:
self.call.error("rsa", error.__class__.__name__ + " - " + \
- error.message)
+ str(error))
return True
# Double sha, so no one can insert "raw" sha
Modified: trunk/server/core/server.py
===================================================================
--- trunk/server/core/server.py 2010-09-15 18:41:24 UTC (rev 407)
+++ trunk/server/core/server.py 2010-09-15 19:04:32 UTC (rev 408)
@@ -330,7 +330,7 @@
parsed = simplejson.loads(msg)
except Exception, error:
self.__call.error("json", error.__class__.__name__ \
- + " - " + error.message + " - " + repr(msg))
+ + " - " + str(error) + " - " + repr(msg))
self.close_msg("crash")
return
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-15 18:41:32
|
Revision: 407
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=407&view=rev
Author: BlueWolf_
Date: 2010-09-15 18:41:24 +0000 (Wed, 15 Sep 2010)
Log Message:
-----------
Added a better handling for rsa en json-parse errors. These aren't really errors but warnings and are known to happen. App can optionally catch these warnings
Modified Paths:
--------------
trunk/server/callback.py
trunk/server/core/callback.py
trunk/server/core/parser.py
trunk/server/core/server.py
Modified: trunk/server/callback.py
===================================================================
--- trunk/server/callback.py 2010-09-15 17:45:24 UTC (rev 406)
+++ trunk/server/callback.py 2010-09-15 18:41:24 UTC (rev 407)
@@ -56,7 +56,10 @@
return False
else:
return result['username']
-
+
+ def error(self, name, reason):
+ log("warning", "Error '" + name + "' occured: " + reason)
+
def signup(self, cid, usr, pwd, extra):
db.execute("SELECT `id` FROM `users` WHERE `username`=%s", usr)
Modified: trunk/server/core/callback.py
===================================================================
--- trunk/server/core/callback.py 2010-09-15 17:45:24 UTC (rev 406)
+++ trunk/server/core/callback.py 2010-09-15 18:41:24 UTC (rev 407)
@@ -171,6 +171,25 @@
pass
+ def error(self, name, reason):
+ """
+ When something within the code goes wrong or unexpected (like a
+ json or rsa-parse error, which don't need a complete traceback, they
+ will be dumped into this function. You can safely ignore this message,
+ the server should continue working normally
+
+ name:
+ Which error this is.
+ * rsa
+ * json
+
+ reason:
+ String with the reason of this error
+
+ This is a placeholder. If you want to catch this event, overwrite this
+ in your own callback class.
+ """
+
def check_login(self, cid, usr, pwd):
"""
This is used to verify the user's login. Return the real username* when
Modified: trunk/server/core/parser.py
===================================================================
--- trunk/server/core/parser.py 2010-09-15 17:45:24 UTC (rev 406)
+++ trunk/server/core/parser.py 2010-09-15 18:41:24 UTC (rev 407)
@@ -39,7 +39,7 @@
func = getattr(self, str(head), None)
if (func):
- func(cid, body)
+ return func(cid, body)
def _check_double_user(self, isbot, screenname, data):
"""
@@ -112,7 +112,13 @@
# Decrypt the password
- pwd = rsa.decrypt(msg['pwd'], client['rsa'])
+ try:
+ pwd = rsa.decrypt(msg['pwd'], client['rsa'])
+ except Exception, error:
+ self.call.error("rsa", error.__class__.__name__ + " - " + \
+ error.message)
+ return True
+
# Double sha, so no one can insert "raw" sha
pwd = hashlib.sha1(pwd).hexdigest()
@@ -261,7 +267,13 @@
connection = client['con']
# Decrypt the password
- pwd = rsa.decrypt(msg['pwd'], client['rsa'])
+ try:
+ pwd = rsa.decrypt(msg['pwd'], client['rsa'])
+ except Exception, error:
+ self.call.error("rsa", error.__class__.__name__ + " - " + \
+ error.message)
+ return True
+
# Double sha, so no one can insert "raw" sha
pwd = hashlib.sha1(pwd).hexdigest()
@@ -286,4 +298,4 @@
"""
self.call.custom(cid, msg['header'], msg['body'])
-
\ No newline at end of file
+
Modified: trunk/server/core/server.py
===================================================================
--- trunk/server/core/server.py 2010-09-15 17:45:24 UTC (rev 406)
+++ trunk/server/core/server.py 2010-09-15 18:41:24 UTC (rev 407)
@@ -326,12 +326,25 @@
for msg in data:
try:
- self.__parser(self.__cid, simplejson.loads(msg))
- except Exception, Er:
+ try:
+ parsed = simplejson.loads(msg)
+ except Exception, error:
+ self.__call.error("json", error.__class__.__name__ \
+ + " - " + error.message + " - " + repr(msg))
+ self.close_msg("crash")
+ return
+
+ if self.__parser(self.__cid, parsed):
+ # Force to close the connection due to an error
+ self.close_msg("crash")
+ return
+
+ except Exception, error:
self.__parser_crash()
# Kick connection
self.close_msg("crash")
+ return
def close(self, reason = "manual"):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-15 17:45:30
|
Revision: 406
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=406&view=rev
Author: BlueWolf_
Date: 2010-09-15 17:45:24 +0000 (Wed, 15 Sep 2010)
Log Message:
-----------
Added a proper config for the core and made a lock for the database
Modified Paths:
--------------
trunk/server/VPS.py
trunk/server/core/server.py
trunk/server/database.py
trunk/server/functions.py
Modified: trunk/server/VPS.py
===================================================================
--- trunk/server/VPS.py 2010-09-14 21:23:27 UTC (rev 405)
+++ trunk/server/VPS.py 2010-09-15 17:45:24 UTC (rev 406)
@@ -90,7 +90,9 @@
log('debug', "Done, found %s landscapes." % len(landscapes.list))
- server = core.Server(config, Callback())
+ server = core.Server({
+ "max-connections": 100
+ }, Callback())
server.start_server()
# Now we sit back and let the server do its stuff. Only stop at
Modified: trunk/server/core/server.py
===================================================================
--- trunk/server/core/server.py 2010-09-14 21:23:27 UTC (rev 405)
+++ trunk/server/core/server.py 2010-09-15 17:45:24 UTC (rev 406)
@@ -54,7 +54,7 @@
The port the server should listen on. Should be int between
1 and 65535. Note that everything lower than 100 usually needs to
be run as root under Unix/Linux.
- Default is 5162.
+ Default is 6653.
-max_connections:
Maximum amount of clients that can be connected simultaneously.
Modified: trunk/server/database.py
===================================================================
--- trunk/server/database.py 2010-09-14 21:23:27 UTC (rev 405)
+++ trunk/server/database.py 2010-09-15 17:45:24 UTC (rev 406)
@@ -15,7 +15,7 @@
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-import sys
+import sys, threading
try: import MySQLdb
except: sys.exit("ERROR: You need the MySQLdb-module for this to work!")
@@ -26,7 +26,8 @@
self.host = host
self.database = database
self.user = user
- self.passwd = passwd
+ self.passwd = passwd
+ self.lock = threading.Lock()
self._connect()
@@ -56,6 +57,8 @@
# Uncomment for mysql-debugging!
#print '\tMySQLdb.' + attr + repr(arg)
+
+ self.lock.acquire()
func = getattr(self.db, attr)
try:
@@ -67,7 +70,10 @@
dbfunc = func(*arg)
else: # Some other error we don't care about
raise MySQLdb.OperationalError, message
-
+
+ finally:
+ self.lock.release()
+
return dbfunc
return exc
Modified: trunk/server/functions.py
===================================================================
--- trunk/server/functions.py 2010-09-14 21:23:27 UTC (rev 405)
+++ trunk/server/functions.py 2010-09-15 17:45:24 UTC (rev 406)
@@ -16,7 +16,7 @@
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os, sys, time, hashlib
-from getpass import getpass
+from getpass import getpass
import database
from filetable import FileTable
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-14 21:23:33
|
Revision: 405
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=405&view=rev
Author: BlueWolf_
Date: 2010-09-14 21:23:27 +0000 (Tue, 14 Sep 2010)
Log Message:
-----------
Better colors with screen (the program) now
Modified Paths:
--------------
trunk/server/callback.py
trunk/server/functions.py
Modified: trunk/server/callback.py
===================================================================
--- trunk/server/callback.py 2010-09-14 19:28:33 UTC (rev 404)
+++ trunk/server/callback.py 2010-09-14 21:23:27 UTC (rev 405)
@@ -23,9 +23,9 @@
def __init__(self):
self.clients = {}
def data_received(self, cid, data):
- log('sendin', cid + ": " + repr(data))
+ log('recv', cid + ": " + repr(data))
def data_send(self, cid, data):
- log('sendout', cid + ": " + repr(data))
+ log('send', cid + ": " + repr(data))
def debug_crash(self, traceback):
log('error', "\n*** Crash ***\n\n%s\n" % traceback)
Modified: trunk/server/functions.py
===================================================================
--- trunk/server/functions.py 2010-09-14 19:28:33 UTC (rev 404)
+++ trunk/server/functions.py 2010-09-14 21:23:27 UTC (rev 405)
@@ -24,6 +24,13 @@
try: from configobj import ConfigObj
except: sys.exit("ERROR: You need the configobj-module for this to work!")
+
+# To get colors working in Windows. Though it works partially
+if os.name == "nt":
+ try: import colarama
+ except: pass
+ else:
+ colarama.init()
def config_defaults(config):
@@ -71,54 +78,54 @@
config['database']['password'] = getpass("Database password: ")
-def log(t, *m):
- def level(i):
- return config['debug']['level'] >= i
- use_colors = config['debug']['use_colors']
- write = sys.stdout.write
- def color(c):
- write("\033[" + c + "m")
-
- message = "\t".join([str(part) for part in m])
-
- if t == "error" and level(1):
- icon = "!!!"
- icon_color = "1;31;7"
- text_color = "1;91"
-
- elif t == "warning" and level(2):
- icon = "[!]"
- icon_color = "1;33;7"
- text_color = "93"
-
- elif t == "succeed" and level(3):
- icon = "OK "
- icon_color = "1;32;7"
- text_color = "32"
-
- elif t == "debug" and level(4):
- icon = " ~ "
- icon_color = "1;7"
- text_color = ""
-
- elif t == "sendin" and level(5):
- icon = "|<-"
- icon_color = "1;100;2"
- text_color = "2"
-
- elif t == "sendout" and level(5):
- icon = "|->"
- icon_color = "1;100;2"
- text_color = "2"
-
- else:
- return
-
- if use_colors: color(icon_color)
- write(" " + icon + " ")
- if use_colors: color("0;" + text_color)
- write("\t" + message)
- if use_colors: color("0")
+def log(t, *m):
+ def level(i):
+ return config['debug']['level'] >= i
+ use_colors = config['debug']['use_colors']
+ write = sys.stdout.write
+ def color(c):
+ write("\033[" + c + "m")
+
+ message = "\t".join([str(part) for part in m])
+
+ if t == "error" and level(1):
+ icon = "!!!"
+ icon_color = "1;31;7"
+ text_color = "1;91"
+
+ elif t == "warning" and level(2):
+ icon = "[!]"
+ icon_color = "1;33;7"
+ text_color = "93"
+
+ elif t == "succeed" and level(3):
+ icon = "OK "
+ icon_color = "1;32;7"
+ text_color = "32"
+
+ elif t == "debug" and level(4):
+ icon = " ~ "
+ icon_color = "1;7"
+ text_color = ""
+
+ elif t == "recv" and level(5):
+ icon = "|<-"
+ icon_color = "1;90;7"
+ text_color = "90"
+
+ elif t == "send" and level(5):
+ icon = "|->"
+ icon_color = "1;90;7"
+ text_color = "90"
+
+ else:
+ return
+
+ if use_colors: color(icon_color)
+ write(" " + icon + " ")
+ if use_colors: color("0;" + text_color)
+ write("\t" + message)
+ if use_colors: color("0")
write("\n")
@@ -138,4 +145,4 @@
landscapes = LandscapeManager(db)
-
\ No newline at end of file
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-14 19:28:39
|
Revision: 404
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=404&view=rev
Author: BlueWolf_
Date: 2010-09-14 19:28:33 +0000 (Tue, 14 Sep 2010)
Log Message:
-----------
Fixed the colarama thingy
Modified Paths:
--------------
trunk/client/functions.py
Modified: trunk/client/functions.py
===================================================================
--- trunk/client/functions.py 2010-09-12 14:27:52 UTC (rev 403)
+++ trunk/client/functions.py 2010-09-14 19:28:33 UTC (rev 404)
@@ -23,7 +23,9 @@
import core
# To get colors working in Windows
-if os.name == "nt": import colerama
+if os.name == "nt":
+ import colarama
+ colarama.init()
VERSION = "0.0.1"
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-12 14:27:58
|
Revision: 403
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=403&view=rev
Author: BlueWolf_
Date: 2010-09-12 14:27:52 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
Changed some log-stuff for windows and screen
Modified Paths:
--------------
trunk/client/callback.py
trunk/client/functions.py
Modified: trunk/client/callback.py
===================================================================
--- trunk/client/callback.py 2010-09-12 01:01:32 UTC (rev 402)
+++ trunk/client/callback.py 2010-09-12 14:27:52 UTC (rev 403)
@@ -25,12 +25,12 @@
def data_received(self, data):
name = data.keys()[0]
value = data[name]
- log("sendin", name + " - " + repr(data))
+ log("recv", name + " - " + repr(data))
def data_send(self, data):
name = data.keys()[0]
value = data[name]
- log("sendout", name + " - " + repr(data))
+ log("send", name + " - " + repr(data))
def connection_ready(self, public_rsa, reconnecting):
# We are connected
Modified: trunk/client/functions.py
===================================================================
--- trunk/client/functions.py 2010-09-12 01:01:32 UTC (rev 402)
+++ trunk/client/functions.py 2010-09-12 14:27:52 UTC (rev 403)
@@ -22,6 +22,10 @@
from validate import Validator
import core
+# To get colors working in Windows
+if os.name == "nt": import colerama
+
+
VERSION = "0.0.1"
# This will be used to [sh]are all variables, functions and classes across the
@@ -119,15 +123,15 @@
icon_color = "1;7"
text_color = ""
- elif t == "sendin" and level(5):
+ elif t == "recv" and level(5):
icon = "|<-"
- icon_color = "1;100;2"
- text_color = "2"
+ icon_color = "1;90;7"
+ text_color = "90"
- elif t == "sendout" and level(5):
+ elif t == "send" and level(5):
icon = "|->"
- icon_color = "1;100;2"
- text_color = "2"
+ icon_color = "1;90;7"
+ text_color = "90"
else:
return
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ch...@us...> - 2010-09-12 01:01:38
|
Revision: 402
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=402&view=rev
Author: chozone
Date: 2010-09-12 01:01:32 +0000 (Sun, 12 Sep 2010)
Log Message:
-----------
Implemented the log system of the client in the server.
Some messages should probably be changed and better categorized, but it's a start.
Modified Paths:
--------------
trunk/server/VPS.py
trunk/server/callback.py
trunk/server/filetable.py
trunk/server/functions.py
trunk/server/landscapes.py
Modified: trunk/server/VPS.py
===================================================================
--- trunk/server/VPS.py 2010-09-11 23:32:12 UTC (rev 401)
+++ trunk/server/VPS.py 2010-09-12 01:01:32 UTC (rev 402)
@@ -24,7 +24,7 @@
def check_database():
- print "Checking database..."
+ log('debug', "Checking database...")
db.execute("SHOW TABLES")
ret = db.fetchall()
db_tables = [i.values()[0] for i in ret]
@@ -34,7 +34,7 @@
for t in req_tables:
if t not in db_tables:
- print "Creating table `%s`..."%t
+ log('debug', "Creating table `%s`..."%t)
db.execute(db_dump[t])
@@ -43,7 +43,7 @@
# Users table has no admins
create_account_setup()
- print "Database check done."
+ log('debug', "Database check done.")
def create_account_setup():
# Ask user if he wants to create an account (1st one, admin)
@@ -75,28 +75,37 @@
VALUES (NULL, %s, %s, 'admin', 0, '', '', '', NOW(), '127.0.0.1')",
(username, password))
- print "Created user '%s'!"%username
+ log('succeed', "Created user '%s'!"%username)
-check_database()
+def main():
+ check_database()
+
+ log('debug', "Retrieving file table from database...")
+ file_table.update_from_database()
+ log('debug', "Done, %s entries in file table." % len(file_table.table))
+
+ log('debug', "Retrieving landscapes from database...")
+ landscapes.update_from_database()
+ log('debug', "Done, found %s landscapes." % len(landscapes.list))
-file_table.update_from_database()
-landscapes.update_from_database()
+
+ server = core.Server(config, Callback())
+ server.start_server()
-
-server = core.Server(config, Callback())
-server.start_server()
+ # Now we sit back and let the server do its stuff. Only stop at
+ # KeyboardInterrupts (^C).
+ # TODO: *some* interactivity here? (so you can type in commands)
+ try:
+ while 1:
+ time.sleep(100)
-# Now we sit back and let the server do its stuff. Only stop at
-# KeyboardInterrupts (^C).
-# TODO: *some* interactivity here? (so you can type in commands)
-try:
- while 1:
- time.sleep(100)
+ except KeyboardInterrupt:
+ pass
-except KeyboardInterrupt:
- print
+
+ server.exit()
+ log('succeed', "Server down")
+ sys.exit()
-
-server.exit()
-sys.exit()
+if __name__ == '__main__': main()
Modified: trunk/server/callback.py
===================================================================
--- trunk/server/callback.py 2010-09-11 23:32:12 UTC (rev 401)
+++ trunk/server/callback.py 2010-09-12 01:01:32 UTC (rev 402)
@@ -23,19 +23,19 @@
def __init__(self):
self.clients = {}
def data_received(self, cid, data):
- print " --> " + cid + ": " + repr(data)
+ log('sendin', cid + ": " + repr(data))
def data_send(self, cid, data):
- print " <-- " + cid + ": " + repr(data)
+ log('sendout', cid + ": " + repr(data))
def debug_crash(self, traceback):
- print "\n*** Crash ***\n\n%s\n" % traceback
+ log('error', "\n*** Crash ***\n\n%s\n" % traceback)
def server_online(self, clients):
self.clients = clients
- print "*** SERVER ONLINE ***"
+ log('succeed', "*** SERVER ONLINE ***")
def enters_vp(self, cid):
- print " > %s: %s"%(cid, self.clients[cid]['con'].ip)
+ log('debug', " > %s: %s"%(cid, self.clients[cid]['con'].ip))
# Send locations and checksums of files to client app, so they can
# download what they need.
@@ -44,13 +44,13 @@
self.clients[cid]['con'].custom_send("landscapes", landscapes.list)
def leaves_vp(self, cid):
- print " < %s: %s"%(cid, self.clients[cid]['con'].ip)
+ log('debug', " < %s: %s"%(cid, self.clients[cid]['con'].ip))
def check_login(self, cid, usr, pwd):
db.execute("SELECT `username` FROM `users` WHERE \
`username`=%s AND \
`password`=%s", (usr, pwd))
- print "* Login %s %s" % (usr, pwd)
+ log('debug', "* Login %s %s" % (usr, pwd))
result = db.fetchone()
if result is None:
return False
@@ -71,6 +71,6 @@
(usr, pwd, extra['email'], extra['realname'],
self.clients[cid]['con'].ip))
- print "* Signup %s" % usr
+ log('debug', "* Signup %s" % usr)
return False # All ok, no errors
Modified: trunk/server/filetable.py
===================================================================
--- trunk/server/filetable.py 2010-09-11 23:32:12 UTC (rev 401)
+++ trunk/server/filetable.py 2010-09-12 01:01:32 UTC (rev 402)
@@ -21,8 +21,6 @@
self.db = db
def update_from_database(self):
- print "Retrieving file table from database..."
-
self.table = {}
self.db.execute("SELECT `filename`, `url`, `checksum` FROM `files`")
@@ -33,8 +31,6 @@
self.table[file['filename']] = {'url': fullurl,
'checksum': file['checksum']}
-
- print "Done, found %s entries in file table." % len(self.table)
return self.table
def add(self, filename, url, checksum):
Modified: trunk/server/functions.py
===================================================================
--- trunk/server/functions.py 2010-09-11 23:32:12 UTC (rev 401)
+++ trunk/server/functions.py 2010-09-12 01:01:32 UTC (rev 402)
@@ -26,9 +26,23 @@
except: sys.exit("ERROR: You need the configobj-module for this to work!")
def config_defaults(config):
+
+ ## TODO: This should (partly) be replaced by same system that client uses
+ ## (with the Validator, but keeping the interactive stuff)
+
+
+ if 'debug' not in config:
+ config['debug'] = {}
+
+ if not 'level' in config['debug']:
+ config['debug']['level'] = 2
+ if not 'use_colors' in config['debug']:
+ config['debug']['use_colors'] = True
+
+
if 'database' not in config:
config['database'] = {}
-
+
intro_text = """
Some settings are missing from the config. Because these settings are required,
We will now ask for them in this console. Please type in the correct value, and
@@ -57,18 +71,68 @@
config['database']['password'] = getpass("Database password: ")
+def log(t, *m):
+ def level(i):
+ return config['debug']['level'] >= i
+ use_colors = config['debug']['use_colors']
+ write = sys.stdout.write
+ def color(c):
+ write("\033[" + c + "m")
+
+ message = "\t".join([str(part) for part in m])
+
+ if t == "error" and level(1):
+ icon = "!!!"
+ icon_color = "1;31;7"
+ text_color = "1;91"
+
+ elif t == "warning" and level(2):
+ icon = "[!]"
+ icon_color = "1;33;7"
+ text_color = "93"
+
+ elif t == "succeed" and level(3):
+ icon = "OK "
+ icon_color = "1;32;7"
+ text_color = "32"
+
+ elif t == "debug" and level(4):
+ icon = " ~ "
+ icon_color = "1;7"
+ text_color = ""
+
+ elif t == "sendin" and level(5):
+ icon = "|<-"
+ icon_color = "1;100;2"
+ text_color = "2"
+
+ elif t == "sendout" and level(5):
+ icon = "|->"
+ icon_color = "1;100;2"
+ text_color = "2"
+
+ else:
+ return
+
+ if use_colors: color(icon_color)
+ write(" " + icon + " ")
+ if use_colors: color("0;" + text_color)
+ write("\t" + message)
+ if use_colors: color("0")
+ write("\n")
+
config = ConfigObj(os.path.join(sys.path[0], 'config'))
config_defaults(config)
config.write()
-print "Connecting to database..."
+log('debug', "Connecting to database...")
db = database.DB( config['database']['host'],
config['database']['database'],
config['database']['user'],
config['database']['password'])
-print "Connected to database `%s` on `%s`" % (config['database']['database'],
- config['database']['host'])
+log('succeed', "Connected to database `%s` on `%s`" %
+ (config['database']['database'], config['database']['host']))
file_table = FileTable(db)
landscapes = LandscapeManager(db)
Modified: trunk/server/landscapes.py
===================================================================
--- trunk/server/landscapes.py 2010-09-11 23:32:12 UTC (rev 401)
+++ trunk/server/landscapes.py 2010-09-12 01:01:32 UTC (rev 402)
@@ -21,14 +21,10 @@
self.db = db
def update_from_database(self):
- print "Retrieving landscapes from database..."
-
self.list = {}
self.db.execute("SELECT `type`, `direction`, `position`, `transition` \
FROM `landscapes` ORDER BY `id` ASC") # Order in DB = order in world
self.list = self.db.fetchall()
- print "Done, found %s landscapes." % len(self.list)
-
return self.list
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-11 23:32:21
|
Revision: 401
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=401&view=rev
Author: BlueWolf_
Date: 2010-09-11 23:32:12 +0000 (Sat, 11 Sep 2010)
Log Message:
-----------
Starting with the avatar-code. Code isn't much commented yet as the code will change a lot with every new change. Most is still temporary
Modified Paths:
--------------
trunk/client/playground.py
Added Paths:
-----------
trunk/client/playground_avatar.py
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-11 17:53:53 UTC (rev 400)
+++ trunk/client/playground.py 2010-09-11 23:32:12 UTC (rev 401)
@@ -17,6 +17,7 @@
from functions import *
import gui
+from playground_avatar import Avatar
class Playground():
@@ -39,7 +40,10 @@
# Playground stuff
self.backgrounds = {}
self.viewport = None
- self.direction_pressed = None
+ self.direction = None
+ self.avatars = {}
+ self.this_user = None
+ self.avatar_offset = None
def event(self, ev):
@@ -59,30 +63,49 @@
elif self.status == "playground":
- if ev.type == KEYDOWN:
- if ev.key == K_UP and self.direction_pressed != 0:
- self.direction_pressed = 0
- sh['timer'].start("playground-move", self.playground_move, \
- time.time(), self.viewport.top, 0)
- elif ev.key == K_DOWN and self.direction_pressed != 1:
- self.direction_pressed = 1
- sh['timer'].start("playground-move", self.playground_move, \
- time.time(), self.viewport.top, 1)
- elif ev.key == K_LEFT and self.direction_pressed != 2:
- self.direction_pressed = 2
- sh['timer'].start("playground-move", self.playground_move, \
- time.time(), self.viewport.left, 2)
- elif ev.key == K_RIGHT and self.direction_pressed != 3:
- self.direction_pressed = 3
- sh['timer'].start("playground-move", self.playground_move, \
- time.time(), self.viewport.left, 3)
-
- elif ev.type == KEYUP:
+ if ev.type == KEYDOWN or ev.type == KEYUP:
+
if ev.key in [K_UP, K_DOWN, K_LEFT, K_RIGHT]:
- self.direction_pressed = None
- sh['timer'].stop("playground-move")
-
+ keys = pygame.key.get_pressed()
+ keys = (keys[K_UP], keys[K_RIGHT], keys[K_DOWN],
+ keys[K_LEFT])
+
+ direction = None
+ # Multiple keys
+ if keys[0] and keys[1]:
+ direction = 1
+ elif keys[1] and keys[2]:
+ direction = 3
+ elif keys[2] and keys[3]:
+ direction = 5
+ elif keys[3] and keys[0]:
+ direction = 7
+
+ # Single keys
+ elif keys[0]:
+ direction = 0
+ elif keys[1]:
+ direction = 2
+ elif keys[2]:
+ direction = 4
+ elif keys[3]:
+ direction = 6
+
+ if direction == None and self.direction != None:
+ # Stop the timer. We are not walking
+ sh['timer'].stop("playground-walk")
+
+ elif self.direction == None or \
+ direction != self.direction[0]:
+ # We started walking or changed direction
+
+ self.direction = (direction, time.time(),
+ self.this_user['pos'][:])
+ sh['timer'].start("playground-walk",
+ self.playground_walk)
+
+
def call(self, name, data):
if name == "status": # A status update
if data['status'] == "login":
@@ -94,6 +117,11 @@
for name in self.backgrounds.keys():
sh['downloader'].remove_usage(name)
self.backgrounds = {}
+ self.viewport = None
+ self.direction = None
+ self.avatars = {}
+ self.this_user = None
+ self.avatar_offset = None
# Load the data for the login
self.loginbg = load_image(False, "images", "loginbg.png")
@@ -124,7 +152,30 @@
self.logingui = None
# Load the data for the playground
- self.viewport = Rect(0, 0, 1000, 700)
+
+ # Load all users
+ self.this_user = sh['client'].userlist[sh['client'].cid]
+ for user in sh['client'].userlist.values():
+ if user['pos'] != None:
+ self.avatars[user['cid']] = Avatar(user)
+
+ to_center = (
+ (self.surf.get_width()/2) - \
+ (self.avatars[self.this_user['cid']].size[0]/2),
+ (self.surf.get_height()/2) - \
+ (self.avatars[self.this_user['cid']].size[1]/2),
+ )
+ self.avatar_offset = (
+ self.this_user['pos'][0] - to_center[0],
+ self.this_user['pos'][1] - to_center[1],\
+ )
+
+ self.viewport = Rect(
+ self.avatar_offset[0],
+ self.avatar_offset[1],
+ 1000,
+ 700)
+
self.oldsurf = self.surf.copy()
self.transit = 1
self.playground_render(None, True)
@@ -232,7 +283,7 @@
rect = Rect(rect)
# Blit the background
- bg_offset = (self.viewport.left%250, self.viewport.top%250)
+ bg_offset = (-self.viewport.left%250, -self.viewport.top%250)
x_min = bg_offset[0]-250
if x_min == -250: x_min = 0
x_max = x_min + 250 * ((float(self.viewport.width) / 250)+1)
@@ -257,6 +308,25 @@
self.surf.blit(background, rect, bg_area)
+ # Blit the users
+ for avatar in self.avatars.values():
+ avatar_rect = Rect(
+ avatar.user['pos'][0] - self.viewport[0],
+ avatar.user['pos'][1] - self.viewport[1],
+ avatar.size[0],
+ avatar.size[1],
+ )
+
+ if not rect.colliderect(avatar_rect): continue
+
+ avatar_area = Rect(
+ rect.left - avatar_rect.left,
+ rect.top - avatar_rect.top,
+ rect.width,
+ rect.height)
+ avatar.blit(self.surf, avatar_area)
+
+
if self.transit != None: # An transition is happening
self.oldsurf.set_alpha(self.transit*255)
self.surf.blit(self.oldsurf, (0,0))
@@ -293,21 +363,37 @@
self.playground_render()
- def playground_move(self, name, startime, startpos, direction):
- # Temporary test function to walk
-
- timeline = time.time() - startime
+ def playground_walk(self, name):
+ direction, starttime, startpos = self.direction
+ timeline = time.time() - starttime
speed = 175
move = timeline*speed
if direction == 0:
- self.viewport.top = startpos - move
+ self.this_user['pos'][1] = startpos[1] - move
elif direction == 1:
- self.viewport.top = startpos + move
+ self.this_user['pos'][1] = startpos[1] - (move/1.7)
+ self.this_user['pos'][0] = startpos[0] + (move/1.7)
elif direction == 2:
- self.viewport.left = startpos - move
+ self.this_user['pos'][0] = startpos[0] + move
elif direction == 3:
- self.viewport.left = startpos + move
+ self.this_user['pos'][0] = startpos[0] + (move/1.7)
+ self.this_user['pos'][1] = startpos[1] + (move/1.7)
+ elif direction == 4:
+ self.this_user['pos'][1] = startpos[1] + move
+ elif direction == 5:
+ self.this_user['pos'][1] = startpos[1] + (move/1.7)
+ self.this_user['pos'][0] = startpos[0] - (move/1.7)
+ elif direction == 6:
+ self.this_user['pos'][0] = startpos[0] - move
+ elif direction == 7:
+ self.this_user['pos'][0] = startpos[0] - (move/1.7)
+ self.this_user['pos'][1] = startpos[1] - (move/1.7)
+
+ self.viewport.topleft = (
+ self.this_user['pos'][0]+self.avatar_offset[0],
+ self.this_user['pos'][1]+self.avatar_offset[1],
+ )
self.playground_render()
Added: trunk/client/playground_avatar.py
===================================================================
--- trunk/client/playground_avatar.py (rev 0)
+++ trunk/client/playground_avatar.py 2010-09-11 23:32:12 UTC (rev 401)
@@ -0,0 +1,34 @@
+## This file is part of Virtual Playground
+## Copyright (c) 2009 Jos Ratsma + Koen Koning
+
+## This program is free software; you can redistribute it and/or
+## modify it under the terms of the GNU General Public License
+## as published by the Free Software Foundation; either
+## version 2 of the License, or (at your option) any later version.
+
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+## GNU General Public License for more details.
+
+## You should have received a copy of the GNU General Public License
+## along with this program; if not, write to the Free Software
+## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+from functions import *
+
+class Avatar():
+ def __init__(self, user):
+ self.user = user
+ self.lastpos = user['pos']
+
+ self.avatar = None
+ self.size = (40,40)
+ sh['downloader'].get_file("happyblock.png", "img", self.download)
+
+ def download(self, filename, cache):
+ self.avatar = cache
+
+ def blit(self, surf, area):
+ if self.avatar:
+ surf.blit(self.avatar, (0,0), area)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-11 17:54:00
|
Revision: 400
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=400&view=rev
Author: BlueWolf_
Date: 2010-09-11 17:53:53 +0000 (Sat, 11 Sep 2010)
Log Message:
-----------
Added some level 3 (succeed) messages and fixed a bug in the layout which made it crash when 3 or more people where connected with the server
Modified Paths:
--------------
trunk/client/callback.py
trunk/client/layout.py
Modified: trunk/client/callback.py
===================================================================
--- trunk/client/callback.py 2010-09-10 19:20:43 UTC (rev 399)
+++ trunk/client/callback.py 2010-09-11 17:53:53 UTC (rev 400)
@@ -36,7 +36,7 @@
# We are connected
if reconnecting:
- log("succeed", "Connection ready!", "Core is logging in again")
+ log("succeed", "Connection ready! Core is logging in again")
sh['main'].call("status", {
"status": "login",
@@ -45,7 +45,7 @@
else:
# Do we need to log in automatically?
if sh['config']['user']['username'] != "":
- log("succeed", "Connection ready!", "App is logging in based "+\
+ log("succeed", "Connection ready! App is logging in based "+\
"on config-settings")
sh['main'].call("status", {
@@ -145,8 +145,25 @@
"action": "update"
})
+ def userlist(self, userlist):
+ if len(userlist) == 1:
+ log("succeed", "We are alone on this server")
+ else:
+ log("succeed", "There are " + str(len(userlist)) + " users on " + \
+ "this server, including myself")
+
def useronline(self, user, userlist):
+ log("succeed", user['user'] + " came online. There are now " + \
+ str(len(userlist)) + " users on this server")
+
sh['main'].call("useronline", user)
def useroffline(self, user, userlist):
+ if len(userlist) == 1:
+ amount = "We are alone this server now"
+ else:
+ amount = "There are now " + str(len(userlist)) + " users on " + \
+ "this server"
+ log("succeed", user['user'] + " went offline. " + amount)
+
sh['main'].call("useroffline", user)
Modified: trunk/client/layout.py
===================================================================
--- trunk/client/layout.py 2010-09-10 19:20:43 UTC (rev 399)
+++ trunk/client/layout.py 2010-09-11 17:53:53 UTC (rev 400)
@@ -179,7 +179,7 @@
elif len(sh['client'].userlist) == 2:
text_sub = "1 other person"
else:
- text_sub = len(sh['client'].userlist)-1 + " people"
+ text_sub = str(len(sh['client'].userlist)-1) + " people"
else:
text_sub = self.topbar_lastsub[1]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-10 19:20:49
|
Revision: 399
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=399&view=rev
Author: BlueWolf_
Date: 2010-09-10 19:20:43 +0000 (Fri, 10 Sep 2010)
Log Message:
-----------
Added a better way to log text to the console. Also added a config-option to change the amount of debugging. Fixed a rather stupid error in the core
Modified Paths:
--------------
trunk/client/VP.py
trunk/client/callback.py
trunk/client/configspec
trunk/client/core/parser.py
trunk/client/downloader.py
trunk/client/functions.py
Modified: trunk/client/VP.py
===================================================================
--- trunk/client/VP.py 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/VP.py 2010-09-10 19:20:43 UTC (rev 399)
@@ -81,7 +81,6 @@
sh['client'].connect(sh['config']['host']['host'], \
sh['config']['host']['port'])
-
# Wait for all the events to come
try:
while 1:
@@ -125,6 +124,8 @@
except: pass
sh['downloader'].stop()
sh['config'].write()
+
+ log("succeed", "System closed")
sys.exit()
@@ -157,7 +158,7 @@
pygame.display.update(rect)
def call(self, name, data):
- print " [>] \t", name, data
+ log("debug", "Call:", name + ' - ' + str(data))
sh['playground'].call(name, data)
sh['layout'].call(name, data)
Modified: trunk/client/callback.py
===================================================================
--- trunk/client/callback.py 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/callback.py 2010-09-10 19:20:43 UTC (rev 399)
@@ -23,15 +23,21 @@
class Callback(core.Callback):
def data_received(self, data):
- print " --> \t" + repr(data)
+ name = data.keys()[0]
+ value = data[name]
+ log("sendin", name + " - " + repr(data))
def data_send(self, data):
- print " <-- \t" + repr(data)
+ name = data.keys()[0]
+ value = data[name]
+ log("sendout", name + " - " + repr(data))
def connection_ready(self, public_rsa, reconnecting):
# We are connected
if reconnecting:
+ log("succeed", "Connection ready!", "Core is logging in again")
+
sh['main'].call("status", {
"status": "login",
"where": "logging in"
@@ -39,6 +45,9 @@
else:
# Do we need to log in automatically?
if sh['config']['user']['username'] != "":
+ log("succeed", "Connection ready!", "App is logging in based "+\
+ "on config-settings")
+
sh['main'].call("status", {
"status": "login",
"where": "logging in"
@@ -47,12 +56,16 @@
sh['config']['user']['password'])
else:
+ log("succeed", "Connection ready!")
+
sh['main'].call("status", {
"status": "login",
"where": "waiting"
})
def logged_in(self, username, cid, owner):
+ log("succeed", "We're logged in")
+
sh['main'].call("status", {
"status": "login",
"where": "downloading"
@@ -68,6 +81,8 @@
def failed_logging_in(self, reason):
# [TODO] Send the reason in some way
+ log("warning", "Failed logging in:", reason)
+
sh['main'].call("status", {
"status": "login",
"where": "waiting"
@@ -80,7 +95,10 @@
def disconnected(self, reason):
- print " !!! \tConnection closed: " + reason
+ if reason == "manual":
+ log("debug", "Connection closed:", reason)
+ else:
+ log("warning", "Connection closed:", reason)
sh['login_info'] = None
Modified: trunk/client/configspec
===================================================================
--- trunk/client/configspec 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/configspec 2010-09-10 19:20:43 UTC (rev 399)
@@ -9,3 +9,7 @@
[host]
host = string(default=vp.bluewolf.nl)
port = integer(default=6653)
+
+[debug]
+level = integer(min=1, max=5, default=2)
+use_colors = boolean(default=True)
Modified: trunk/client/core/parser.py
===================================================================
--- trunk/client/core/parser.py 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/core/parser.py 2010-09-10 19:20:43 UTC (rev 399)
@@ -56,8 +56,7 @@
self.sh['rsakey'] = msg['public']
- reconnect = (self.core.cid == None and self.sh['auto_login'])
-
+ reconnect = (self.core.cid == None and bool(self.sh['auto_login']))
self.call.connection_ready(msg['public'], reconnect)
if reconnect:
Modified: trunk/client/downloader.py
===================================================================
--- trunk/client/downloader.py 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/downloader.py 2010-09-10 19:20:43 UTC (rev 399)
@@ -40,7 +40,7 @@
def get_file(self, filename, filetype, callback, *arg):
- print " !!! \tDownload task:", filename
+ log("debug", "Download task:", filename)
# First check if we already have this file loaded
if filename in self.loaded_files:
@@ -68,7 +68,7 @@
self.queue.put((1, filename))
else:
- print "File '" + filename + "' is not in the repository!"
+ log("warning", "File '" + filename + "' is not in the repository!")
callback(filename, self.error(filetype, "not in repos"), *arg)
@@ -124,7 +124,7 @@
filename)
if not filename in sh['filetable']:
- print "File '" + filename + "' is not in the repository!"
+ log("warning", "File '"+filename+"' is not in the repository!")
self.callbacks(filename, task['callbacks'], \
self.error(task['filetype'], "not in repos"))
return
@@ -158,7 +158,7 @@
try: f = urllib2.urlopen(request)
except urllib2.URLError, e:
- print "Url '" + url + "' could not be found!"
+ log("warning", "Url '" + url + "' could not be found!")
self.callbacks(filename, task['callbacks'], \
self.error(filename, "not found"))
return
@@ -180,8 +180,8 @@
filename + ".tmp")
if checksum != filehash:
- print "Checksum mismatch for '" + filename + "! " + \
- filehash + " > " + checksum
+ log("warning" "Checksum mismatch for '" + filename + "!", \
+ filehash + " > " + checksum)
self.callbacks(filename, task['callbacks'], \
self.error(task['filetype'], "checksum"))
Modified: trunk/client/functions.py
===================================================================
--- trunk/client/functions.py 2010-09-09 19:34:56 UTC (rev 398)
+++ trunk/client/functions.py 2010-09-10 19:20:43 UTC (rev 399)
@@ -48,7 +48,7 @@
else:
image = image.convert_alpha()
except pygame.error, message:
- print 'Cannot load image:', fullname
+ log("error", 'Cannot load image:', fullname)
raise SystemExit, message
return image
@@ -70,8 +70,8 @@
sh['config'] = configobj.ConfigObj(real_path("config.conf"), \
configspec = real_path("configspec"))
except configobj.ParseError:
- print "Config: The config-file is malformed. Please check the file " + \
- "or remove it to create a new default one"
+ log("error", "Config:", "The config-file is malformed. Please check " +\
+ "the file or remove it to create a new default one")
sys.exit()
validator = Validator()
@@ -81,9 +81,60 @@
for (section_list, key, _) in configobj.flatten_errors(sh['config'], \
result):
if key is not None:
- print "Config: Something is wrong with the " + \
- "'%s/%s' key. Please check" % (section_list[0], key)
+ log("error", "Config:", "Something is wrong with the " + \
+ "'%s/%s' key. Please check" % (section_list[0], key))
else:
- print "Config: The '%s' section is missing" % section_list[0]
+ log("error", "Config:", \
+ "The '%s' section is missing" % section_list[0])
sys.exit()
+
+def log(t, *m):
+ def level(i):
+ return sh['config']['debug']['level'] >= i
+ use_colors = sh['config']['debug']['use_colors']
+ write = sys.stdout.write
+ def color(c):
+ write("\033[" + c + "m")
+
+ message = "\t".join([str(part) for part in m])
+
+ if t == "error" and level(1):
+ icon = "!!!"
+ icon_color = "1;31;7"
+ text_color = "1;91"
+
+ elif t == "warning" and level(2):
+ icon = "[!]"
+ icon_color = "1;33;7"
+ text_color = "93"
+
+ elif t == "succeed" and level(3):
+ icon = "OK "
+ icon_color = "1;32;7"
+ text_color = "32"
+
+ elif t == "debug" and level(4):
+ icon = " ~ "
+ icon_color = "1;7"
+ text_color = ""
+
+ elif t == "sendin" and level(5):
+ icon = "|<-"
+ icon_color = "1;100;2"
+ text_color = "2"
+
+ elif t == "sendout" and level(5):
+ icon = "|->"
+ icon_color = "1;100;2"
+ text_color = "2"
+
+ else:
+ return
+
+ if use_colors: color(icon_color)
+ write(" " + icon + " ")
+ if use_colors: color("0;" + text_color)
+ write("\t" + message)
+ if use_colors: color("0")
+ write("\n")
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-09 19:35:03
|
Revision: 398
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=398&view=rev
Author: BlueWolf_
Date: 2010-09-09 19:34:56 +0000 (Thu, 09 Sep 2010)
Log Message:
-----------
* Added a userlist, useronline and useroffline callback into the core
* The 'Who is online' subtext in topbar from the layout is now dynamic and gets updated as soon as someone goes online or offline
Modified Paths:
--------------
trunk/client/callback.py
trunk/client/core/callback.py
trunk/client/core/client.py
trunk/client/core/parser.py
trunk/client/layout.py
Modified: trunk/client/callback.py
===================================================================
--- trunk/client/callback.py 2010-09-09 15:26:04 UTC (rev 397)
+++ trunk/client/callback.py 2010-09-09 19:34:56 UTC (rev 398)
@@ -126,3 +126,9 @@
sh['main'].call("filetable", {
"action": "update"
})
+
+ def useronline(self, user, userlist):
+ sh['main'].call("useronline", user)
+
+ def useroffline(self, user, userlist):
+ sh['main'].call("useroffline", user)
Modified: trunk/client/core/callback.py
===================================================================
--- trunk/client/core/callback.py 2010-09-09 15:26:04 UTC (rev 397)
+++ trunk/client/core/callback.py 2010-09-09 19:34:56 UTC (rev 398)
@@ -157,3 +157,54 @@
"""
pass
+
+ def userlist(self, userlist):
+ """
+ Just after the user is logged in the current list of users will be send.
+ This variable is the same as client.userlist. This callback can be used
+ to append the app's own data to the clients.
+
+ userlist:
+ A dict with the current list of users. The cid is the key and the
+ value is the data for this user. The data consist of a dict with:
+ * cid - The unique ID for this user
+ * user - The username
+ * app - [Appname, Appversion]
+ * version - Which core it's using (string)
+ * bot - If it's a bot
+ * owner - The owner for this bot (only available when bot = True)
+ * pos - [Z, X, Y] The position for this user. Is None
+ when you can't see this user.
+ * ? - And any other extra data the server's app has defined
+ for its users
+ """
+
+ pass
+
+ def useronline(self, user, userlist):
+ """
+ When an other users comes online, this event will be fired.
+
+ user:
+ Same as the dict in callback.userlist
+ userlist:
+ Dictionary with all current online users. This is the same as
+ client.userlist
+ """
+
+ pass
+
+ def useroffline(self, user, userlist):
+ """
+ When an other user goes offline, this event will be fired. This happens
+ AFTER the user is removed from client.userlist.
+
+ user:
+ Same as the dict in callback.userlist
+ userlist:
+ Dictionary with all current online users. The user that did go
+ offline is already removed from this list. This is the same as
+ client.userlist
+ """
+
+ pass
Modified: trunk/client/core/client.py
===================================================================
--- trunk/client/core/client.py 2010-09-09 15:26:04 UTC (rev 397)
+++ trunk/client/core/client.py 2010-09-09 19:34:56 UTC (rev 398)
@@ -86,6 +86,7 @@
self.username = None
self.owner = None
self.cid = None # Connection-id
+ self.userlist = {}
# Class that parsers all incomming data
self.__parse = Parser(self.__sh)
@@ -330,6 +331,7 @@
self.username = None
self.owner = None
self.cid = None
+ self.userlist = {}
try: self.__sock.shutdown(0)
except: pass
Modified: trunk/client/core/parser.py
===================================================================
--- trunk/client/core/parser.py 2010-09-09 15:26:04 UTC (rev 397)
+++ trunk/client/core/parser.py 2010-09-09 19:34:56 UTC (rev 398)
@@ -99,39 +99,37 @@
* owner - The owner for this bot (only available when bot = True)
* pos - [Z, X, Y] The position for this user. Is None
when you can't see this user.
+ * ? - And any other extra data the server's app has defined for
+ its users
"""
- # TODO
+ for user in msg:
+ self.core.userlist[user['cid']] = user
- pass
+ self.call.userlist(self.core.userlist)
+
def useronline(self, msg):
"""
Called after an user (or bot) has signed on.
- * cid - The unique ID for this connection
- * user - The username
- * app - [Appname, Appversion]
- * version - Which core it's using (string)
- * bot - If it's a bot
- * owner - The owner for this bot (only available when
- bot = True)
- * pos - [Z, X, Y] The position for this user. Is None
- when you can't see this user.
+ Data is the same as the dict in callback.userlist
"""
- # TODO
-
- pass
+ self.core.userlist[msg['cid']] = msg
+ self.call.useronline(msg, self.core.userlist)
+
def useroffline(self, msg):
"""
An user has gone offline
* cid - The connection-id for this client
"""
- # TODO
+ if not self.core.userlist.has_key(msg['cid']): return
- pass
+ user = self.core.userlist[msg['cid']]
+ del self.core.userlist[msg['cid']]
+ self.call.useroffline(user, self.core.userlist)
def error(self, msg):
Modified: trunk/client/layout.py
===================================================================
--- trunk/client/layout.py 2010-09-09 15:26:04 UTC (rev 397)
+++ trunk/client/layout.py 2010-09-09 19:34:56 UTC (rev 398)
@@ -41,6 +41,9 @@
self.toppos = None
self.topbar_mainfont = None
self.topbar_subfont = None
+ self.topbar_lastsub = [""]*3 # Used for caching, when the connection's
+ # already closed but the animation is still
+ # going
def event(self, ev):
if self.status == "playground":
@@ -111,8 +114,14 @@
time.time(), 1)
self.status = data['status']
+
+
+ elif name == "useronline" or name == "useroffline":
+ self.updatetop()
+
+ # [TODO] Show notification
+
-
def updatetop(self, wholebar = False):
if wholebar:
# This happens when the WHOLE bar needs to be updated
@@ -152,12 +161,28 @@
textcolor_subshadow = (0, 0, 0)
if i == 0:
text_main = "General"
- text_sub = sh['client'].username + ": 0 V"
+
+ # Sub text
+ if sh['client'].username:
+ text_sub = sh['client'].username + ": 0 V"
+ else:
+ text_sub = self.topbar_lastsub[0]
textpos_sub += 30
elif i == 1:
text_main = "Who is online"
- text_sub = "Only you"
+
+ # Sub text
+ if sh['client'].username:
+ if len(sh['client'].userlist) == 1:
+ text_sub = "Only you"
+ elif len(sh['client'].userlist) == 2:
+ text_sub = "1 other person"
+ else:
+ text_sub = len(sh['client'].userlist)-1 + " people"
+ else:
+ text_sub = self.topbar_lastsub[1]
+
textpos_sub += 32
elif i == 2:
@@ -165,6 +190,7 @@
text_sub = "0 items"
textpos_sub += 30
+ self.topbar_lastsub[i] = text_sub
# Blit image
rect2.move_ip(0, -self.toppos)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-09 15:26:11
|
Revision: 397
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=397&view=rev
Author: BlueWolf_
Date: 2010-09-09 15:26:04 +0000 (Thu, 09 Sep 2010)
Log Message:
-----------
The topbar has now text, although it's still static yet (except for the name of course)
Modified Paths:
--------------
trunk/client/layout.py
Modified: trunk/client/layout.py
===================================================================
--- trunk/client/layout.py 2010-09-08 19:10:55 UTC (rev 396)
+++ trunk/client/layout.py 2010-09-09 15:26:04 UTC (rev 397)
@@ -39,6 +39,8 @@
# Playground stuff
self.topbar = None
self.toppos = None
+ self.topbar_mainfont = None
+ self.topbar_subfont = None
def event(self, ev):
if self.status == "playground":
@@ -98,7 +100,12 @@
self.hover = None
self.toppos = 0
+ self.topbar_mainfont = pygame.font.Font(real_path(\
+ "fonts", "DejaVuSans-Bold.ttf"), 19)
+ self.topbar_subfont = pygame.font.Font(real_path(\
+ "fonts", "DejaVuSans-Bold.ttf"), 10)
+
# Slide the topbar in
sh['timer'].start("layout-topslide", self.timer, \
time.time(), 1)
@@ -108,10 +115,14 @@
def updatetop(self, wholebar = False):
if wholebar:
+ # This happens when the WHOLE bar needs to be updated
+ # For example: When the startup-animation is happening
self.surf.fill([0,0,0,0])
self.surf.blit(self.topbar, (0,self.toppos), (0,0,1000,TOPHEIGHT))
-
+
+ # Walkthrough every button
for i in range(TOPBUTTONS):
+ # Calculating and setting all variables
left = TOPLEFT + (TOPBUTTONWIDTH*i)
rect = Rect(left, self.toppos, TOPBUTTONWIDTH, TOPHEIGHT)
@@ -119,18 +130,75 @@
if self.selected is i: # This button is selected
rect2 = rect.move(0,TOPHEIGHT*2)
+ textcolor_main = (159, 159, 159)
+ textcolor_sub = (116, 116, 116)
+ textpos_main = 6
+ textpos_sub = 1
elif self.hover is i: # This button is hovered
rect2 = rect.move(0,TOPHEIGHT)
-
+ textcolor_main = (132, 125, 114)
+ textcolor_sub = (116, 108, 96)
+ textpos_main = 5
+ textpos_sub = 0
else:
rect2 = rect.move(0,0)
+ textcolor_main = (119, 119, 119)
+ textcolor_sub = (90, 90, 90)
+ textpos_main = 5
+ textpos_sub = 0
+
+ textcolor_mainshadow = (0, 0, 0)
+ textcolor_subshadow = (0, 0, 0)
+ if i == 0:
+ text_main = "General"
+ text_sub = sh['client'].username + ": 0 V"
+ textpos_sub += 30
+
+ elif i == 1:
+ text_main = "Who is online"
+ text_sub = "Only you"
+ textpos_sub += 32
+ elif i == 2:
+ text_main = "Items"
+ text_sub = "0 items"
+ textpos_sub += 30
+
+
+ # Blit image
rect2.move_ip(0, -self.toppos)
self.surf.blit(self.topbar, rect, rect2)
+
+
+ # Blit text
+ # Main-shadow
+ text = self.topbar_mainfont.render(text_main, True, \
+ textcolor_mainshadow)
+ textpos = [(302/2)-(text.get_width()/2), textpos_main]
+ textpos[0] += rect.left
+ textpos[1] += rect.top
+ self.surf.blit(text, (textpos[0], textpos[1]-1))
+ # Main
+ text = self.topbar_mainfont.render(text_main, True, textcolor_main)
+ self.surf.blit(text, textpos)
+
+ # Sub-shadow
+ text = self.topbar_subfont.render(text_sub, True, \
+ textcolor_subshadow)
+ textpos = [(302/2)-(text.get_width()/2), textpos_sub]
+ textpos[0] += rect.left
+ textpos[1] += rect.top
+ self.surf.blit(text, (textpos[0], textpos[1]-1))
+ # Sub
+ text = self.topbar_subfont.render(text_sub, True, textcolor_sub)
+ self.surf.blit(text, textpos)
+
+
sh['update']((0,0, 1000, 65))
+
def topbarcursor(self, pos):
if pos[0] > TOPLEFT and pos[0] < (TOPBUTTONWIDTH*TOPBUTTONS+TOPLEFT) \
and pos[1] < 55:
@@ -149,6 +217,8 @@
if direction == 0 : # Up
# Clear the bar
self.topbar = None
+ self.topbar_mainfont = None
+ self.topbar_subfont = None
self.surf.fill([0,0,0,0])
sh['update']((0,0, 1000, 65))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-08 19:11:02
|
Revision: 396
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=396&view=rev
Author: BlueWolf_
Date: 2010-09-08 19:10:55 +0000 (Wed, 08 Sep 2010)
Log Message:
-----------
GUI-objects can now distinguish which mousebutton is pressed. Also fixed a rather annoying bug in the window which happended when pressing a mousebutton while moving the window
Modified Paths:
--------------
trunk/client/gui.py
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-08 15:50:22 UTC (rev 395)
+++ trunk/client/gui.py 2010-09-08 19:10:55 UTC (rev 396)
@@ -181,7 +181,7 @@
# the interface
pos = (ev.pos[0] - self.mousedown[0][0], \
ev.pos[1] - self.mousedown[0][1])
- self.mousedown[1].click(1, pos)
+ self.mousedown[1].click(1, pos, ev.buttons)
return True
else:
# Check which object we hover
@@ -195,24 +195,25 @@
rect, hover = self.this_pos(ev.pos, bringontop = True)
if hover:
pos = (ev.pos[0] - rect[0], ev.pos[1] - rect[1])
- hover.click(0, pos)
+ hover.click(0, pos, ev.button)
- self.mousedown = (rect, hover)
+ if ev.button == 1:
+ self.mousedown = (rect, hover)
- if self.focus != hover:
- # Change the focus
- if self.focus:
- self.focus.focus = False
- self.focus.lost_focus()
- self.focus = None
+ if self.focus != hover:
+ # Change the focus
+ if self.focus:
+ self.focus.focus = False
+ self.focus.lost_focus()
+ self.focus = None
+
+ self.focus = hover
- self.focus = hover
+ # Tell this object
+ hover.focus = True
+ hover.got_focus()
+ self.feedback.mousedown(hover)
- # Tell this object
- hover.focus = True
- hover.got_focus()
- self.feedback.mousedown(hover)
-
return True
else:
@@ -229,9 +230,11 @@
obj = self.mousedown[1]
obj.frozen = True
- obj.click(2, pos)
- self.mousedown = None
+ obj.click(2, pos, ev.button)
+ if not 1 in pygame.mouse.get_pressed():
+ self.mousedown = None
+
obj.unfreeze()
return True
@@ -315,9 +318,31 @@
pass
def hovering(self, state=None, pos=None):
+ """
+ Executed when a object gets hovered.
+ State = True - Mouse enters the object
+ State = False - Mouse leaves the object
+ State = None - When state doesn't change. When the mouse is already
+ hovering about the object
+
+ pos will only be a tuple when state is either True or None
+ """
+
pass
- def click(self, state, pos):
+ def click(self, state, pos, button):
+ """
+ When a object gets clicked
+ State = 0 - Mousebutton got clicked
+ State = 1 - Mousebutton is clicked, mouse got moved
+ State = 2 - Mousebutton is released
+
+ pos = Position of the mouse, compared to the object
+
+ button = Which button is pressed.
+ Please not that with state = 2 'button' is a tuple with all the
+ pressed buttons!
+ """
pass
def got_focus(self):
@@ -573,8 +598,8 @@
self.surf.blit(self.gui, rect, img)
- def click(self, state, pos):
- if state == 0:
+ def click(self, state, pos, button):
+ if state == 0 and button == 1:
if self.canclose:
border = Rect(9, 9, self.rect.width-51, 28)
close = self.calculate_pos(self.pos['close_pos'])
@@ -589,22 +614,21 @@
self.closedown = True
self.update(close)
- elif state == 1:
- if self.mousepos != None:
- movepos = [pos[0]-self.mousepos[0], pos[1]-self.mousepos[1]]
- self.move(movepos)
+ elif state == 1 and self.mousepos != None:
+ movepos = [pos[0]-self.mousepos[0], pos[1]-self.mousepos[1]]
+ self.move(movepos)
- if self.closedown:
- close = self.calculate_pos(self.pos['close_pos'])
- inside = close.collidepoint(pos)
- if self.closedown_visible and not inside:
- self.closedown_visible = False
- self.update(close)
- elif self.closedown_visible == False and inside:
- self.closedown_visible = True
- self.update(close)
+ elif state == 1 and self.closedown:
+ close = self.calculate_pos(self.pos['close_pos'])
+ inside = close.collidepoint(pos)
+ if self.closedown_visible and not inside:
+ self.closedown_visible = False
+ self.update(close)
+ elif self.closedown_visible == False and inside:
+ self.closedown_visible = True
+ self.update(close)
- elif state == 2:
+ elif state == 2 and button == 1:
self.mousepos = None
if self.closedown:
@@ -765,8 +789,8 @@
if self.focus:
pygame.draw.line(self.surf, [118, 58, 19], (pos+cursorpos+6, 10), (pos+cursorpos+6, 26), 2)
- def click(self, state, pos):
- if state == 0:
+ def click(self, state, pos, button):
+ if state == 0 and button == 1:
# Calculate position based on the clicked position
inp = self.input
@@ -921,20 +945,20 @@
if state != None:
self.update()
- def click(self, state, pos):
- if state == 0:
+ def click(self, state, pos, button):
+ if state == 0 and button == 1:
self.clicked = True
self.clicked_visible = True
self.update()
- elif state == 1:
+ elif state == 1 and self.clicked:
hover = bool(Rect(0, 0, self.rect.width, self.rect.height)
.collidepoint(pos))
if hover != self.clicked_visible:
self.clicked_visible = hover
self.update()
- elif state == 2:
+ elif state == 2 and button == 1:
waspressed = self.clicked_visible
self.clicked = False
@@ -1059,19 +1083,19 @@
if state != None:
self.update()
- def click(self, state, pos):
- if state == 0:
+ def click(self, state, pos, button):
+ if state == 0 and button == 1:
self.clicked = True
self.clicked_visible = True
self.update()
- elif state == 1:
+ elif state == 1 and self.clicked:
hover = bool(Rect(0, 0, self.rect.width, self.rect.height).collidepoint(pos))
if hover != self.clicked_visible:
self.clicked_visible = hover
self.update()
- elif state == 2:
+ elif state == 2 and button == 1:
wasclicked = self.clicked_visible
self.clicked = False
self.clicked_visible = False
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-08 15:50:33
|
Revision: 395
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=395&view=rev
Author: BlueWolf_
Date: 2010-09-08 15:50:22 +0000 (Wed, 08 Sep 2010)
Log Message:
-----------
Moved and changed the size of the signup-window. Fixed some variables in gui.Button and gui.Link regarding appearance when clicked. When clicked, it didn't rendered its new state properly
Modified Paths:
--------------
trunk/client/gui.py
trunk/client/playground.py
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-07 20:38:29 UTC (rev 394)
+++ trunk/client/gui.py 2010-09-08 15:50:22 UTC (rev 395)
@@ -851,8 +851,8 @@
self.backgroundsurf = pygame.Surface((self.rect.width, \
self.rect.height*3), SRCALPHA).convert_alpha()
self.style = None
- self.mousedown = False
- self.ispressed = False
+ self.clicked = False
+ self.clicked_visible = False
self.caption = ""
@@ -893,9 +893,9 @@
if self.style == "login":
# Which state do we need?
- if self.ispressed:
+ if self.clicked_visible:
top = 68
- elif self.hover:# and not self.mousedown:
+ elif self.hover or self.clicked:
top = 34
else:
top = 0
@@ -923,31 +923,34 @@
def click(self, state, pos):
if state == 0:
- self.mousedown = True
- self.ispressed = True
+ self.clicked = True
+ self.clicked_visible = True
self.update()
elif state == 1:
- hover = bool(Rect(0, 0, self.rect.width, self.rect.height).collidepoint(pos))
- if hover != self.ispressed:
- self.ispressed = hover
+ hover = bool(Rect(0, 0, self.rect.width, self.rect.height)
+ .collidepoint(pos))
+ if hover != self.clicked_visible:
+ self.clicked_visible = hover
self.update()
elif state == 2:
- self.mousedown = False
+ waspressed = self.clicked_visible
+ self.clicked = False
+ self.clicked_visible = False
+
self.update()
- if self.ispressed:
+ if waspressed:
self.submit()
-
- self.ispressed = False
def submit(self):
self.feedback.submit(self)
def manualpush(self, state):
- self.ispressed = state
+ self.clicked = state
+ self.clicked_visible = state
self.update()
@@ -1000,8 +1003,8 @@
def __defaults__(self):
self.cangetfocus = False
self.font = None
- self.mousedown = False
- self.ispressed = False
+ self.clicked = False
+ self.clicked_visible = False
self.caption = ""
self.color = [0, 0, 0]
@@ -1038,10 +1041,10 @@
pos = self.rect.width - textwidth
# Which state do we need?
- if self.ispressed:
+ if self.clicked_visible:
color = self.color_click
self.font.set_underline(True)
- elif self.hover and not self.mousedown:
+ elif self.hover or self.clicked:
color = self.color_hover
self.font.set_underline(True)
else:
@@ -1058,25 +1061,25 @@
def click(self, state, pos):
if state == 0:
- self.mousedown = True
- self.ispressed = True
+ self.clicked = True
+ self.clicked_visible = True
self.update()
elif state == 1:
hover = bool(Rect(0, 0, self.rect.width, self.rect.height).collidepoint(pos))
- if hover != self.ispressed:
- self.ispressed = hover
+ if hover != self.clicked_visible:
+ self.clicked_visible = hover
self.update()
elif state == 2:
- self.mousedown = False
+ wasclicked = self.clicked_visible
+ self.clicked = False
+ self.clicked_visible = False
self.update()
- if self.ispressed:
+ if wasclicked:
self.submit()
-
- self.ispressed = False
def submit(self):
self.feedback.submit(self)
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-07 20:38:29 UTC (rev 394)
+++ trunk/client/playground.py 2010-09-08 15:50:22 UTC (rev 395)
@@ -354,8 +354,10 @@
# Create signup window
window = self.parent.logingui.add(gui.Window, "signup", \
- Rect(50, 50, 200, 200), SignupFeedback())
+ Rect(300, 140, 400, 420), SignupFeedback())
window.caption = "Signup"
+
+ #window.add(gui.
window.unfreeze()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-07 20:38:36
|
Revision: 394
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=394&view=rev
Author: BlueWolf_
Date: 2010-09-07 20:38:29 +0000 (Tue, 07 Sep 2010)
Log Message:
-----------
Added mouse_focus and key_focus back to the sh again, as a certian pygame-bug came back again (Not always giving the right variable, depending on OS/Window Manager)
Modified Paths:
--------------
trunk/client/VP.py
trunk/client/gui.py
Modified: trunk/client/VP.py
===================================================================
--- trunk/client/VP.py 2010-09-06 19:37:54 UTC (rev 393)
+++ trunk/client/VP.py 2010-09-07 20:38:29 UTC (rev 394)
@@ -37,6 +37,9 @@
sh['timer'] = Timer()
sh['downloader'] = Downloader()
sh['login_info'] = None
+
+ sh['key_focus'] = True
+ sh['mouse_focus'] = True
# Fire up pygame
os.environ['SDL_VIDEO_CENTERED']='1'
@@ -86,7 +89,7 @@
if ev.type == QUIT: break
- if ev.type == MOUSEMOTION:
+ elif ev.type == MOUSEMOTION:
# Prevent this event from overflowing the queue. Always
# return the position right now and remove al other
# mousemotions in the queue
@@ -96,7 +99,18 @@
ev = pygame.event.Event(MOUSEMOTION,
buttons = ev.buttons,
pos = pos)
+
+ sh['mouse_focus'] = True
+ elif ev.type == KEYDOWN:
+ sh['key_focus'] = True
+
+ elif ev.type == ACTIVEEVENT:
+ if ev.state == 1: # Mouse
+ sh['mouse_focus'] = bool(ev.gain)
+ elif ev.state == 2: # Key
+ sh['key_focus'] = bool(ev.gain)
+
# Send through all the layers
if sh['windows'].event(ev): continue
if sh['layout'].event(ev): continue
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-06 19:37:54 UTC (rev 393)
+++ trunk/client/gui.py 2010-09-07 20:38:29 UTC (rev 394)
@@ -116,7 +116,7 @@
if pos == None: pos = pygame.mouse.get_pos()
- if pygame.mouse.get_focused():
+ if sh['mouse_focus']:
# Get the current hovered object
rect, hover = self.this_pos(pos)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-06 19:38:03
|
Revision: 393
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=393&view=rev
Author: BlueWolf_
Date: 2010-09-06 19:37:54 +0000 (Mon, 06 Sep 2010)
Log Message:
-----------
A GUI-window can now be closed, among other small fixes
Modified Paths:
--------------
trunk/client/gui.py
trunk/client/playground.py
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-06 16:00:32 UTC (rev 392)
+++ trunk/client/gui.py 2010-09-06 19:37:54 UTC (rev 393)
@@ -58,6 +58,11 @@
raise KeyError(key)
+ def has(self, key):
+ for child in self.children:
+ if child.name == key: return True
+ return False
+
def add(self, Obj, name, rect, feedback = None):
"""
Append a child to this object
@@ -114,21 +119,25 @@
if pygame.mouse.get_focused():
# Get the current hovered object
rect, hover = self.this_pos(pos)
-
+
# Is it different from the previous check?
if hover != self.hover:
# De-hover the previous one
if self.hover:
self.hover.hover = False
- self.hover.hovering(False)
+ self.hover.hovering(state=False)
self.hover = hover
# Hover the current one
if self.hover:
self.hover.hover = True
- self.hover.hovering(True)
+ pos = (pos[0] - rect[0], pos[1] - rect[1])
+ self.hover.hovering(state=True, pos=pos)
+ elif hover != None:
+ pos = (pos[0] - rect[0], pos[1] - rect[1])
+ self.hover.hovering(pos=pos)
if hover: return True # Disable events further down the interface
@@ -136,7 +145,7 @@
# Remove the previous hover
if self.hover:
self.hover.hover = False
- self.hover.hovering(False)
+ self.hover.hovering(state=False)
self.hover = None
def give_focus(self, *obj):
@@ -296,11 +305,16 @@
def __defaults__(self):
pass
-
+
+ def has(self, key):
+ for child in self.children:
+ if child.name == key: return True
+ return False
+
def render(self):
pass
- def hovering(self, value):
+ def hovering(self, state=None, pos=None):
pass
def click(self, state, pos):
@@ -411,6 +425,11 @@
if pos == len(self.children): pos = 0
self.give_focus(self.children[pos])
+
+ def remove(self):
+ # Remove this object
+ self.parent.children.remove(self)
+ self.update()
@@ -428,7 +447,10 @@
self.backgroundsurf = self.surf.copy()
self.font = pygame.font.Font(real_path("fonts", \
"DejaVuSans-Bold.ttf"), 14)
- self.buttonstate = 0 # 0 = Nothing, 1 = Hover, 2 = Click
+ self.closehover = False # If the mouse is hovering above the X
+ self.closedown = False # If the mouse is clicking the X
+ self.closedown_visible = False # If the button should be seen as pressed
+
self.mousepos = None # Mouse position when clicking the title
self.pos = {
@@ -541,12 +563,12 @@
# Create button
if self.canclose:
- if self.buttonstate == 0:
+ if self.closedown_visible:
+ img = self.pos['closeC_img']
+ elif self.closehover or self.closedown:
+ img = self.pos['closeH_img']
+ else:
img = self.pos['close_img']
- elif self.buttonstate == 1:
- img = self.pos['closeH_img']
- elif self.buttonstate == 2:
- img = self.pos['closeC_img']
rect = self.calculate_pos(self.pos['close_pos'])
self.surf.blit(self.gui, rect, img)
@@ -555,20 +577,66 @@
if state == 0:
if self.canclose:
border = Rect(9, 9, self.rect.width-51, 28)
+ close = self.calculate_pos(self.pos['close_pos'])
else:
border = Rect(9, 9, self.rect.width-18, 28)
- if border.collidepoint(pos):
+ if border.collidepoint(pos): # Move the window
# Get the REAL pos, not the one relative to self.rect
self.mousepos = (pos[0]-self.rect[0], pos[1]-self.rect[1])
+
+ elif self.canclose and close.collidepoint(pos): # Close window
+ self.closedown_visible = True
+ self.closedown = True
+ self.update(close)
elif state == 1:
if self.mousepos != None:
movepos = [pos[0]-self.mousepos[0], pos[1]-self.mousepos[1]]
self.move(movepos)
+
+ if self.closedown:
+ close = self.calculate_pos(self.pos['close_pos'])
+ inside = close.collidepoint(pos)
+ if self.closedown_visible and not inside:
+ self.closedown_visible = False
+ self.update(close)
+ elif self.closedown_visible == False and inside:
+ self.closedown_visible = True
+ self.update(close)
elif state == 2:
self.mousepos = None
+
+ if self.closedown:
+ close = self.calculate_pos(self.pos['close_pos'])
+ if self.closedown_visible:
+ self.remove()
+ return
+
+ self.closedown_visible = False
+ self.closedown = False
+ self.update(close)
+
+
+ def hovering(self, state=None, pos=None):
+ if state == False and self.closehover:
+ close = self.calculate_pos(self.pos['close_pos'])
+ self.closehover = 0
+ self.update(close)
+ elif pos != None:
+ close = self.calculate_pos(self.pos['close_pos'])
+ inside = close.collidepoint(pos)
+ if self.closehover == False and inside:
+ self.closehover = True
+ self.update(close)
+ elif self.closehover and not inside:
+ self.closehover = False
+ self.update(close)
+
+
+
+
def move(self, newpos):
# Move the current window
oldrect = self.rect.move(0,0) # Where is .copy?
@@ -849,8 +917,9 @@
self.surf.blit(font, pos)
- def hovering(self, value):
- self.update()
+ def hovering(self, state=None, pos=None):
+ if state != None:
+ self.update()
def click(self, state, pos):
if state == 0:
@@ -983,8 +1052,9 @@
self.surf.blit(font, (pos, 0))
- def hovering(self, state):
- self.update()
+ def hovering(self, state=None, pos=None):
+ if state != None:
+ self.update()
def click(self, state, pos):
if state == 0:
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-06 16:00:32 UTC (rev 392)
+++ trunk/client/playground.py 2010-09-06 19:37:54 UTC (rev 393)
@@ -170,7 +170,7 @@
usrlabel.color = [177, 93, 39]
usrlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
- usr = self.logingui.add(gui.Textbox, "usr", (345, 285, 310, 37))
+ usr = self.logingui.add(gui.Textbox, "usrtextbox", (345, 285, 310, 37))
usr.set_style("login")
pwdlabel = self.logingui.add(gui.Label, "pwdlabel", \
@@ -180,15 +180,15 @@
pwdlabel.color = [177, 93, 39]
pwdlabel.set_font(("fonts", "DejaVuSans-Bold.ttf"), 15)
- pwd = self.logingui.add(gui.Textbox, "pwd", (345, 350, 310, 37))
+ pwd = self.logingui.add(gui.Textbox, "pwdtextbox", (345, 350, 310, 37))
pwd.set_style("login")
pwd.set_type("password")
- login = self.logingui.add(gui.Button, "login", (425, 398, 151, 34))
+ login = self.logingui.add(gui.Button, "loginbutton", (425, 398, 151, 34))
login.caption = "Log in!"
login.set_style("login")
- signup = self.logingui.add(gui.Link, "signup", (345, 470, 310, 18))
+ signup = self.logingui.add(gui.Link, "signuplink", (345, 470, 310, 18))
signup.caption = "Don't have an account yet?"
signup.align = 1
signup.color = [140, 74, 31]
@@ -316,26 +316,26 @@
self.parent = parent
def keypress(self, obj, ev):
- if obj.name == "usr":
+ if obj.name == "usrtextbox":
# Using the enter key in the username field
if ev.type == KEYUP and ev.key == K_RETURN:
- self.parent.logingui.give_focus("pwd")
+ self.parent.logingui.give_focus("pwdtextbox")
- elif obj.name == "pwd":
+ elif obj.name == "pwdtextbox":
# Using the enter key in the password field
if ev.type == KEYDOWN and ev.key == K_RETURN:
- self.parent.logingui['login'].manualpush(True)
+ self.parent.logingui['loginbutton'].manualpush(True)
elif ev.type == KEYUP and ev.key == K_RETURN:
- self.parent.logingui['login'].manualpush(False)
- self.parent.logingui['login'].submit()
+ self.parent.logingui['loginbutton'].manualpush(False)
+ self.parent.logingui['loginbutton'].submit()
def submit(self, obj):
# Clicking the login button
- if obj.name == "login":
- usr = self.parent.logingui['usr'].input
- pwd = sha1(self.parent.logingui['pwd'].input).hexdigest()
+ if obj.name == "loginbutton":
+ usr = self.parent.logingui['usrtextbox'].input
+ pwd = sha1(self.parent.logingui['pwdtextbox'].input).hexdigest()
self.parent.logingui = None
sh['main'].call("status", {
@@ -348,8 +348,10 @@
sh['client'].login(usr, pwd)
- elif obj.name == "signup":
+ elif obj.name == "signuplink":
+ if self.parent.logingui.has("signup"): return
+
# Create signup window
window = self.parent.logingui.add(gui.Window, "signup", \
Rect(50, 50, 200, 200), SignupFeedback())
@@ -360,10 +362,10 @@
def mousedown(self, obj):
if obj.name == "usrlabel":
- self.parent.logingui.give_focus('usr')
+ self.parent.logingui.give_focus('usrtextbox')
elif obj.name == "pwdlabel":
- self.parent.logingui.give_focus('pwd')
+ self.parent.logingui.give_focus('pwdtextbox')
class SignupFeedback(gui.Feedback):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-06 16:00:39
|
Revision: 392
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=392&view=rev
Author: BlueWolf_
Date: 2010-09-06 16:00:32 +0000 (Mon, 06 Sep 2010)
Log Message:
-----------
Fixed a update bug when moving the window very fast to the topleft. Can't figure out yet why the inner-window looks partly transparent
Modified Paths:
--------------
trunk/client/gui.py
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-05 21:06:29 UTC (rev 391)
+++ trunk/client/gui.py 2010-09-06 16:00:32 UTC (rev 392)
@@ -576,7 +576,7 @@
# Combina the old rect and the new rect to update our whole move
updaterect = oldrect.union(self.rect)
- updaterect.topleft = (oldrect[0]-self.rect[0], oldrect[1]-self.rect[1])
+ updaterect.move_ip(-self.rect[0], -self.rect[1])
self.update(updaterect, render=False)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <Blu...@us...> - 2010-09-05 21:06:36
|
Revision: 391
http://virtplayground.svn.sourceforge.net/virtplayground/?rev=391&view=rev
Author: BlueWolf_
Date: 2010-09-05 21:06:29 +0000 (Sun, 05 Sep 2010)
Log Message:
-----------
Windows can now be moved and stacked. I also miiiight have forgotten to add the gui-window images in my last commit. So I'm adding it now.
There seems to be a minor pygame/SDL bug with transparent images above transparant images. It's barely noticable though
Modified Paths:
--------------
trunk/client/gui.py
trunk/client/playground.py
Added Paths:
-----------
trunk/client/images/gui/window.png
Modified: trunk/client/gui.py
===================================================================
--- trunk/client/gui.py 2010-09-04 22:48:33 UTC (rev 390)
+++ trunk/client/gui.py 2010-09-05 21:06:29 UTC (rev 391)
@@ -183,7 +183,7 @@
elif ev.type == MOUSEBUTTONDOWN: # Clicking
# Check which object we've focused
- rect, hover = self.this_pos(ev.pos)
+ rect, hover = self.this_pos(ev.pos, bringontop = True)
if hover:
pos = (ev.pos[0] - rect[0], ev.pos[1] - rect[1])
hover.click(0, pos)
@@ -230,15 +230,15 @@
elif (ev.type == KEYDOWN or ev.type == KEYUP) and self.focus:
self.focus.keypress(ev)
- def this_pos(self, pos):
+ def this_pos(self, pos, bringontop = False):
# Return the object and their actual rect on this position
- for child in self.children:
+ for child in reversed(self.children):
if not child.rect.collidepoint(pos): continue
child_pos = (pos[0] - child.rect[0], pos[1] - child.rect[1])
- rect, hover = child.this_pos(child_pos)
+ rect, hover = child.this_pos(child_pos, bringontop)
if hover:
return rect, hover
@@ -326,14 +326,15 @@
return obj
- def update(self, rect = None):
+ def update(self, rect = None, render = True):
"""
Update this part of the object
"""
# Send a message to our parent, telling them this rect needs to be
# updated
- self.needs_update = True
+ if render:
+ self.needs_update = True
if self.frozen: return
@@ -376,19 +377,30 @@
if isparent:
self.main_parent.update_mouse()
self.frozen = False
- self.update()
+
+ if self.needs_update:
+ self.update()
else:
self.frozen = False
- def this_pos(self, pos):
+ def this_pos(self, pos, bringontop = False):
# Return the object on this position
- for child in self.children:
+ # Bring to the foreground if needed
+ if bringontop and self.canrise:
+ # Find ourself in our parent's children-list
+ i = self.parent.children.index(self)
+ del self.parent.children[i]
+ self.parent.children.append(self)
+ self.update()
+
+ # Find the child on this position
+ for child in reversed(self.children):
if not child.rect.collidepoint(pos): continue
child_pos = (pos[0] - child.rect[0], pos[1] - child.rect[1])
- rect, hover = child.this_pos(child_pos)
+ rect, hover = child.this_pos(child_pos, bringontop)
rect.move_ip(child.rect[0], child.rect[1])
return rect, hover
@@ -416,9 +428,9 @@
self.backgroundsurf = self.surf.copy()
self.font = pygame.font.Font(real_path("fonts", \
"DejaVuSans-Bold.ttf"), 14)
+ self.buttonstate = 0 # 0 = Nothing, 1 = Hover, 2 = Click
+ self.mousepos = None # Mouse position when clicking the title
- self.buttonstate = 0
-
self.pos = {
# img is the position on the image
# pos is the rendered position
@@ -504,6 +516,8 @@
inner = self.calculate_pos(self.pos['inner_pos'])
self.backgroundsurf.fill(self.colors['bgcolor'], inner)
+ self.update()
+
def render(self):
self.surf.fill([0, 0, 0, 0])
self.surf.blit(self.backgroundsurf, (0,0))
@@ -537,13 +551,33 @@
self.surf.blit(self.gui, rect, img)
+ def click(self, state, pos):
+ if state == 0:
+ if self.canclose:
+ border = Rect(9, 9, self.rect.width-51, 28)
+ else:
+ border = Rect(9, 9, self.rect.width-18, 28)
+ if border.collidepoint(pos):
+ # Get the REAL pos, not the one relative to self.rect
+ self.mousepos = (pos[0]-self.rect[0], pos[1]-self.rect[1])
+ elif state == 1:
+ if self.mousepos != None:
+ movepos = [pos[0]-self.mousepos[0], pos[1]-self.mousepos[1]]
+ self.move(movepos)
+ elif state == 2:
+ self.mousepos = None
+ def move(self, newpos):
+ # Move the current window
+ oldrect = self.rect.move(0,0) # Where is .copy?
+ self.rect.topleft = newpos
- def move(self, topos):
- # [TODO]
- pass
+ # Combina the old rect and the new rect to update our whole move
+ updaterect = oldrect.union(self.rect)
+ updaterect.topleft = (oldrect[0]-self.rect[0], oldrect[1]-self.rect[1])
+ self.update(updaterect, render=False)
Added: trunk/client/images/gui/window.png
===================================================================
(Binary files differ)
Property changes on: trunk/client/images/gui/window.png
___________________________________________________________________
Added: svn:mime-type
+ application/octet-stream
Modified: trunk/client/playground.py
===================================================================
--- trunk/client/playground.py 2010-09-04 22:48:33 UTC (rev 390)
+++ trunk/client/playground.py 2010-09-05 21:06:29 UTC (rev 391)
@@ -352,7 +352,7 @@
# Create signup window
window = self.parent.logingui.add(gui.Window, "signup", \
- Rect(0, 0, 200, 200), SignupFeedback())
+ Rect(50, 50, 200, 200), SignupFeedback())
window.caption = "Signup"
window.unfreeze()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|