Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Soccer_Halftable_Revised.py
- ### entire zip file can be found at this link http://www.datafilehost.com/d/e251cd13
- # The ORIGINAL version of this game was developed for the course
- # "interaction technologies" of the master course "mobile computing"
- # at the University of Applied Sciences Hagenberg by Benjamin Gmeiner
- # and Yen-Chia Lin
- #
- # Special thanks to Christopher Schmidt (http://crschmidt.net/), who's
- # open source project "Accelball" made it a lot easier and faster to
- # access the Accelerometer data
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- #
- # Copyright (c) 2008 Gmeiner Benjamin, benjamin.gmeiner@fh-hagenberg.at
- # Yen-Chia Lin, yen-chia.lin@fh-hagenberg.at
- #
- from graphics import *
- from sensor import *
- import e32, audio, appuifw, os, sys, key_codes, time, math, random, graphics, sensor, string
- import sysinfo, gc, copy
- CUR_AUTHOR = 1 # 0 for debugging
- PLAY_SOUNDS = 1 # 0 for skipping sounds
- DRAW_DEBUG = 0
- DRAW_FPS = False
- boundary_width = 492
- max_x = 500 ### <<< ref
- max_y = 360 ### <<< ref
- canvasImage = None
- class GameObject(object):
- x = 0
- y = 0
- width = 0
- height = 0
- imgX = 0 # draw image delta
- imgY = 0 # draw image delta
- def getPoint(self):
- return [self.x, self.y]
- def getMaxX(self):
- return self.x + self.width + self.imgX
- def getMaxY(self):
- return self.y + self.height + self.imgY
- def getInX(self): ### leftmost contact perimeter
- return self.x + self.imgX
- def getInY(self): ### top contact perimeter
- return self.y + self.imgY
- def drawBoundingBox(self, image):
- image.rectangle((self.getInX(), self.getInY(), self.getMaxX(), self.getMaxY()),outline = COLOR_BLUE)
- class SensorConnection():
- xAxis = 0
- yAxis = 0
- def __init__(self):
- """Connect to the sensor."""
- self.accelerometer = AccelerometerXYZAxisData(data_filter=LowPassFilter())
- self.accelerometer.set_callback(data_callback=self.sense_conn)
- def sense_conn(self):
- self.xAxis = self.accelerometer.x*-1 ### <<<
- self.yAxis = self.accelerometer.y*-1 ### <<<
- def run(self):
- self.accelerometer.start_listening()
- def cleanup(self):
- """Cleanup after yourself. *Must be called* before exiting."""
- self.accelerometer.stop_listening() ### <<<
- def handle_redraw(rect):
- if canvasImage: ### Skips only at first pass as "None"
- canvas.blit(canvasImage)
- def quit():
- global running
- running=0
- def exitLoading(reason):
- appuifw.note(reason, "error")
- os._exit(reason)
- #===============================================================================
- # Sound Methods
- #===============================================================================
- def playSoundShoot():
- global sound_hit, PLAY_SOUNDS
- if(PLAY_SOUNDS == 1):
- if sound_hit.state() != audio.EPlaying:
- sound_hit.play()
- #===============================================================================
- # Key Toggle Methods
- #===============================================================================
- def toggle_PlaySounds():
- global PLAY_SOUNDS
- if PLAY_SOUNDS == 1:
- PLAY_SOUNDS = 0
- else:
- PLAY_SOUNDS = 1
- '''
- def toggle_CurrentAuthor():
- global CUR_AUTHOR
- CUR_AUTHOR += 1
- CUR_AUTHOR = CUR_AUTHOR % 3
- def toggle_DrawDebug():
- global DRAW_DEBUG
- if DRAW_DEBUG == 1:
- DRAW_DEBUG = 0
- else:
- DRAW_DEBUG = 1
- def toggle_DrawFPS():
- global DRAW_FPS
- DRAW_FPS = not DRAW_FPS
- '''
- #===============================================================================
- # Image Processing
- #===============================================================================
- def automask(im):
- width, height = im.size
- mask = Image.new(im.size, '1') # black and white
- tran = im.getpixel((0,0))[0] # transparent top-left
- for y in range(height):
- line = im.getpixel([(x, y) for x in range(width)])
- for x in range(width):
- if line[x] == tran:
- mask.point((x,y), 0) # mask on the point
- return mask
- #Converts the specified "area" of the image into an image mask
- #Transparent color is the color found in the upper left pixel
- def automaskArea(im, area):
- width = area[2] - area[0]
- height = area[3] - area[1]
- startX = area[0]
- startY = area[1]
- mask = Image.new((width, height), '1') # black and white
- tran = im.getpixel((startX,startY))[0] # transparent top-left
- for y in range(height):
- for x in range(width):
- if im.getpixel((startX + x, startY + y))[0] == tran:
- mask.point((x,y),0)
- return mask
- def statusupdate(im, status, progress):
- global loadingStatusLine
- im.text((10,20), u"Initialising..." + progress, fill = COLOR_BLACK)
- im.text((10,50 + loadingStatusLine * 20), u"> " + status, fill=COLOR_BLACK)
- loadingStatusLine += 1
- handle_redraw(())
- #===============================================================================
- # Collistion Detection Methods
- #===============================================================================
- def checkWallBoundary():
- """Returns true, if ball collides with the wall behind the goalie"""
- global m_ball, m_goalObject, boundary_width
- return m_ball.y <= 14 and (
- (m_ball.x >= 0 and m_ball.x + m_ball.width < m_goalObject.x) or
- (m_ball.x > m_goalObject.getMaxX() and m_ball.x <= boundary_width))
- def checkSideBoundary():
- """Returns true, if ball colides with Side Boundary"""
- global m_ball
- if m_ball.x < 0:
- m_ball.x = 0
- return True
- elif m_ball.getMaxX() > boundary_width:
- m_ball.x = boundary_width - m_ball.width
- return True
- return False
- def checkBackWallBoundary():
- """Returns true, if ball collides with Boundary"""
- global m_ball
- if m_ball.y > max_y - m_ball.height:
- m_ball.y = max_y - m_ball.height
- return True
- return False
- ### checks collision detection
- def checkCollision(objA, objB): ### +++
- return ((objA.getInX() < objB.getMaxX()) and (objB.getInX() < objA.getMaxX()) and
- (objA.getInY() < objB.getMaxY()) and (objB.getInY() < objA.getMaxY()))
- #===============================================================================
- # Helper Methods
- #===============================================================================
- def doGoalAchieved():
- global goalsAchieved, statusImage, timeLeft
- goalsAchieved += 1
- statusImage = createStatusBox(goalsAchieved, timeLeft)
- playSoundShoot()
- resetBall()
- def resetBall(): ### +++ ball
- global m_ball, ballSpeed, ball_reset
- m_ball.x, m_ball.y = [random.randrange(30, 420), 270]
- ballSpeed = [10,-0.05] ### >>> ball_reset
- def isSameDirection(v1, v2): ### +++ v1=v2
- return (v1 < 0 and v2 < 0 and v2 < v1) or (v1 > 0 and v2 > 0 and v2 > v1)
- def updateFPS():
- global prevTime, totalTime, fpsResult, fpsCounter
- curTime = time.time()
- frameTime = curTime - prevTime
- prevTime = curTime
- totalTime += frameTime
- if totalTime >= 1:
- fpsResult = fpsCounter + 1
- fpsCounter = 0
- totalTime = 0
- fpsCounter += 1
- def createStatusBox(count, timeleft):
- statImg = Image.new((182, 60),'RGB16') ### <<<
- statImg.clear(COLOR_ORANGE)
- statImg.rectangle((0, 0, 182, 60), width = 4, outline = COLOR_BLACK) ### <<<
- statImg.text((10,25), u"Goals: " + unicode(count),font='dense', fill = COLOR_BLACK) ### <<<
- # countdown
- statImg.text((10,48), u"Time Left: " + unicode(timeleft)+ " s", font ='dense', fill = COLOR_BLACK) ### <<<
- return statImg ### >>> statImg.transpose(ROTATE_90)
- def calibrateNeutralValue():
- global accl, neutralValue
- neutralValue = accl.yAxis
- #===============================================================================
- # color definintions
- #===============================================================================
- COLOR_BLACK = 0x000000
- COLOR_WHITE = 0xffffff
- COLOR_GRAYLIGHT = 0xeeeeee
- COLOR_GRAYDARK = 0x666666
- COLOR_BLUE = 0x0000ff
- COLOR_GREEN = 0x00ff00
- COLOR_RED = 0xff0000
- COLOR_ORANGE = 0xffcc00
- #===============================================================================
- # BEGIN Main() more or less ...
- #===============================================================================
- m_goalie = GameObject()
- m_attackPlayer1 = GameObject()
- m_attackPlayer2 = GameObject()
- m_goalObject = GameObject()
- appuifw.app.orientation='landscape'
- appuifw.app.screen = 'large'
- appuifw.app.directional_pad = False
- loadingStatusLine = 1
- canvas = appuifw.Canvas(redraw_callback = handle_redraw)
- appuifw.app.body = canvas
- buf = Image.new(canvas.size)
- canvasImage = Image.new(canvas.size)
- #===============================================================================
- # key bindings
- #===============================================================================
- '''
- canvas.bind(key_codes.EKeyStar, toggle_PlaySounds)
- canvas.bind(key_codes.EKeyHash, toggle_CurrentAuthor)
- canvas.bind(key_codes.EKeySelect, playSoundShoot)
- canvas.bind(key_codes.EKey0, toggle_DrawDebug)
- canvas.bind(key_codes.EKey5, resetBallKeyBinding)
- canvas.bind(key_codes.EKey2, calibrateNeutralValue)
- canvas.bind(key_codes.EKey3, toggle_DrawFPS)
- '''
- appuifw.app.exit_key_handler=quit
- #===============================================================================
- # PROPERTIES
- #===============================================================================
- running = 1
- accl = SensorConnection()
- accl.run() ### <<<
- #determine python root (where is our script installed)
- #this has to be c:\\python or e:\\python
- PYTHON_ROOT = u"E:\\Python\\pyWuzzler\\"
- '''
- if(os.path.exists("C:\\private\\a000902D\\default.py")):
- PYTHON_ROOT = u"C:\\private\\a000902D\\pyWuzzler\\"
- elif(os.path.exists("E:\\private\\a000902D\\default.py")):
- PYTHON_ROOT = u"E:\\private\\a000902D\\pyWuzzler\\"
- elif(os.path.exists("C:\\data\\Python\\pyWuzzler.py")):
- PYTHON_ROOT = u"C:\\data\\Python\\pyWuzzler\\"
- elif(os.path.exists("E:\\data\\Python\\pyWuzzler.py")):
- PYTHON_ROOT = u"E:\\data\\Python\\pyWuzzler\\"
- else:
- exitLoading(u"couldn't determine python source directory")
- '''
- # draw init Background and start initialisation
- if(os.path.exists(PYTHON_ROOT + u"initBackground.png")):
- initBackroundImage=Image.open(PYTHON_ROOT + u"initBackground.png")
- else:
- exitLoading(PYTHON_ROOT + u"initBackground.png missing!");
- canvasImage.blit(initBackroundImage, target=(0, 0))
- statusupdate(canvasImage, "starting initialisation", "...")
- statusupdate(canvasImage, "initialising basic properties", "...")
- ################################################################################
- ##### +++++ Main Setting and Directory #########################################
- ################################################################################
- acceleration = 0.5 ### +++ player y acceleration
- neutralValue = 42 # value that specifies at which angle the player is in a neutral position -> can be used for calibration
- noOfAnimations = 37 # number of animations
- frontArea = [0, 1, 2, 3, 4, 5] # define front areas
- neutralArea = [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] # define a neutral area, where the model stays in a neutral position and can interact with the ball
- backArea = [31, 32, 33, 34, 35, 36, 37] # define the states that is when the player is in back position
- lastState = 0 # last player state
- player_speed = [0,0]
- goalsAchieved = 0
- #===============================================================================
- # properties of ball
- #===============================================================================
- m_ball = GameObject()
- ball_reset = [10,-0.05] ### <<<
- ballSpeed = ball_reset
- BALL_MAX_SPEED = 16
- ballFriction = 0.995
- x_gravity = 0.2
- y_gravity = 0.025
- ballShootAngle = 60 ### ZZZ from middle to right or left most angle (in grad)
- shootForce = 0
- #===============================================================================
- # Variables for FPS
- #===============================================================================
- startTime = time.time()
- prevTime = startTime
- totalTime = 0
- fpsCounter = 0
- fpsResult = 0
- timePassed = 0
- timeLimit = 180
- timeLeft = timeLimit
- #===============================================================================
- # LOAD SOUNDS
- #===============================================================================
- if(os.path.exists(PYTHON_ROOT + u"hit.wav") and
- os.path.exists(PYTHON_ROOT + u"hit.wav") and
- os.path.exists(PYTHON_ROOT + u"hit.wav")):
- statusupdate(canvasImage, "loading sounds","...")
- sound_hit = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
- sound_goal = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
- sound_bounce = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
- else:
- exitLoading(u"some audio files are missing");
- #===============================================================================
- # PRE-RENDERING AND IMAGE LOADING
- #===============================================================================
- statusupdate(canvasImage, "loading player models, will take ","...")
- statusupdate(canvasImage, "a while on first run","...")
- attackstate = 0 #ranges from -2 (most left) to 2 (most right)
- if(os.path.exists(PYTHON_ROOT + u"playerSprites.png")):
- playerImage=Image.open(PYTHON_ROOT + u"playerSprites.png")
- else:
- exitLoading(u"player sprites-file is missing");
- #create image mask if it doesn't exist yet, otherwise load from fs
- playerImageMasks = []
- for val in range(noOfAnimations):
- fName = PYTHON_ROOT + u"playerMask_" + unicode(val) + ".png"
- if(os.path.exists(fName)):
- maskImg = Image.new(size=(34,100), mode='1')
- maskImg.load(fName)
- playerImageMasks.append(maskImg)
- else:
- playerImageMasks.append(automaskArea(playerImage, (0,val*34, 100, (val+1)*34)))
- playerImageMasks[val].save(fName, format='PNG', compression='no', quality=1, bpp=1)
- #defender
- imgName = PYTHON_ROOT + u"defenderSprites.png"
- maskName = PYTHON_ROOT + u"defenderSprites_mask.png"
- if(os.path.exists(imgName)):
- defenderImage = Image.open(imgName)
- else:
- exitLoading(u"goalie sprites-file is missing");
- if(os.path.exists(maskName)):
- defenderImageMask = Image.new(defenderImage.size, mode='1') #todo: get variable size!!!
- defenderImageMask.load(maskName)
- else:
- defenderImageMask = automask(defenderImage);
- defenderImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
- #statusupdate(img, "creating player model mask","...")
- statusupdate(canvasImage, "loading ball sprites and creating mask", "...")
- imgName = PYTHON_ROOT + u"sprites_ballV2.png"
- maskName = PYTHON_ROOT + u"sprites_ballV2_mask.png"
- if(os.path.exists(imgName)):
- ballImage = Image.open(imgName)
- else:
- exitLoading(u"ball sprites-file is missing");
- if(os.path.exists(maskName)):
- ballImageMask = Image.new(ballImage.size, mode='1')#todo: get variable size!!!
- ballImageMask.load(maskName)
- else:
- ballImageMask = automask(ballImage);
- ballImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
- statusupdate(canvasImage, "loading pole sprites and creating mask", "...")
- imgName = PYTHON_ROOT + u"pole.png"
- maskName = PYTHON_ROOT + u"pole_mask.png"
- if(os.path.exists(imgName)):
- poleImage = Image.open(imgName)
- else:
- exitLoading(u"pole sprites-file is missing");
- if(os.path.exists(maskName)):
- poleImageMask = Image.new(poleImage.size, mode='1')#todo: get variable size!!!
- poleImageMask.load(maskName)
- else:
- poleImageMask = automask(poleImage);
- poleImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
- statusupdate(canvasImage, "loading background", "...")
- if(os.path.exists(PYTHON_ROOT + u"background.png")):
- bgImage = Image.open(PYTHON_ROOT + u"background.png")
- else:
- exitLoading(u"background file is missing");
- #properties of attacking player
- statusupdate(canvasImage, "initialising some properties, we're almost done ;)", "...")
- #===============================================================================
- # init GameObjects +++++
- #===============================================================================
- prev_locf = 0
- prev_locb = 0
- dist_players = 180 # x distance point of players
- playerHeight = 14
- m_attackPlayer1.width = m_attackPlayer2.width = 16
- m_attackPlayer1.height = m_attackPlayer2.height = playerHeight
- m_attackPlayer1.x = 132 ### player max left = 10 : max right = 261
- m_attackPlayer1.y = m_attackPlayer2.y = 200
- m_attackPlayer1.imgX = m_attackPlayer2.imgX = 9
- m_attackPlayer1.imgY = m_attackPlayer2.imgY = 14 ### swing contact bearing 14=axis-38 : 70=axis-28 // 70-14=56 divided by 10 = 5.6
- m_attackPlayer2.x = m_attackPlayer1.x + dist_players ### player max right = 459
- m_ball.x, m_ball.y = [random.randrange(25, 250), 320]
- m_ball.width = ballImage.size[1]
- m_ball.height = ballImage.size[0]
- m_goalie.x = 240 ### centre of the goal
- m_goalie.y = 24 ### dist in front of the goal
- m_goalie.width = 16
- m_goalie.height = 14
- m_goalie.imgX = 8
- m_goalie.imgY = 16
- m_goalObject.x = 164
- m_goalObject.y = 0
- m_goalObject.width = 136
- m_goalObject.height = 12
- #properties of defending player
- speedAttackPlayer = [0,0]
- defSpeed = 0
- #properties of the goal
- leftGoalMargin = 164
- rightGoalMargin = 284
- gameRunning = 0
- prev_force = 0
- res = appuifw.query(u"Start by pressing OK", "query")
- if(res == 1): gameRunning = 1
- startTime = time.time()
- framedelay = 0
- while(gameRunning):
- statusImage = createStatusBox(goalsAchieved,timeLeft)
- while running:
- if(time.time() - startTime - timePassed > 1): # over one second passed
- timePassed = timePassed + 1
- timeLeft = timeLimit - timePassed
- statusImage = createStatusBox(goalsAchieved, timeLeft)
- if timeLeft % 25 == 0:
- e32.reset_inactivity()
- if(timeLeft <= 0):
- running = 0
- indexRaw = accl.xAxis # kick value
- force_index = int(indexRaw*2.5) + neutralValue
- # calculate current player state
- if (force_index < 0):
- force_index = 0
- elif (force_index > noOfAnimations-1):
- force_index = noOfAnimations-1
- src = ((force_index * 34, 0),((force_index+1)*34, 100))
- #draw Background
- buf.rectangle((504,0,640,360),fill=(COLOR_BLACK))
- buf.blit(bgImage, target=(0,0))
- #draw status window
- buf.blit(statusImage, target=(0,buf.size[1] - statusImage.size[1]))
- #draw ball
- buf.blit(ballImage, target=m_ball.getPoint(), mask=ballImageMask, scale=0)
- #draw poles
- buf.blit(poleImage, target=(0,0), mask=poleImageMask)
- buf.blit(poleImage, target=(0,200), mask=poleImageMask)
- #Draw goalie (defending player)
- buf.blit(defenderImage, target=m_goalie.getPoint(), mask=defenderImageMask)
- #Draw first attacking player
- buf.blit(playerImage, target=m_attackPlayer1.getPoint(), source=src, mask=playerImageMasks[force_index], scale=0)
- #Draw second attacking player
- buf.blit(playerImage, target=m_attackPlayer2.getPoint(), source=src, mask=playerImageMasks[force_index], scale=0)
- if(CUR_AUTHOR == 0):
- buf.text((10,20), u"xAxis: " + unicode(accl.xAxis), fill = COLOR_BLACK)
- buf.text((100,20), u"Index: " + unicode(force_index), fill = COLOR_BLACK)
- buf.text((10,40), u"Ball x: " + unicode(m_ball.x), fill= COLOR_BLACK)
- buf.text((10,60), u"Ball y: " + unicode(m_ball.y), fill= COLOR_BLACK)
- buf.text((10,80), u"Ball vx: " + unicode(ballSpeed[0]), fill= COLOR_BLACK)
- buf.text((10,100), u"Ball vy: " + unicode(ballSpeed[1]), fill= COLOR_BLACK)
- # Draw Boundingboxes
- if DRAW_DEBUG:
- m_ball.drawBoundingBox(buf)
- m_attackPlayer1.drawBoundingBox(buf)
- m_attackPlayer2.drawBoundingBox(buf)
- m_goalie.drawBoundingBox(buf)
- m_goalObject.drawBoundingBox(buf)
- # updating FPS
- ### >>> updateFPS()
- ### >>> if(DRAW_FPS or CUR_AUTHOR == 1): buf.text((200, 10), u"FPS: " + unicode(fpsResult), fill = COLOR_BLACK)
- # calculate position of goalie
- if(m_goalie.x < m_ball.x):
- if(m_goalie.x >= rightGoalMargin + 10 or m_ball.x - m_goalie.x < 10):
- defSpeed = 0 #if the def player is at the Margin of the goal, stop moving
- else:
- defSpeed = 2
- if(m_goalie.x > m_ball.x):
- if(m_goalie.x < leftGoalMargin - 20 or m_goalie.x - m_ball.x < 10):
- defSpeed = 0 #if the def player is at the Margin of the goal, stop moving
- else:
- defSpeed = -2
- m_goalie.x += defSpeed
- # calculate speed and position of player
- PlayerSpeed = accl.yAxis * 0.2 ### MAX: accl.yAxis = 48
- m_attackPlayer1.x -= PlayerSpeed
- m_attackPlayer2.x -= PlayerSpeed
- if m_attackPlayer1.x < 10:
- m_attackPlayer1.x = 10
- m_attackPlayer2.x = 10 + dist_players
- if m_attackPlayer1.x >= 268:
- m_attackPlayer1.x = 268
- m_attackPlayer2.x = 268 + dist_players
- #===============================================================================
- # check for shoot
- #===============================================================================
- ##### +++++ getting a "kick" out of this game
- shootForce = (prev_force - force_index) * 1.25
- if shootForce == 0: shootForce = 1
- if shootForce > prev_force and shootForce > 7:
- shootForce = BALL_MAX_SPEED
- prev_locf = 10
- elif shootForce < prev_force and shootForce < -7:
- shootForce = -9 ### -BALL_MAX_SPEED
- prev_locb = -10
- else:
- prev_locf, prev_locb = 0,0
- prev_force = force_index
- m_attackPlayer1.height = playerHeight + prev_locf
- m_attackPlayer2.height = playerHeight + prev_locf
- m_attackPlayer1.imgY = 14 + ((force_index - 8) *2.725) + prev_locb
- m_attackPlayer2.imgY = 14 + ((force_index - 8) *2.725) + prev_locb
- boundaryBounce = False
- #===============================================================================
- # Ball Physics
- #===============================================================================
- if m_ball.y < 60:
- #===============================================================================
- # check GOAL
- #===============================================================================
- if checkCollision(m_ball, m_goalObject):
- doGoalAchieved()
- if checkWallBoundary():
- m_ball.y = 14
- ballSpeed[1] *= -1
- #===============================================================================
- # check ball collision with goalie
- #===============================================================================
- if checkCollision(m_goalie, m_ball): ### ??? should add def swing ani
- ballSpeed[1] = 4
- playSoundShoot()
- #===============================================================================
- # detect SHOOT!!!
- #===============================================================================
- if force_index in neutralArea:
- player1Shoot = checkCollision(m_attackPlayer1, m_ball)
- player2Shoot = checkCollision(m_attackPlayer2, m_ball)
- if player1Shoot or player2Shoot:
- if shootForce < -7: #abs(shootForce) > 7:
- playSoundShoot()
- shootForce -= 5
- # collision with player
- ballCenter = m_ball.x + m_ball.width / 2
- playerX = 0 ### represents either m_attackPlayer1 or m_attackPlayer2
- if player1Shoot:
- playerX = m_attackPlayer1.getMaxX()
- else:
- playerX = m_attackPlayer2.getMaxX()
- playerHalfWidth = m_attackPlayer1.width / 2
- _res = playerX - ballCenter - playerHalfWidth
- vx = ((shootForce/3)/playerHalfWidth) * _res
- if _res < 0:
- # ballcenter is left of player
- ballSpeed = [-vx, shootForce*-1]
- else:
- # ballcenter is right of player
- ballSpeed = [vx, shootForce*-1]
- boundaryBounce = checkSideBoundary()
- #print ballSpeed
- m_attackPlayer1.x = m_attackPlayer2.x - dist_players
- else: ### ^^^ index outside of neutralArea -- hides passing contact areas
- m_attackPlayer1.height = -1
- m_attackPlayer2.height = -1
- #===============================================================================
- # boundary check
- #===============================================================================
- if checkSideBoundary():
- ballSpeed[0] *= -1
- if checkBackWallBoundary():
- ballSpeed[1] = (ballSpeed[1]/1.25) * -1
- # apply new ball speed
- ballSpeed[1] *= ballFriction
- ballSpeed[0] *= ballFriction
- m_ball.x += ballSpeed[0]
- m_ball.y += ballSpeed[1]
- # limit the speed of the ball
- if ballSpeed[0] > BALL_MAX_SPEED:
- ballSpeed[0] = BALL_MAX_SPEED
- elif ballSpeed[0] < -BALL_MAX_SPEED:
- ballSpeed[0] = -BALL_MAX_SPEED
- if ballSpeed[1] > BALL_MAX_SPEED:
- ballSpeed[1] = BALL_MAX_SPEED
- elif ballSpeed[1] < -BALL_MAX_SPEED:
- ballSpeed[1] = -BALL_MAX_SPEED
- # to gravitate toward player zone
- if m_ball.x < 12:
- ballSpeed[0] += x_gravity
- elif m_ball.x > 450:
- ballSpeed[0] -= x_gravity ###
- if m_ball.y < 200:
- if m_ball.y < 120 and (m_ball.x + m_ball.width < m_goalObject.x - 20) or (m_ball.x > m_goalObject.getMaxX() + 20):
- ballSpeed[1] += y_gravity + 0.1
- else:
- ballSpeed[1] += y_gravity
- elif m_ball.y > 254:
- ballSpeed[1] -= y_gravity
- #===============================================================================
- # Ball Physics end
- #===============================================================================
- canvasImage=copy.copy(buf)
- handle_redraw(())
- buf = Image.new(canvas.size) # resets buffer
- # gc.collect() ### not needed
- e32.ao_yield()
- res = appuifw.query(u"TIME'S UP! \nYou have shot " + unicode(goalsAchieved) + " goals in " +
- unicode(timePassed) + " seconds \n\n Play again?", "query")
- if(res != 1):
- gameRunning = 0
- print "ended"
- else:
- running = 1
- startTime = time.time()
- timePassed = 0
- timeLeft = timeLimit
- goalsAchieved = 0
- resetBall()
- sound_hit.close()
- sound_goal.close()
- sound_bounce.close()
- e32.ao_yield()
- appuifw.app.body = None
- accl.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement