pong game - keeping score by tracking location of the ball.

hi guys

the ball actually can comes from the cpu player side - in this case the right side of the screen

I will post all my code later but it does not have the scoring logic that think it should have which is when the ball goes thru the right or left wall.

I orginally had  the score go up when the sides were hit and the top and bottom were not part of the collision so the ball would just fall thru the bottom of the screen.

I then thought all four walls should have collision detection but when I watched a pong game online collision was only detected on the top and bottom.

so I think once I remove the left and right walls from collisions detection the ball will pass thru them and therefore disappear each time either paddle misses the wall.   But the now I score the game has to change from the ball hitting either wall to passing thru the wall.

so this why I think if I can detect when a ball passes beyond  a certain axis point in either direction the score will be update

so I think my  if statement would read like this 

if mycircle.x =\> 600 --this part is not exactly correct just an idea then cpuscore= cpuscore + 1 if mycirle.x =\> -600 then player1score= player1score + 1 end 

this function will only be called at certain points of the game like when it starts or gets restarted when it ends. - I know the ball be created each time the function is called. This is what  I created it for. 

I have another function that currently ends the game I think when the game hits 5 or 10 pts for testing purposes.

I  will post my original code that has all 4 walls with collision detection later and play around with my idea but I wanted some feedback before I started to work on my code again for this game.

I am slowly getting there. Once I am done I think I will move on to another classic game. I hope to one day make really good games but I have to  learn bit by bit by working on a simpler game.

thanks in advance guys.

just curious what do games do most beginners start with when it comes to corona & lua?

i figured out I had to uses  sensors for scoring  but now when I click on the text link to restart the game multiple balls come out at once

see my code below

