Links und Funktionen
Sprachumschaltung

Navigationspfad
Sie sind hier: Startseite / Probestudium / 2011 / WS I: 3D-Programmierung / Arbeitsgruppen / 3D Pong / 3dpong_0.9_src


Inhaltsbereich

3dpong_0.9_src

Fast fertig. ;-)

pong_full.py — text/python-source, 7 KB (7419 bytes)

Dateiinhalt

"""
this code is absolutely uncommented.
use it on ur own risk.
coypright_list = ["maximilian bandle", "niklas rosenstein", "julia katheder", "marvin batshoun", "katrin unknown"]
**BUT** Coded only by copyright_list[:2]
"""


from visual     import *
from sys        import argv
from time       import time
from random     import random,choice
from copy       import copy

def wait(seconds):
    start   = time()
    while True:
        delta = time()-start
        if delta > seconds: break

def interpolatebetweentupels(x,tup1,tup2):
    r       = []
    for i in range(len(tup1)):
        r.append((tup1[i]*x + tup2[i]*(1-x)))
    return tuple(r)

class ball(sphere): #visual class
    def __init__(self,speed,direction,radius=20,color=(1,1,)):
        sphere.__init__(self,radius=radius)
        self.material   = materials.plastic
        self.speed      = speed
        self.SetDirection(direction)

    def SetDirection(self,v):
        if isinstance(v,tuple) or isinstance(v,list):
            v = vector(v[0],v[1],v[2])
        v.norm()
        self.direction = v

    def Calculate(self,fps):
        self.pos       += self.direction*self.speed / fps

    def Invert(self,axis):
        if axis == 'x':
            self.direction.x *= -1
        elif axis == 'y':
            self.direction.y *= -1
        elif axis == 'z':
            self.direction.z *= -1
        else:
            raise IndexError, 'char for 3d axis expected <x,y,z>'

    def SetColor(self,value):
        self.color      = value

    def stop(self):
        self.speed      = 0

class player:
    def __init__(self,pos,racketsize,movement=800,color=(1,1,1,),keys=['up','down','left','right']):
        self.symbol     = box(pos=pos,opacity=0.5,color=color,**racketsize)
        self.keys       = keys
        self.movement   = movement

    def Calculate(self,key,game):
        ball        = game.ball
        collision   = game.xcollision
        movement    = self.movement/float(game.fps)
        if key:
            if key == self.keys[0]:
                self.symbol.pos += vector(0,movement,0)
            if key == self.keys[1]:
                self.symbol.pos += vector(0,-movement,0)
            if key == self.keys[2]:
                self.symbol.pos += vector(0,0,-movement)
            if key == self.keys[3]:
                self.symbol.pos += vector(0,0,movement)

        


        if collision and collision == self:
            racketpos   = self.symbol.pos.z,self.symbol.pos.y
            ballpos     = ball.pos.z-racketpos[0],ball.pos.y-racketpos[1]
            hitx,hity   = False,False
            if abs(ballpos[0]) < self.symbol.width/2.:
                hitx    = True
            if abs(ballpos[1]) < self.symbol.height/2.:
                hity    = True
            if not hitx or not hity:
                game.looser = self

class game:
    def __init__(self,ballspeed=200,fps=25,names=["Player 1","Player 2"],fieldsize={'width':200,'height':200,'length':800,'opacity':0.2}):
        """
        self.otherwin       = display(  width   = 300,
                                        height  = 300,
                                        x       = 300,
                                        y       = 300)
        #self.otherwin.select()
        self.otherwin.visible    = True
        """
        scene.width         = 600; scene.height = 600


        self.fps            = fps
        self.box            = box(**fieldsize)
        self.ball           = ball(ballspeed,(1,0.4,0.2),radius=10)
        self.ball.color = (0,0,0)

        playersize          = {'width':100,'height':50,'length':5}
        self.playernames    = names
        self.players        = [ player( (-fieldsize['length']/2.,0,0), playersize, color = (0.6,0.8,0.8)),
                                player( (fieldsize['length']/2.,0,0), playersize, keys = ['w','s','d','a'], color = (0.8,0.6,0.8))]

        self.xcollision     = False

        self.looser         = None
        self.label          = None

    def VectorToList(self,vec):
        return [vec.x,vec.y,vec.z]

    def createlabel(self,looser,loosername):
        if self.label:
            self.label.visible  = True
            self.label.color    = looser.symbol.color
            self.label.text     = "%s did loose" % loosername
        else:
            self.label          = label(color = self.looser.symbol.color, text = "%s did loose" % loosername, axis = scene.forward)

    def killlabel(self):
        if self.label: self.label.visible   = False

    def playerside(self,xcoord):
        if xcoord < 0: return self.players[0]
        return self.players[1]

    def calcelements(self):
        rad                 = self.ball.radius
        x,y,z               = self.VectorToList(self.ball.pos)
        if  abs(x)+rad > self.box.length/2.:
            self.ball.Invert('x')
            self.xcollision     = self.playerside(x)
            """
                self.ball.stop()
                self.isrunning  = False
                self.winner     = self.winningplayer(x)
            """
        else:
            self.xcollision     = None
        if  abs(y)+rad > self.box.height/2.:
            self.ball.Invert('y')
        if  abs(z)+rad > self.box.width/2.:
            self.ball.Invert('z')

        ln                  = self.box.length
        inter               = (x+(ln/2.))/float(ln)
        self.ball.SetColor(interpolatebetweentupels(inter,self.players[1].symbol.color,self.players[0].symbol.color))

    def end(self):
        scene.exit()

    def gamedidend(self):
        self.box.color  = (1,0.2,0.2)
        self.looser     = None
        while True:
            rate(self.fps)
            if scene.kb.keys:
                if scene.kb.getkey() == '\n':
                    print "new game started"
                    self.run()
                    break
                else:
                    pass

    def resetball(self):
        self.ball.pos       = (0,0,0)
        direction           = [choice([1,-1]),random(),random()]
        self.ball.SetDirection(direction)

    def next(self):
        self.ball.Calculate(self.fps)
        self.calcelements()
        if scene.kb.keys:
            key         = scene.kb.getkey()
        else: key = None
        for player in self.players:
            self.running    =  player.Calculate(key,self)

    def run(self):
        #copy(scene)
        self.killlabel()
        self.box.color      = (1,1,1)
        self.isrunning      = True
        self.winner         = None
        self.resetball()

        while not self.looser:
            rate(self.fps)    #visual command
            self.next()

        looser = self.players.index(self.looser)
        print "The looser is {looser}".format(looser=self.playernames[looser])

        self.createlabel(self.looser,self.playernames[looser])

        self.gamedidend()
        self.exit()

def main(argv):
    try: ballspeed  = float(argv[1])
    except: ballspeed   = 300.
    try: names      = [argv[2],argv[3]]
    except: names       = ["Player 1","Player 2"]
    try: fps        = argv[4]
    except: fps         = 25

    g = game(ballspeed,fps,names)
    g.run()

if __name__ == '__main__': main(argv)

Funktionsleiste