-
Notifications
You must be signed in to change notification settings - Fork 2
/
game.py
234 lines (191 loc) · 7.36 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import sys
import time
import random
import network
from entity import *
from config import Config
# Panda3d
from direct.showbase.DirectObject import DirectObject
from direct.task.Task import Task
from panda3d.core import WindowProperties
from panda3d.core import CollisionTraverser
from panda3d.core import Filename,AmbientLight,DirectionalLight
from panda3d.core import PandaNode,NodePath,Camera,TextNode
from panda3d.core import Vec2,Vec3,Vec4,BitMask32
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
import random, sys, os, math
WAIT_TIME = 1
UPDATE_TIME = 0.05
CONTROL_REDUNDANCY = 10 # number of extra times to send each control message from the client
class Controller(DirectObject):
def __init__(self, parentChar, keyMap):
assert isinstance(parentChar, Character)
base.disableMouse()
self.char = parentChar
self.keyMap = keyMap
print 'keymap is',keyMap
parentChar.node.rotationallyImmune = True
self.floater = NodePath('floater')
self.floater.reparentTo(parentChar.node)
self.floater.setPos(1,0,2)
base.camera.reparentTo(self.floater)
base.camera.setPos(0,-5,0)
base.camera.setH(0)
print base.camera.getPos(render)
props = WindowProperties()
props.setCursorHidden(True)
base.win.requestProperties(props)
taskMgr.add(self.controlCamera, 'camera-task')
self.h = parentChar.node.getH()
self.p = parentChar.node.getP()
#the parent of the camera - the character - is angled by the mouse
def controlCamera(self, task):
if not Config.mouseLookMode:
return task.cont
pointer = base.win.getPointer(0)
x,y = pointer.getX(), pointer.getY()
if base.win.movePointer(0,300,300):
self.h -= (x-300) * 0.1
self.p -= (y-300) * 0.1
if self.p < -90: self.p = -90
if self.p > 90: self.p = 90
#floater is node for pitch control
self.floater.setP(self.p)
#char is floater's parent, actually set it's heading
self.char.node.setH(self.h)
return task.cont
def getControl(self):
move = Vec2(
self.keyMap['Right']-self.keyMap['Left'],
self.keyMap['Fore']-self.keyMap['Back'])
move.normalize()
return [self.h, self.p, move.getX(), move.getY(), self.keyMap['Jump'], self.keyMap['Duck'], self.keyMap['Shoot']]
class AIController(DirectObject):
def __init__(self, parentChar):
assert isinstance(parentChar, Character)
self.char = parentChar
def getControl(self):
targets = [c.node.getPos() for c in CharacterPool.values() if c.nameNode.node().getText()[:3]!='Zom']
bestTarget, bestLength = None, ()
charPos = self.char.node.getPos()
for target in targets:
length = (target - charPos).length()
if length < bestLength:
bestTarget, bestLength = target, length
h = Vec2(0,1).signedAngleDeg(Vec2(bestTarget.getXy() - charPos.getXy()))
jump = bestTarget.getZ() - charPos.getZ() > 0.5
#print 'zombie looking in direction:', h, 'at', target, charPos
forward = 1 if bestLength > 2 else 0
return [h,0,0,forward,jump,0,0]
class World(DirectObject):
def __init__(self, isServer, name, ip, port, log):
self.log = log
self.config = Config()
#set up world
base.win.setClearColor(Vec4(0,0,0,1))
self.environ = loader.loadModel('resources/models/world')
self.environ.reparentTo(render)
self.environ.setPos(0,0,0)
Character.startPosition = self.environ.find('**/start_point').getPos()
#set up collisions
Character.collisionTraverser = CollisionTraverser()
if SHOW_COLLISIONS:
Character.collisionTraverser.showCollisions(render)
#set up networking
mode = network.MODE_SERVER if isServer else network.MODE_CLIENT
self.connection = network.Connection(mode, name, ip, port, log=self.log)
self.sendDeltaT = 0
#set up local client
self.control = Controller(self.connection.localUser.char, self.config.controlDict)
taskMgr.add(self.step, 'world-step')
#set up characters
if network.mode == network.MODE_SERVER:
self.ai = []
for i in range(1):
c = Character(name='Zombie')
self.ai.append(AIController(c))
print 'INITIALIZING SERVER WITH', len(self.ai), 'ZOMBIES'
else:
self.controlList = []
def stepServer(self, updateDue):
assert network.mode == network.MODE_SERVER
network.sendReceive()
# handle received client input
while self.connection.readQueue:
packet = self.connection.readQueue.popleft()
assert packet.opCode == network.CL_UPDATE
#print 'saw client update, from time', packet.data[0]
packet.sender.addControlState(packet.data[0],packet.data[1])
# Simulate characters attempting to move
for control in ([self.control]+self.ai):
control.char.applyControl(globalClock.getDt(), control.getControl(), control==self.control)
timeStamp = time.clock()
for user in UserPool.values():
if user != self.connection.localUser:
user.char.applyControl(globalClock.getDt(), user.takeControlStateSample(timeStamp), False)
Character.collisionTraverser.traverse(render)
# handle collide case
for c in CharacterPool.values():
c.postCollide()
# process explosions, then projectiles
for e in EffectPool.values():
if not e.movePostCollide(globalClock.getDt()):
EffectPool.remove(e)
del NetEnt.entities[e.id]
del e
for p in ProjectilePool.values():
if not p.movePostCollide(globalClock.getDt()):
Effect(parentNode=p.node)
ProjectilePool.remove(p)
del NetEnt.entities[p.id]
del p
# For each connected client, package up visible objects/world state and send to client
if updateDue:
entstate = NetEnt.getState()
for user in UserPool.values():
if user == self.connection.localUser:
continue
self.connection.writeQueue.append(network.Packet(user, network.SV_UPDATE, entstate))
network.sendReceive()
def stepClient(self, updateDue):
assert network.mode == network.MODE_CLIENT
timeStamp = network.getTime()
localControl = self.control.getControl()
if updateDue:
# add client timestamp, client input sample to list, then send to server
controlData = (timeStamp, localControl)
self.connection.writeQueue.append(network.Packet(self.connection.serverUser, network.CL_UPDATE, controlData)) #self.controlList))
network.sendReceive()
# Use packets to determine visible objects and their state
while self.connection.readQueue:
packet = self.connection.readQueue.popleft()
assert packet.opCode == network.SV_UPDATE
assert packet.sender == self.connection.serverUser
NetEnt.addGlobalState(packet.sentTime, packet.data)
localChar = self.connection.localUser.char
# update all non-local characters
NetEnt.takeGlobalStateSample(network.getTime(), skipList=[localChar.id])
# apply input to local char speculatively, #todo: consider collisions?
localChar.applyControl(globalClock.getDt(), localControl, True, timeStamp=timeStamp)
Character.collisionTraverser.traverse(render)
localChar.postCollide()
localChar.applyCorrection(timeStamp)
def step(self, task):
# determine if an update packet is due
self.sendDeltaT += globalClock.getDt()
updateDue = self.sendDeltaT > UPDATE_TIME
if network.mode == network.MODE_SERVER:
self.stepServer(updateDue)
else:
self.stepClient(updateDue)
#reset update counter
if updateDue:
# increase time to next update (but never allow more than 1 update 'owed')
self.sendDeltaT = min(self.sendDeltaT-UPDATE_TIME, UPDATE_TIME)
# orient the sprites correctly
for item in CharacterPool.values()+ProjectilePool.values():
if item.sprite:
item.sprite.updateCameraAngle(base.camera)
#print
return task.cont