---ball now moves but multiple balls and wall collisions and scoring. ----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- ----pong game ----- -- Your code here local physics = require("physics") physics.start() -----load music -----local backgroundMusic = audio.loadStream("Stealth Music - Ninja.mp3") --------l------------------------------------------------------------------- --------------------------- scoring ---- Player 1 score player1score = 0 player1scoreTxt = display.newText( "Player 1 Score: 0", 0, 0, "Helvetica", 30 ) player1scoreTxt.x = display.contentCenterX player1scoreTxt.y = 10 ---CPU Score cpuscore=0 cpuscoreTxt = display.newText( "CPU Player Score: 0", 0, 0, "Helvetica", 30 ) cpuscoreTxt.x = display.contentCenterX cpuscoreTxt.y = 500 ------------------------------------------------ ------------layout of room ----left side of room local myleft = display.newLine( 10, -50, 10, 1000 ) ----physics.addBody( myleft, "static" ,{density = 0, friction = 0}) physics.addBody( myleft, "static", { isSensor=true }) myleft.isSensor = true ----rightside of room local myright = display.newLine( 310, 900, 310, -50 ) ---physics.addBody( myright, "static" ,{density = 0, friction = 0}) physics.addBody( myright, "static", { isSensor=true }) myright.isSensor = true --center of room local mycenter = display.newLine( 160, 550, 170, -50 ) ---bottom of room local mybottom =display.newLine( - 9899, 500, 495, 520 ) physics.addBody( mybottom, "static" ,{density = 0, friction = 0}) ---top of room local mytop =display.newLine( -925, -97, 555, -1 ) physics.addBody( mytop, "static" ,{density = 0, friction = 0}) ---------------------------------------------------------------------- local creategamescreen local startgame local moveball local ballcollison ------creates first screen a player sees function creategamescreen() startgametext = display.newText( "Tap here to start the game!", 150, 250, "Helvetica", 24 ) startgametext:setFillColor( 1, 0, 0 ) local function removetxt() display.remove(startgametext) startgame() end startgametext:addEventListener ( "tap", removetxt ) end creategamescreen() ----this starts the game function startgame(event) print("function startgame starts") player1score = 0 player1scoreTxt.text = "Player1 Score: " .. player1score print ("player 1 score is ",player1score) cpuscore = 0 cpuscoreTxt.text = "CPU Score: " .. cpuscore print ("cpu score is ",cpuscore) timer.performWithDelay ( 4000, moveball ) ------------------------------------------------------------------- end -- Create a rectangle player one myRect = display.newRect( 0, 0, 30, 100 ) myRect.x =40 myRect.y =125 --- paddle for computer player cpupaddle=display.newImage ("paddle1.png") cpupaddle.x =270 cpupaddle.y =325 ---makes ball bounce physics.addBody( cpupaddle, "static" ,{density = 1.0, friction = .3, bounce = 0}) physics.addBody( myRect, "static" ,{density = 1.0, friction = .3, bounce = 0}) ---------------move paddle player#1 local function ontouch (event) if event.phase == "ended" then ----moves it any where i click-- --- transition.to (myRect,{x=event.x, y=event.y}) ---just moves it up and down transition.to (myRect,{y=event.y}) end end Runtime:addEventListener("touch", ontouch) ----draw ball function moveball () myCircle = display.newCircle( 200, 200, 30 ) myCircle:setFillColor( 0.5 ) physics.addBody(myCircle,"dynamic",{density=0.1,bounce = .8, friction = 0}) myCircle.x =300 myCircle.y =125 ----this works to make the ball bounce off the paddle but ball moves at random for x & y ---myCircle:setLinearVelocity(math.random(-600,-300),math.random(-100,500)) myCircle:setLinearVelocity(math.random(-600,-300),math.random(-100,500)) ---this moves cpupaddle transition.to (cpupaddle,{x=cpupaddle.x, y=cpupaddle.y + math.random(-230,180)}) end function gameover() local gameovertext = display.newText( "Game Over! click here to restart", 150, 250, "Helvetica", 24 ) gameovertext:setFillColor( 1, 0, 0 ) local function removegameovertext(event) print ("game restarted") --gameovertext = nil display.remove(gameovertext) startgame() end gameovertext:addEventListener ( "tap",removegameovertext) end ---collsion notificatons when ball hits paddle and move paddle 2 function ballcollison( self, event) --if ( event.phase == "began" ) then -- print ("event began") --checks score if player1score \>5 then print ("player1 won gameover") gameover() elseif cpuscore \>5 then print ("test") print ("cpu won gameover") gameover() else print (" both scores are under 5 points serve the ball") timer.performWithDelay ( 4000, moveball ) end end local myCircle = display.newCircle( 200, 200, 30 ) myCircle:setFillColor( 0.5 ) myCircle.alpha =0 myRect.collision = ballcollison myRect:addEventListener("collision") --myCircle.collision = ballcollison --myCircle:addEventListener( "collision" ) ---leftwall collision ---collsion notificatons when ball hits left wall function leftwallcollison( self, event) ----added if ( event.phase == "began" ) then print ("event left wall began") elseif ( event.phase == "ended" ) then print ("ball hit left wall") print ("cpu scored") cpuscore = cpuscore + 1 cpuscoreTxt.text = "CPU Score: " .. cpuscore print ("cpu score is ",cpuscore) end end myleft.collision = leftwallcollison myleft:addEventListener( "collision" ) ---right collision ---collsion notificatons when ball hits right wall function rightwallcollison( self, event) ----added if ( event.phase == "began" ) then print ("event right wall began") elseif ( event.phase == "ended" ) then print ("ball hit right wall") print ("player1 scored") player1score = player1score + 1 player1scoreTxt.text = "Player1 Score: " .. player1score print ("player1 score is ",player1score ) end end myright.collision = rightwallcollison myright:addEventListener( "collision" ) --function bottomwallcollison( self, event) --local obj = event.target --myCircle = nil ---- --if ( event.phase == "began" ) then print ("event bottom wall began") -- elseif ( event.phase == "ended" ) then -- print ("removingball" ) --display.remove( myCircle ) -- end --end --mybottom.collision = bottomwallcollison --mybottom:addEventListener( "collision" )

can any one tell me why so many balls generated when i restart the game see code above

This is just me thinking out loud but in your game over function try adding

[lua]display.remove(myCircle)

myCircle = nil[/lua]

I know how to remove the balls. My issue now is that when I restart the game I get about 4 to 8 balls served at the same time.

see when I click on the text “game over click here to restart the game”. It runs my start game function and all these balls get served up.

But if I relauch the app from the simulator I don’t get the issue or if I click on the text that “starts the game”

I am wondering if the timer portion is the cause — timer.performWithDelay ( 4000, moveball )?

any thoughts

