Advertisement
here2share

### Soccer_Halftable_Revised.py

Jan 5th, 2015
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Soccer_Halftable_Revised.py
  2.  
  3. ### entire zip file can be found at this link http://www.datafilehost.com/d/e251cd13
  4.  
  5. # The ORIGINAL version of this game was developed for the course
  6. # "interaction technologies" of the master course "mobile computing"
  7. # at the University of Applied Sciences Hagenberg by Benjamin Gmeiner
  8. # and Yen-Chia Lin
  9. #
  10. # Special thanks to Christopher Schmidt (http://crschmidt.net/), who's
  11. # open source project "Accelball" made it a lot easier and faster to
  12. # access the Accelerometer data
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. #   http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. #
  26. # Copyright (c) 2008 Gmeiner Benjamin, benjamin.gmeiner@fh-hagenberg.at
  27. #                   Yen-Chia Lin,   yen-chia.lin@fh-hagenberg.at
  28. #
  29.  
  30. from graphics import *
  31. from sensor import *
  32. import e32, audio, appuifw, os, sys, key_codes, time, math, random, graphics, sensor, string
  33. import sysinfo, gc, copy
  34.  
  35. CUR_AUTHOR = 1 # 0 for debugging
  36. PLAY_SOUNDS = 1 # 0 for skipping sounds
  37. DRAW_DEBUG = 0
  38. DRAW_FPS = False
  39.  
  40. boundary_width = 492
  41. max_x = 500 ### <<< ref
  42. max_y = 360 ### <<< ref
  43. canvasImage = None
  44.  
  45. class GameObject(object):
  46.     x = 0
  47.     y = 0
  48.     width = 0
  49.     height = 0
  50.     imgX = 0 # draw image delta
  51.     imgY = 0 # draw image delta
  52.    
  53.     def getPoint(self):
  54.         return [self.x, self.y]
  55.     def getMaxX(self):
  56.         return self.x + self.width + self.imgX
  57.     def getMaxY(self):
  58.         return self.y + self.height + self.imgY
  59.     def getInX(self): ### leftmost contact perimeter
  60.         return self.x + self.imgX
  61.     def getInY(self): ### top contact perimeter
  62.         return self.y + self.imgY
  63.     def drawBoundingBox(self, image):
  64.         image.rectangle((self.getInX(), self.getInY(), self.getMaxX(), self.getMaxY()),outline = COLOR_BLUE)
  65.        
  66. class SensorConnection():
  67.     xAxis = 0
  68.     yAxis = 0
  69.     def __init__(self):
  70.         """Connect to the sensor."""
  71.         self.accelerometer = AccelerometerXYZAxisData(data_filter=LowPassFilter())
  72.         self.accelerometer.set_callback(data_callback=self.sense_conn)
  73.  
  74.     def sense_conn(self):
  75.         self.xAxis = self.accelerometer.x*-1 ### <<<
  76.         self.yAxis = self.accelerometer.y*-1 ### <<<
  77.  
  78.     def run(self):
  79.         self.accelerometer.start_listening()
  80.  
  81.     def cleanup(self):
  82.         """Cleanup after yourself. *Must be called* before exiting."""
  83.         self.accelerometer.stop_listening() ### <<<
  84.  
  85. def handle_redraw(rect):
  86.     if canvasImage: ### Skips only at first pass as "None"
  87.         canvas.blit(canvasImage)
  88.  
  89. def quit():
  90.     global running
  91.     running=0
  92.  
  93. def exitLoading(reason):
  94.     appuifw.note(reason, "error")
  95.     os._exit(reason)
  96.  
  97. #===============================================================================
  98. # Sound Methods
  99. #===============================================================================
  100.  
  101. def playSoundShoot():
  102.     global sound_hit, PLAY_SOUNDS
  103.     if(PLAY_SOUNDS == 1):
  104.         if sound_hit.state() != audio.EPlaying:
  105.             sound_hit.play()
  106.  
  107. #===============================================================================
  108. # Key Toggle Methods
  109. #===============================================================================
  110.  
  111. def toggle_PlaySounds():
  112.     global PLAY_SOUNDS
  113.    
  114.     if PLAY_SOUNDS == 1:
  115.         PLAY_SOUNDS = 0
  116.     else:
  117.         PLAY_SOUNDS = 1
  118. '''
  119. def toggle_CurrentAuthor():
  120.     global CUR_AUTHOR
  121.    
  122.     CUR_AUTHOR += 1
  123.     CUR_AUTHOR = CUR_AUTHOR % 3
  124.  
  125. def toggle_DrawDebug():
  126.     global DRAW_DEBUG  
  127.    
  128.     if DRAW_DEBUG == 1:
  129.         DRAW_DEBUG = 0
  130.     else:
  131.         DRAW_DEBUG = 1
  132.        
  133. def toggle_DrawFPS():
  134.     global DRAW_FPS
  135.    
  136.     DRAW_FPS = not DRAW_FPS
  137. '''
  138.  
  139. #===============================================================================
  140. # Image Processing
  141. #===============================================================================   
  142. def automask(im):
  143.     width, height = im.size
  144.     mask = Image.new(im.size, '1') # black and white
  145.     tran = im.getpixel((0,0))[0] # transparent top-left
  146.     for y in range(height):
  147.         line = im.getpixel([(x, y) for x in range(width)])
  148.         for x in range(width):
  149.             if line[x] == tran:
  150.                 mask.point((x,y), 0) # mask on the point
  151.     return mask
  152.  
  153. #Converts the specified "area" of the image into an image mask
  154. #Transparent color is the color found in the upper left pixel
  155. def automaskArea(im, area):
  156.     width = area[2] - area[0]
  157.     height = area[3] - area[1]
  158.     startX = area[0]
  159.     startY = area[1]
  160.  
  161.     mask = Image.new((width, height), '1') # black and white
  162.     tran = im.getpixel((startX,startY))[0] # transparent top-left
  163.        
  164.     for y in range(height):
  165.         for x in range(width):
  166.             if im.getpixel((startX + x, startY + y))[0] == tran:
  167.                 mask.point((x,y),0)
  168.     return mask
  169.  
  170. def statusupdate(im, status, progress):
  171.     global loadingStatusLine
  172.     im.text((10,20), u"Initialising..." + progress, fill = COLOR_BLACK)
  173.     im.text((10,50 + loadingStatusLine * 20), u"> " + status, fill=COLOR_BLACK)
  174.     loadingStatusLine += 1
  175.     handle_redraw(())
  176.  
  177. #===============================================================================
  178. # Collistion Detection Methods
  179. #===============================================================================
  180. def checkWallBoundary():
  181.     """Returns true, if ball collides with the wall behind the goalie"""
  182.     global m_ball, m_goalObject, boundary_width
  183.     return m_ball.y <= 14 and (
  184.                         (m_ball.x >= 0 and m_ball.x + m_ball.width < m_goalObject.x) or
  185.                         (m_ball.x > m_goalObject.getMaxX() and m_ball.x <= boundary_width))
  186.  
  187. def checkSideBoundary():
  188.     """Returns true, if ball colides with Side Boundary"""
  189.     global m_ball
  190.     if m_ball.x < 0:
  191.         m_ball.x = 0
  192.         return True
  193.     elif m_ball.getMaxX() > boundary_width:
  194.         m_ball.x = boundary_width - m_ball.width
  195.         return True
  196.     return False
  197.  
  198. def checkBackWallBoundary():
  199.     """Returns true, if ball collides with Boundary"""
  200.     global m_ball
  201.     if m_ball.y > max_y - m_ball.height:
  202.         m_ball.y = max_y - m_ball.height
  203.         return True
  204.     return False
  205.  
  206. ### checks collision detection
  207. def checkCollision(objA, objB): ### +++
  208.     return ((objA.getInX() < objB.getMaxX()) and (objB.getInX() < objA.getMaxX()) and
  209.             (objA.getInY() < objB.getMaxY()) and (objB.getInY() < objA.getMaxY()))
  210.  
  211.  
  212. #===============================================================================
  213. # Helper Methods
  214. #===============================================================================
  215. def doGoalAchieved():
  216.     global goalsAchieved, statusImage, timeLeft
  217.     goalsAchieved += 1
  218.     statusImage = createStatusBox(goalsAchieved, timeLeft)
  219.     playSoundShoot()
  220.     resetBall()
  221.    
  222. def resetBall(): ### +++ ball
  223.     global m_ball, ballSpeed, ball_reset
  224.     m_ball.x, m_ball.y = [random.randrange(30, 420), 270]
  225.     ballSpeed = [10,-0.05] ### >>> ball_reset
  226.  
  227. def isSameDirection(v1, v2): ### +++ v1=v2
  228.     return (v1 < 0 and v2 < 0 and v2 < v1) or (v1 > 0 and v2 > 0 and v2 > v1)
  229.    
  230. def updateFPS():
  231.     global prevTime, totalTime, fpsResult, fpsCounter
  232.  
  233.     curTime = time.time()
  234.     frameTime = curTime - prevTime
  235.     prevTime = curTime
  236.     totalTime += frameTime
  237.  
  238.     if totalTime >= 1:
  239.         fpsResult = fpsCounter + 1
  240.         fpsCounter = 0
  241.         totalTime = 0
  242.  
  243.     fpsCounter += 1
  244.  
  245. def createStatusBox(count, timeleft):
  246.     statImg = Image.new((182, 60),'RGB16') ### <<<
  247.     statImg.clear(COLOR_ORANGE)
  248.     statImg.rectangle((0, 0, 182, 60), width = 4, outline = COLOR_BLACK) ### <<<
  249.     statImg.text((10,25), u"Goals: " + unicode(count),font='dense', fill = COLOR_BLACK) ### <<<
  250.     # countdown
  251.     statImg.text((10,48), u"Time Left: " + unicode(timeleft)+ " s", font ='dense', fill = COLOR_BLACK) ### <<<
  252.  
  253.     return statImg ### >>> statImg.transpose(ROTATE_90)
  254.  
  255. def calibrateNeutralValue():
  256.     global accl, neutralValue
  257.     neutralValue = accl.yAxis
  258.    
  259. #===============================================================================
  260. # color definintions
  261. #===============================================================================
  262. COLOR_BLACK = 0x000000
  263. COLOR_WHITE = 0xffffff
  264. COLOR_GRAYLIGHT = 0xeeeeee
  265. COLOR_GRAYDARK = 0x666666
  266. COLOR_BLUE = 0x0000ff
  267. COLOR_GREEN = 0x00ff00
  268. COLOR_RED = 0xff0000
  269. COLOR_ORANGE = 0xffcc00
  270.  
  271. #===============================================================================
  272. # BEGIN Main() more or less ...
  273. #===============================================================================
  274. m_goalie = GameObject()
  275. m_attackPlayer1 = GameObject()
  276. m_attackPlayer2 = GameObject()
  277. m_goalObject = GameObject()
  278. appuifw.app.orientation='landscape'
  279. appuifw.app.screen = 'large'
  280. appuifw.app.directional_pad = False
  281. loadingStatusLine = 1
  282. canvas = appuifw.Canvas(redraw_callback = handle_redraw)
  283. appuifw.app.body = canvas
  284. buf = Image.new(canvas.size)
  285. canvasImage = Image.new(canvas.size)
  286.  
  287. #===============================================================================
  288. # key bindings
  289. #===============================================================================
  290. '''
  291. canvas.bind(key_codes.EKeyStar, toggle_PlaySounds)
  292. canvas.bind(key_codes.EKeyHash, toggle_CurrentAuthor)
  293. canvas.bind(key_codes.EKeySelect, playSoundShoot)
  294. canvas.bind(key_codes.EKey0, toggle_DrawDebug)
  295. canvas.bind(key_codes.EKey5, resetBallKeyBinding)
  296. canvas.bind(key_codes.EKey2, calibrateNeutralValue)
  297. canvas.bind(key_codes.EKey3, toggle_DrawFPS)
  298. '''
  299.  
  300. appuifw.app.exit_key_handler=quit
  301.  
  302. #===============================================================================
  303. # PROPERTIES
  304. #===============================================================================
  305. running = 1
  306. accl = SensorConnection()
  307. accl.run() ### <<<
  308.  
  309. #determine python root (where is our script installed)
  310. #this has to be c:\\python or e:\\python
  311. PYTHON_ROOT = u"E:\\Python\\pyWuzzler\\"
  312. '''
  313. if(os.path.exists("C:\\private\\a000902D\\default.py")):
  314.     PYTHON_ROOT = u"C:\\private\\a000902D\\pyWuzzler\\"
  315. elif(os.path.exists("E:\\private\\a000902D\\default.py")):
  316.     PYTHON_ROOT = u"E:\\private\\a000902D\\pyWuzzler\\"
  317. elif(os.path.exists("C:\\data\\Python\\pyWuzzler.py")):
  318.     PYTHON_ROOT = u"C:\\data\\Python\\pyWuzzler\\"
  319. elif(os.path.exists("E:\\data\\Python\\pyWuzzler.py")):
  320.     PYTHON_ROOT = u"E:\\data\\Python\\pyWuzzler\\"
  321. else:
  322.     exitLoading(u"couldn't determine python source directory")
  323. '''
  324.  
  325. # draw init Background and start initialisation
  326. if(os.path.exists(PYTHON_ROOT + u"initBackground.png")):
  327.     initBackroundImage=Image.open(PYTHON_ROOT + u"initBackground.png")
  328. else:
  329.     exitLoading(PYTHON_ROOT + u"initBackground.png missing!");
  330. canvasImage.blit(initBackroundImage, target=(0, 0))
  331. statusupdate(canvasImage, "starting initialisation", "...")
  332. statusupdate(canvasImage, "initialising basic properties", "...")
  333.  
  334. ################################################################################
  335. ##### +++++ Main Setting and Directory #########################################
  336. ################################################################################
  337.  
  338. acceleration = 0.5 ### +++ player y acceleration
  339.  
  340. neutralValue = 42 # value that specifies at which angle the player is in a neutral position -> can be used for calibration
  341. noOfAnimations = 37 # number of animations
  342. frontArea = [0, 1, 2, 3, 4, 5] # define front areas
  343. 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
  344. backArea = [31, 32, 33, 34, 35, 36, 37] # define the states that is when the player is in back position
  345. lastState = 0 # last player state
  346. player_speed = [0,0]
  347. goalsAchieved = 0
  348.  
  349. #===============================================================================
  350. # properties of ball
  351. #===============================================================================
  352. m_ball = GameObject()
  353. ball_reset = [10,-0.05] ### <<<
  354. ballSpeed = ball_reset
  355. BALL_MAX_SPEED = 16
  356. ballFriction = 0.995
  357. x_gravity = 0.2
  358. y_gravity = 0.025
  359. ballShootAngle = 60 ### ZZZ from middle to right or left most angle (in grad)
  360. shootForce = 0
  361.  
  362. #===============================================================================
  363. # Variables for FPS
  364. #===============================================================================
  365. startTime = time.time()
  366. prevTime = startTime
  367. totalTime = 0
  368. fpsCounter = 0
  369. fpsResult = 0
  370. timePassed = 0
  371. timeLimit = 180
  372. timeLeft = timeLimit
  373.  
  374. #===============================================================================
  375. # LOAD SOUNDS
  376. #===============================================================================
  377.  
  378. if(os.path.exists(PYTHON_ROOT + u"hit.wav") and
  379.     os.path.exists(PYTHON_ROOT + u"hit.wav") and
  380.     os.path.exists(PYTHON_ROOT + u"hit.wav")):
  381.     statusupdate(canvasImage, "loading sounds","...")
  382.     sound_hit = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
  383.     sound_goal = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
  384.     sound_bounce = audio.Sound.open(PYTHON_ROOT + u"hit.wav")
  385. else:
  386.     exitLoading(u"some audio files are missing");
  387.  
  388. #===============================================================================
  389. # PRE-RENDERING AND IMAGE LOADING
  390. #===============================================================================
  391.  
  392. statusupdate(canvasImage, "loading player models, will take ","...")
  393. statusupdate(canvasImage, "a while on first run","...")
  394. attackstate = 0 #ranges from -2 (most left) to 2 (most right)
  395. if(os.path.exists(PYTHON_ROOT + u"playerSprites.png")):
  396.     playerImage=Image.open(PYTHON_ROOT + u"playerSprites.png")
  397. else:
  398.     exitLoading(u"player sprites-file is missing");
  399.  
  400. #create image mask if it doesn't exist yet, otherwise load from fs
  401. playerImageMasks = []
  402.  
  403. for val in range(noOfAnimations):
  404.     fName = PYTHON_ROOT + u"playerMask_" + unicode(val) + ".png"
  405.     if(os.path.exists(fName)):
  406.         maskImg = Image.new(size=(34,100), mode='1')
  407.         maskImg.load(fName)
  408.         playerImageMasks.append(maskImg)
  409.     else:
  410.         playerImageMasks.append(automaskArea(playerImage, (0,val*34, 100, (val+1)*34)))
  411.         playerImageMasks[val].save(fName, format='PNG', compression='no', quality=1, bpp=1)
  412.  
  413. #defender
  414. imgName = PYTHON_ROOT + u"defenderSprites.png"
  415. maskName = PYTHON_ROOT + u"defenderSprites_mask.png"
  416. if(os.path.exists(imgName)):
  417.     defenderImage = Image.open(imgName)
  418. else:
  419.     exitLoading(u"goalie sprites-file is missing");
  420.  
  421. if(os.path.exists(maskName)):
  422.     defenderImageMask = Image.new(defenderImage.size, mode='1') #todo: get variable size!!!
  423.     defenderImageMask.load(maskName)
  424. else:
  425.     defenderImageMask = automask(defenderImage);
  426.     defenderImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
  427.  
  428. #statusupdate(img, "creating player model mask","...")
  429. statusupdate(canvasImage, "loading ball sprites and creating mask", "...")
  430. imgName = PYTHON_ROOT + u"sprites_ballV2.png"
  431. maskName = PYTHON_ROOT + u"sprites_ballV2_mask.png"
  432. if(os.path.exists(imgName)):
  433.     ballImage = Image.open(imgName)
  434. else:
  435.     exitLoading(u"ball sprites-file is missing");
  436.  
  437. if(os.path.exists(maskName)):
  438.     ballImageMask = Image.new(ballImage.size, mode='1')#todo: get variable size!!!
  439.     ballImageMask.load(maskName)
  440. else:
  441.     ballImageMask = automask(ballImage);
  442.     ballImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
  443.  
  444. statusupdate(canvasImage, "loading pole sprites and creating mask", "...")
  445. imgName = PYTHON_ROOT + u"pole.png"
  446. maskName = PYTHON_ROOT + u"pole_mask.png"
  447. if(os.path.exists(imgName)):
  448.     poleImage = Image.open(imgName)
  449. else:
  450.     exitLoading(u"pole sprites-file is missing");
  451.  
  452. if(os.path.exists(maskName)):
  453.     poleImageMask = Image.new(poleImage.size, mode='1')#todo: get variable size!!!
  454.     poleImageMask.load(maskName)
  455. else:
  456.     poleImageMask = automask(poleImage);
  457.     poleImageMask.save(maskName, format='PNG', compression='no', quality=1, bpp=1)
  458.  
  459. statusupdate(canvasImage, "loading background", "...")
  460.  
  461. if(os.path.exists(PYTHON_ROOT + u"background.png")):
  462.     bgImage = Image.open(PYTHON_ROOT + u"background.png")
  463. else:
  464.     exitLoading(u"background file is missing");
  465.  
  466. #properties of attacking player
  467. statusupdate(canvasImage, "initialising some properties, we're almost done ;)", "...")
  468.  
  469. #===============================================================================
  470. # init GameObjects +++++
  471. #===============================================================================
  472.  
  473. prev_locf = 0
  474. prev_locb = 0
  475. dist_players = 180 # x distance point of players
  476. playerHeight = 14
  477.  
  478. m_attackPlayer1.width = m_attackPlayer2.width = 16
  479. m_attackPlayer1.height = m_attackPlayer2.height = playerHeight
  480. m_attackPlayer1.x = 132 ### player max left = 10 : max right = 261
  481. m_attackPlayer1.y = m_attackPlayer2.y = 200
  482. m_attackPlayer1.imgX = m_attackPlayer2.imgX = 9
  483. m_attackPlayer1.imgY = m_attackPlayer2.imgY = 14 ### swing contact bearing 14=axis-38 : 70=axis-28 // 70-14=56 divided by 10 = 5.6
  484. m_attackPlayer2.x = m_attackPlayer1.x + dist_players ### player max right = 459
  485.  
  486. m_ball.x, m_ball.y = [random.randrange(25, 250), 320]
  487. m_ball.width = ballImage.size[1]
  488. m_ball.height = ballImage.size[0]
  489.  
  490. m_goalie.x = 240 ### centre of the goal
  491. m_goalie.y = 24 ### dist in front of the goal
  492. m_goalie.width = 16
  493. m_goalie.height = 14
  494. m_goalie.imgX = 8
  495. m_goalie.imgY = 16
  496.  
  497. m_goalObject.x = 164
  498. m_goalObject.y = 0
  499. m_goalObject.width = 136
  500. m_goalObject.height = 12
  501.  
  502. #properties of defending player
  503. speedAttackPlayer = [0,0]
  504. defSpeed = 0
  505. #properties of the goal
  506. leftGoalMargin = 164
  507. rightGoalMargin = 284
  508.  
  509. gameRunning = 0
  510. prev_force = 0
  511. res = appuifw.query(u"Start by pressing OK", "query")
  512. if(res == 1): gameRunning = 1
  513. startTime = time.time()
  514. framedelay = 0
  515.  
  516. while(gameRunning):
  517.     statusImage = createStatusBox(goalsAchieved,timeLeft)
  518.     while running:
  519.         if(time.time() - startTime - timePassed > 1): # over one second passed
  520.             timePassed = timePassed + 1
  521.             timeLeft = timeLimit - timePassed
  522.             statusImage = createStatusBox(goalsAchieved, timeLeft)
  523.             if timeLeft % 25 == 0:
  524.                 e32.reset_inactivity()
  525.             if(timeLeft <= 0):
  526.                 running = 0
  527.  
  528.         indexRaw = accl.xAxis # kick value
  529.         force_index = int(indexRaw*2.5) + neutralValue
  530.  
  531.         # calculate current player state
  532.         if (force_index < 0):
  533.             force_index = 0
  534.         elif (force_index > noOfAnimations-1):
  535.             force_index = noOfAnimations-1
  536.  
  537.         src = ((force_index * 34, 0),((force_index+1)*34, 100))
  538.  
  539.         #draw Background
  540.         buf.rectangle((504,0,640,360),fill=(COLOR_BLACK))
  541.         buf.blit(bgImage, target=(0,0))
  542.  
  543.         #draw status window
  544.         buf.blit(statusImage, target=(0,buf.size[1] - statusImage.size[1]))
  545.  
  546.         #draw ball
  547.         buf.blit(ballImage, target=m_ball.getPoint(), mask=ballImageMask, scale=0)
  548.  
  549.         #draw poles
  550.         buf.blit(poleImage, target=(0,0), mask=poleImageMask)
  551.         buf.blit(poleImage, target=(0,200), mask=poleImageMask)
  552.  
  553.         #Draw goalie (defending player)
  554.         buf.blit(defenderImage, target=m_goalie.getPoint(), mask=defenderImageMask)
  555.  
  556.         #Draw first attacking player
  557.         buf.blit(playerImage, target=m_attackPlayer1.getPoint(), source=src, mask=playerImageMasks[force_index], scale=0)
  558.         #Draw second attacking player
  559.         buf.blit(playerImage, target=m_attackPlayer2.getPoint(), source=src, mask=playerImageMasks[force_index], scale=0)
  560.  
  561.         if(CUR_AUTHOR == 0):
  562.             buf.text((10,20), u"xAxis: " + unicode(accl.xAxis), fill = COLOR_BLACK)
  563.             buf.text((100,20), u"Index: " + unicode(force_index), fill = COLOR_BLACK)
  564.             buf.text((10,40), u"Ball x: " + unicode(m_ball.x), fill= COLOR_BLACK)
  565.             buf.text((10,60), u"Ball y: " + unicode(m_ball.y), fill= COLOR_BLACK)
  566.             buf.text((10,80), u"Ball vx: " + unicode(ballSpeed[0]), fill= COLOR_BLACK)
  567.             buf.text((10,100), u"Ball vy: " + unicode(ballSpeed[1]), fill= COLOR_BLACK)
  568.  
  569.         # Draw Boundingboxes
  570.         if DRAW_DEBUG:
  571.             m_ball.drawBoundingBox(buf)
  572.             m_attackPlayer1.drawBoundingBox(buf)
  573.             m_attackPlayer2.drawBoundingBox(buf)
  574.             m_goalie.drawBoundingBox(buf)
  575.             m_goalObject.drawBoundingBox(buf)
  576.  
  577.         # updating FPS
  578.         ### >>> updateFPS()
  579.         ### >>> if(DRAW_FPS or CUR_AUTHOR == 1): buf.text((200, 10), u"FPS: " + unicode(fpsResult), fill = COLOR_BLACK)
  580.  
  581.         # calculate position of goalie
  582.         if(m_goalie.x < m_ball.x):
  583.             if(m_goalie.x >= rightGoalMargin + 10 or m_ball.x - m_goalie.x < 10):
  584.                 defSpeed = 0 #if the def player is at the Margin of the goal, stop moving
  585.             else:
  586.                 defSpeed = 2
  587.         if(m_goalie.x > m_ball.x):
  588.             if(m_goalie.x < leftGoalMargin - 20 or m_goalie.x - m_ball.x < 10):
  589.                 defSpeed = 0 #if the def player is at the Margin of the goal, stop moving
  590.             else:
  591.                 defSpeed = -2
  592.  
  593.         m_goalie.x += defSpeed
  594.  
  595.         # calculate speed and position of player
  596.         PlayerSpeed = accl.yAxis * 0.2 ### MAX: accl.yAxis = 48
  597.  
  598.         m_attackPlayer1.x -= PlayerSpeed
  599.         m_attackPlayer2.x -= PlayerSpeed
  600.         if m_attackPlayer1.x < 10:
  601.             m_attackPlayer1.x = 10
  602.             m_attackPlayer2.x = 10 + dist_players
  603.         if m_attackPlayer1.x >= 268:
  604.             m_attackPlayer1.x = 268
  605.             m_attackPlayer2.x = 268 + dist_players
  606.  
  607.         #===============================================================================
  608.         #   check for shoot
  609.         #===============================================================================
  610.        
  611.         ##### +++++ getting a "kick" out of this game
  612.         shootForce = (prev_force - force_index) * 1.25
  613.         if shootForce == 0: shootForce = 1
  614.         if shootForce > prev_force and shootForce > 7:
  615.             shootForce = BALL_MAX_SPEED
  616.             prev_locf = 10
  617.         elif shootForce < prev_force and shootForce < -7:
  618.             shootForce = -9 ### -BALL_MAX_SPEED
  619.             prev_locb = -10
  620.         else:
  621.             prev_locf, prev_locb = 0,0
  622.         prev_force = force_index
  623.  
  624.         m_attackPlayer1.height = playerHeight + prev_locf
  625.         m_attackPlayer2.height = playerHeight + prev_locf
  626.         m_attackPlayer1.imgY = 14 + ((force_index - 8) *2.725) + prev_locb
  627.         m_attackPlayer2.imgY = 14 + ((force_index - 8) *2.725) + prev_locb
  628.         boundaryBounce = False
  629.  
  630.         #===============================================================================
  631.         #   Ball Physics
  632.         #===============================================================================
  633.         if m_ball.y < 60:
  634.             #===============================================================================
  635.             # check GOAL
  636.             #===============================================================================
  637.             if checkCollision(m_ball, m_goalObject):
  638.                 doGoalAchieved()
  639.            
  640.             if checkWallBoundary():
  641.                 m_ball.y = 14
  642.                 ballSpeed[1] *= -1
  643.  
  644.             #===============================================================================
  645.             # check ball collision with goalie
  646.             #===============================================================================
  647.             if checkCollision(m_goalie, m_ball): ### ??? should add def swing ani
  648.                 ballSpeed[1] = 4
  649.                 playSoundShoot()
  650.  
  651.         #===============================================================================
  652.         # detect SHOOT!!!
  653.         #===============================================================================
  654.         if force_index in neutralArea:
  655.             player1Shoot = checkCollision(m_attackPlayer1, m_ball)
  656.             player2Shoot = checkCollision(m_attackPlayer2, m_ball)
  657.             if player1Shoot or player2Shoot:
  658.                 if shootForce < -7: #abs(shootForce) > 7:
  659.                     playSoundShoot()
  660.                     shootForce -= 5
  661.                 # collision with player
  662.                 ballCenter = m_ball.x + m_ball.width / 2
  663.                 playerX = 0 ### represents either m_attackPlayer1 or m_attackPlayer2
  664.                 if player1Shoot:
  665.                     playerX = m_attackPlayer1.getMaxX()
  666.                 else:
  667.                     playerX = m_attackPlayer2.getMaxX()
  668.                 playerHalfWidth = m_attackPlayer1.width / 2
  669.                    
  670.                 _res = playerX - ballCenter - playerHalfWidth
  671.                 vx = ((shootForce/3)/playerHalfWidth) * _res
  672.  
  673.                 if _res < 0:                   
  674.                     # ballcenter is left of player
  675.                     ballSpeed = [-vx, shootForce*-1]
  676.  
  677.                 else:
  678.                     # ballcenter is right of player
  679.                     ballSpeed = [vx, shootForce*-1]
  680.  
  681.                 boundaryBounce = checkSideBoundary()
  682.                 #print ballSpeed
  683.  
  684.                 m_attackPlayer1.x = m_attackPlayer2.x - dist_players
  685.  
  686.         else: ### ^^^ index outside of neutralArea -- hides passing contact areas
  687.             m_attackPlayer1.height = -1
  688.             m_attackPlayer2.height = -1
  689.  
  690.  
  691.         #===============================================================================   
  692.         # boundary check
  693.         #===============================================================================
  694.         if checkSideBoundary():
  695.             ballSpeed[0] *= -1
  696.         if checkBackWallBoundary():
  697.             ballSpeed[1] = (ballSpeed[1]/1.25) * -1
  698.  
  699.         # apply new ball speed
  700.         ballSpeed[1] *= ballFriction
  701.         ballSpeed[0] *= ballFriction
  702.         m_ball.x += ballSpeed[0]
  703.         m_ball.y += ballSpeed[1]
  704.  
  705.         # limit the speed of the ball
  706.         if ballSpeed[0] > BALL_MAX_SPEED:
  707.             ballSpeed[0] = BALL_MAX_SPEED
  708.         elif ballSpeed[0] < -BALL_MAX_SPEED:
  709.             ballSpeed[0] = -BALL_MAX_SPEED
  710.         if ballSpeed[1] > BALL_MAX_SPEED:
  711.             ballSpeed[1] = BALL_MAX_SPEED
  712.         elif ballSpeed[1] < -BALL_MAX_SPEED:
  713.             ballSpeed[1] = -BALL_MAX_SPEED
  714.        
  715.         # to gravitate toward player zone      
  716.         if m_ball.x < 12:
  717.             ballSpeed[0] += x_gravity
  718.         elif m_ball.x > 450:
  719.             ballSpeed[0] -= x_gravity ###
  720.         if m_ball.y < 200:
  721.             if m_ball.y < 120 and (m_ball.x + m_ball.width < m_goalObject.x - 20) or (m_ball.x > m_goalObject.getMaxX() + 20):
  722.                 ballSpeed[1] += y_gravity + 0.1
  723.             else:
  724.                 ballSpeed[1] += y_gravity
  725.         elif m_ball.y > 254:
  726.             ballSpeed[1] -= y_gravity  
  727.  
  728.         #===============================================================================
  729.         #   Ball Physics end
  730.         #===============================================================================
  731.        
  732.         canvasImage=copy.copy(buf)
  733.         handle_redraw(())
  734.         buf = Image.new(canvas.size) # resets buffer
  735.         # gc.collect() ### not needed
  736.         e32.ao_yield()
  737.  
  738.     res = appuifw.query(u"TIME'S UP! \nYou have shot " + unicode(goalsAchieved) + " goals in " +
  739.                 unicode(timePassed) + " seconds \n\n Play again?", "query")
  740.  
  741.     if(res != 1):
  742.         gameRunning = 0
  743.         print "ended"
  744.        
  745.     else:
  746.         running = 1
  747.         startTime = time.time()
  748.         timePassed = 0
  749.         timeLeft = timeLimit
  750.         goalsAchieved = 0
  751.         resetBall()
  752.  
  753. sound_hit.close()
  754. sound_goal.close()
  755. sound_bounce.close()
  756. e32.ao_yield()
  757. appuifw.app.body = None
  758. accl.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement