Re: Pong en Lua
Posté: 08 Sep 2017, 21:06
ok, merci
News, programmes, tutoriaux, forum sur les calculatrices TI !
https://tiplanet.org/forum/
screen = platform.window
ww, wh = screen:width(), screen:height()
Pad = class()
function Pad:init(x,y) --rajouterai l pour la taille de la raquette plus tard
self.y = y
self.x = x
self.score = 0
--self.length = l
end
function Pad:move(dir)
if (dir > 0 and self.y < wh - 41) or (dir < 0 and self.y > 1) then
self.y = self.y + 2 * dir
end
end
function Pad:addPoint()
self.score = self.score + 1
end
function Pad:paint(gc)
gc:setColorRGB(255, 255, 255)
gc:fillRect(self.x, self.y, 6, 40)
end
Ball = class()
function Ball:init(x,y,dx,dy)
self.x = x
self.y = y
if dx == 1 then
dx = -2
end
if dy == 1 then
dy = -2
end --je n'ai pas trouve comment faire mieux
self.dx = dx
self.dy = dy
end
function Ball:move()
self.x = self.x + self.dx
self.y = self.y + self.dy
screen:invalidate()
end
function Ball:collision(pad1,pad2)
if self.x == 0 then
pad2:addPoint()
self:init(ww/2-2,wh/2-2,math.random(1,2),math.random(1,2))
elseif self.x == ww-5 then
pad1:addPoint()
self:init(ww/2-2,wh/2-2,math.random(1,2),math.random(1,2))
end
if (self.x == pad1.x+9 and self.y > pad1.y and self.y < pad1.y+35) or (self.x == pad2.x-5 and self.y > pad2.y and self.y < pad2.y+35) then
self.dx = -self.dx
end
if self.y == 0 or self.y == wh-5 then
self.dy = -self.dy
end
screen:invalidate()
end
function Ball:paint(gc)
gc:setColorRGB(255,255,255)
gc:fillArc(self.x,self.y,5,5,0,360)
end
player1 = Pad(5, wh / 2 - 20)
player2 = Pad(ww-13,wh/2-20)
ball = Ball(ww/2-2,wh/2-2,math.random(1,2),math.random(1,2))
timer.start(0.01)
function on.paint(gc)
gc:setColorRGB(0, 0, 0)
gc:fillRect(0, 0, ww, wh)
player1:paint(gc)
player2:paint(gc)
ball:paint(gc)
ball:collision(player1,player2)
gc:setFont("sansserif","b",24)
gc:setPen("thick","dashed")
gc:drawString(player1.score,ww/2-25,30)
gc:drawString(player2.score,ww/2+7,30)
gc:fillRect(ww/2-2,0,4,wh)
end
function on.arrowDown()
player1:move(2)
screen:invalidate()
end
function on.arrowUp()
player1:move(-2)
screen:invalidate()
end
function on.arrowLeft()
player2:move(-2)
screen:invlaidate()
end
function on.arrowRight()
player2:move(2)
screen:invalidate()
end
function on.timer()
ball:move()
screen:invalidate()
end
function Ball:collision(pad1,pad2)
if self.x <= 0 then
pad2:addPoint()
self:init(ww/2-2,wh/2-2,math.random(1,2),math.random(1,2))
elseif self.x >= ww-5 then
pad1:addPoint()
self:init(ww/2-2,wh/2-2,math.random(1,2),math.random(1,2))
end
if (self.x <= pad1.x+9 and self.y > pad1.y and self.y < pad1.y+35) or (self.x >= pad2.x-5 and self.y > pad2.y and self.y < pad2.y+35) then
self.dx = -self.dx
end
if self.y <= 0 or self.y >= wh-5 then
self.dy = -self.dy
end
screen:invalidate()
end