function gameover() local gameovertext = display.newText( "Game Over! click here to restart", 150, 250, "Helvetica", 24 ) gameovertext:setFillColor( 1, 0, 0 ) local function removegameovertext(event) print ("game restarted") --gameovertext = nil display.remove(gameovertext) startgame() end gameovertext:addEventListener ( "tap",removegameovertext)

can anyone help me ?

posting so much code will not help… we expect you to localise to the code that is causing the issue and then we will advise.

we are all busy and don’t want to spend ages trying to figure out your entire code base

sorry guys I thought the full code would help . Keep in mind I am not sure which is causing the issue of too many balls being served when the  text " game over click to restart the game" is click on.

I am examining the it now it may be the logic if statements here. 

--if ( event.phase == "began" ) then -- print ("event began") --checks score if player1score \>5 then print ("player1 won gameover") gameover() elseif cpuscore \>5 then print ("test") print ("cpu won gameover") gameover() else print (" both scores are under 5 points serve the ball") timer.performWithDelay ( 4000, moveball ) end end

thanks in advance for your help

how can I stop  timer.performWithDelay ( 4000, moveball )

ok it the move ball function that is the cause of multiple balls being created but only when I restart the game.

i move the display.new circle outside the function only one ball gets created like I want but in the begging the ball is show but then drops because of the physics start piece in the begining

so I then change the location of the ball so it is off the screen.

so is there a way to have the ball stay stil til the move function is called  

function moveball () physics.addBody(myCircle,"dynamic",{density=0.1,bounce = .8, friction = 0}) myCircle.x =300 myCircle.y =125 ----this works to make the ball bounce off the paddle but ball moves at random for x & y ---myCircle:setLinearVelocity(math.random(-600,-300),math.random(-100,500)) myCircle:setLinearVelocity(math.random(-600,-300),math.random(-100,500)) ---this moves cpupaddle transition.to (cpupaddle,{x=cpupaddle.x, y=cpupaddle.y + math.random(-230,180)}) end

You need to stop the timer function

Local timer= timer.performWithDelay ( 4000, moveball )

And then in gameover function:

Timer.cancel(timer)
Timer = nil

A few things that might help

  1. You should have a stopGame() function that you call when your game has ended which should drop your objects, timers and listeners and stop physics. 

  2. You should have a startGame() function the initialises your game state.  This should create your objects in default positions, create any timers and set/reset any counters (like store).  Now you can start physics again.

finally finish the game its not perfect but it works

----pong game

------testing version
– Your code here
-----local backgroundMusic = audio.loadStream(“Stealth Music - Ninja.mp3”)

local creategamescreen
local startgame
local gameover
pongpoint = audio.loadSound ( “pongscore.wav” )
serverball = audio.loadSound ( “pongserverball.wav” )

--------------------------- score board
---- Player 1 score

player1score = 0
 
player1scoreTxt = display.newText( “Player 1 Score: 0”, 0, 0, “Helvetica”, 30 )
    player1scoreTxt.x = display.contentCenterX
    player1scoreTxt.y = 10

—CPU Score

cpuscore=0

cpuscoreTxt = display.newText( “CPU Player Score: 0”, 0, 0, “Helvetica”, 30 )
    cpuscoreTxt.x = display.contentCenterX
    cpuscoreTxt.y = 500


------------layout of room
----left side of room
local myleft = display.newLine( 10, -50, 10, 1000 )

----rightside of room
 local myright = display.newLine( 310, 900, 310, -50 )

–center  of room
 local mycenter = display.newLine( 160, 550, 170, -50 )

—bottom of room
local mybottom =display.newLine( - 9899, 500, 495, 520 )

—top of room
–local mytop =display.newLine( -925, -97, 555, -1 )

local mytop =display.newLine( -925, -72, 555, -27 )


– Create a rectangle player one

myRect = display.newRect( 0, 0, 30, 100 )

myRect.x =40
myRect.y =125

— paddle for computer player

cpupaddle=display.newImage (“paddle1.png”)
cpupaddle.x =270
cpupaddle.y =325

------creates first screen a player sees

function creategamescreen()
 startgametext = display.newText( “Tap here to start the game!”, 150, 250, “Helvetica”, 24 )
 startgametext:setFillColor( 1, 0, 0 )

local function removetxt()
display.remove(startgametext)
startgame()
end
 startgametext:addEventListener ( “tap”, removetxt )
end
creategamescreen()

---------------move paddle player#1
local function ontouch (event)
  if event.phase == “ended” then
----moves it any where i click–
      — transition.to (myRect,{x=event.x, y=event.y})
—just moves it up and down
        transition.to (myRect,{y=event.y})
   end
end

Runtime:addEventListener(“touch”, ontouch)

----this starts the game
function startgame(event)

print(“function startgame starts”)

local physics = require(“physics”)
physics.start()

---------- add physics to layout of room
----left side of room

physics.addBody( myleft, “static”, { isSensor=true })
myleft.isSensor = true

----rightside of room

physics.addBody( myright, “static”, { isSensor=true })
myright.isSensor = true

—bottom of room
local mybottom =display.newLine( - 9899, 500, 495, 520 )
physics.addBody( mybottom, “static” ,{density = 0, friction = 0})   

—top of room
local mytop =display.newLine( -925, -97, 555, -1 )
physics.addBody( mytop, “static” ,{density = 0, friction = 0})   


—add physics to paddles

physics.addBody( cpupaddle, “static” ,{density = 1.0, friction = .3, bounce = 0})
physics.addBody( myRect, “static” ,{density = 1.0, friction = .3, bounce = 0})

-----------------------score

player1score = 0
player1scoreTxt.text = "Player1 Score: " … player1score
print ("player 1 score is ",player1score)

cpuscore = 0
cpuscoreTxt.text = "CPU Score: " … cpuscore
print ("cpu  score is ",cpuscore)
timer.performWithDelay ( 4000, moveball )
audio.play (serverball )

end

— ends the game

function gameover()

local physics = require(“physics”)
physics.stop()
 

local gameovertext = display.newText( “Game Over! click here to restart”, 150, 250, “Helvetica”, 24 )
gameovertext:setFillColor( 1, 0, 0 )

local function removegameovertext(event)
 print (“game restarted”)
–gameovertext = nil
 display.remove(gameovertext)
startgame()
end

gameovertext:addEventListener ( “tap”,removegameovertext)

end


function moveball ()

print (“server the ball”)

local physics = require(“physics”)
physics.start()
  myCircle = display.newCircle( 200, 200, 30 )
  myCircle:setFillColor( 0.5 )
 myCircle.x = display.contentCenterX
  myCircle.y = display.contentCenterY
physics.addBody(myCircle,“dynamic”,{density=0.1,bounce = .8, friction = 0})
----this works to make the ball bounce off the paddle but  ball moves at random for x & y
   
myCircle:setLinearVelocity(math.random(-600,-300),math.random(-100,500))

—this moves cpupaddle
–transition.to (cpupaddle,{x=cpupaddle.x, y=cpupaddle.y + math.random(-230,180)})
– transition.to (cpupaddle,{x=cpupaddle.x, y=cpupaddle.y + math.random(-100,100)})
 transition.to (cpupaddle,{x=cpupaddle.x, y=math.random(-200,100)})
 transition.to (cpupaddle,{x=cpupaddle.x, y=math.random(10,250)})
end

------comment out for backup
—leftwall collision
—collsion notificatons when ball hits left wall
function leftwallcollison( self, event)

  if ( event.phase == “began” ) then
    print (“event left wall  began”)
  elseif ( event.phase == “ended” ) and cpuscore <11 then
        print (“ball hit left wall”)
print (“cpu scored”)
cpuscore = cpuscore + 1
audio.play (pongpoint)
cpuscoreTxt.text = "CPU Score: " … cpuscore
print ("cpu  score is ",cpuscore)
timer.performWithDelay ( 4000, moveball )
audio.play (serverball)
elseif  cpuscore >10 then
print (“gameover CPU won game”)
gameover()
end
   end

myleft.collision = leftwallcollison
myleft:addEventListener( “collision” )

function rightwallcollison( self, event)
----added
  if ( event.phase == “began” ) then
       print (“event right wall  began”)
    elseif ( event.phase == “ended” )  and player1score <11 then
      print (“ball hit right wall”)
       print (“player1 scored”)
player1score = player1score + 1
audio.play (pongpoint)
player1scoreTxt.text = "Player1 Score: " … player1score
print ("player1 score  is ",player1score )
timer.performWithDelay ( 4000, moveball )
audio.play (serverball)
elseif player1score >10 then

print(“gameover player1 won game”)
gameover()
         end
end
myright.collision = rightwallcollison
myright:addEventListener( “collision” )