Advertisement
xX-AAAAAAAAAA-Xx

ComputerCraft Pong Server

Aug 17th, 2024
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.97 KB | Software | 0 0
  1. local modem = peripheral.wrap("right")
  2. modem.open(6660)
  3.  
  4. -- Initialize game variables
  5. local BallX, BallY = 50, 20
  6. local BallVelX, BallVelY = 1, 1
  7. local P1Y, P2Y = 20, 20
  8. local P1Score, P2Score = 0, 0
  9. local P1Present, P2Present = false, false
  10.  
  11. while true do
  12.     -- Handle incoming messages
  13.     local event, side, senderId, message, distance = os.pullEvent("modem_message")
  14.    
  15.     if senderId == 1 then
  16.         local data = textutils.unserialize(message)
  17.         if data then
  18.             if data.action == "move" then
  19.                 if data.player == 1 then
  20.                     P1Y = data.y
  21.                     P1Present = true
  22.                 elseif data.player == 2 then
  23.                     P2Y = data.y
  24.                     P2Present = true
  25.                 end
  26.             end
  27.         end
  28.     end
  29.    
  30.     -- Update ball position
  31.     BallX = BallX + BallVelX
  32.     BallY = BallY + BallVelY
  33.    
  34.     -- Ball collision with paddles
  35.     if BallX == 1 and BallY >= P1Y and BallY <= P1Y + 5 then
  36.         BallVelX = -BallVelX
  37.     elseif BallX == 98 and BallY >= P2Y and BallY <= P2Y + 5 then
  38.         BallVelX = -BallVelX
  39.     end
  40.    
  41.     -- Ball collision with top/bottom
  42.     if BallY <= 1 or BallY >= 38 then
  43.         BallVelY = -BallVelY
  44.     end
  45.    
  46.     -- Ball out of bounds
  47.     if BallX <= 0 then
  48.         P2Score = P2Score + 1
  49.         BallX, BallY = 50, 20
  50.         BallVelX, BallVelY = 1, 1
  51.     elseif BallX >= 99 then
  52.         P1Score = P1Score + 1
  53.         BallX, BallY = 50, 20
  54.         BallVelX, BallVelY = -1, -1
  55.     end
  56.    
  57.     -- Broadcast game state
  58.     modem.transmit(1, "all", textutils.serialize({
  59.         ball = {x = BallX, y = BallY},
  60.         paddle1 = P1Y,
  61.         paddle2 = P2Y,
  62.         score1 = P1Score,
  63.         score2 = P2Score,
  64.         present1 = P1Present,
  65.         present2 = P2Present
  66.     }))
  67.    
  68.     -- Reset presence flags
  69.     P1Present, P2Present = false, false
  70.    
  71.     -- Sleep to control game speed
  72.     sleep(0.05)
  73. end
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement