A pong clone, but with a twist!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. local running = true
  2. local socket = require 'socket'
  3. local udp = socket.udp()
  4. local player1ip, player2ip, p1data, p2data, player1port, player2port = "none", "none", nil, nil, nil, nil
  5. udp:settimeout(0)
  6. udp:setsockname('*', 12345)
  7. local p1ping = 0
  8. local p2ping = 0
  9. local data, msg_or_ip, port_or_nil
  10. while running do
  11. data, msg_or_ip, port_or_nil = udp:receivefrom()
  12. if data then
  13. if (player1ip == msg_or_ip) then
  14. p1ping = 0
  15. p1data = data
  16. elseif player2ip == msg_or_ip then
  17. p2data = data
  18. p2ping = 0
  19. else
  20. if (player1ip == "none") then
  21. player1ip = msg_or_ip
  22. p1data = data
  23. player1port = port_or_nil
  24. print("CONNECTED: PLAYER 1 FROM: " .. player1ip)
  25. elseif player2ip == "none" and msg_or_ip ~= player1ip then
  26. player2ip = msg_or_ip
  27. p2data = data
  28. player2port = port_or_nil
  29. print("CONNECTED: PLAYER 2 FROM: " .. player2ip)
  30. elseif (player1ip ~= msg_or_ip and player2ip ~= msg_or_ip) then
  31. print("Lobby Full!" .. player1ip .. player2ip)
  32. end
  33. end
  34. elseif player1ip ~= "none" then
  35. p1ping = p1ping + 1
  36. if p1ping > 5 then
  37. if p2data then
  38. udp:sendto(p2data .. '|' .. p1ping, player1ip, player1port)
  39. end
  40. print("PLAYER 1 DISCONNECTED")
  41. p1data = nil
  42. player1ip = "none"
  43. player1port = nil
  44. end
  45. elseif player2ip ~= "none" then
  46. p2ping = p2ping + 1
  47. if p2ping > 5 then
  48. if p1data then
  49. udp:sendto(p1data .. '|' .. p2ping, player2ip, player2port)
  50. end
  51. print("PLAYER 2 DISCONNECTED")
  52. p2data = nil
  53. player2ip = "none"
  54. player2port = nil
  55. end
  56. end
  57. if data then
  58. print(data .. "FROM " .. msg_or_ip .. "Playerlist: " .. player1ip .. " " .. player2ip)
  59. end
  60. if p1data and p2data then
  61. udp:sendto(p1data .. '|' .. p2ping, player2ip, player2port)
  62. udp:sendto(p2data .. '|' .. p1ping, player1ip, player1port)
  63. print("SENT1: " .. player2ip .. " " .. player2port .. " " .. p1data)
  64. print("SENT2: " .. player1ip .. " " .. player1port .. " " .. p2data)
  65. end
  66. socket.sleep(0.01)
  67. end