player-lejos.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import bluetooth
  2. from robot import Robot
  3. from tag import TagClient
  4. from random import randint, random
  5. import signal, sys
  6. import math
  7. import time
  8. import numpy as np
  9. serverMACAddress = '00:16:53:18:2E:17'
  10. port = 1
  11. s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  12. s.connect((serverMACAddress, port))
  13. #while 1:
  14. # text = bytes([1])
  15. # if text == "quit":
  16. # break
  17. # s.send(bytes([1]))
  18. #sock.close()
  19. rid = 11
  20. run = False
  21. board = None
  22. tagplayer = -1
  23. client = TagClient('localhost', 10318)
  24. client.info(rid, 14, 19, 7, 13.5)
  25. px, py, course = None, None, None
  26. # Sinal de ctrl-c
  27. def signal_handler(signal, frame):
  28. client.stop()
  29. sock.close()
  30. sys.exit(0)
  31. signal.signal(signal.SIGINT, signal_handler)
  32. players = {}
  33. while not client.quit:
  34. time.sleep(0.4)
  35. # nao recebeu informacoes do campo
  36. if client.getFieldInfo() is None:
  37. continue
  38. elif px is None:
  39. board = client.getFieldInfo()
  40. px, py = board[0]*random(), board[1]*random()
  41. course = math.pi*2.0*random()
  42. # jogo esta pausado
  43. if client.getStatus() is False:
  44. players = {}
  45. s.send(bytes([0x65]))
  46. continue
  47. # nao recebeu informacoes do pegador
  48. if client.getTagInfo() is None:
  49. continue
  50. # verifica se ha posicoes novas
  51. newposs = client.getPosition()
  52. for info in newposs:
  53. posx, posy, courser, idd, xsize, ysize, xtag, ytag = info
  54. if idd != rid:
  55. players[idd] = [posx, posy]
  56. else:
  57. px, py, course = posx, posy, courser
  58. tag, interval = client.getTagInfo()
  59. pos = [players[p] for p in players]
  60. x1, y1 = 0, 0
  61. if time.time() >= interval and len(pos) >= 1 and tag == rid:
  62. print("Pegando")
  63. x1 = -py+pos[0][1]
  64. y1 = -px+pos[0][0]
  65. elif tag != rid:
  66. print("Fugindo")
  67. x1 = py-players[tag][1]
  68. y1 = px-players[tag][0]
  69. else:
  70. print("Esperando")
  71. s.send(bytes([5]))
  72. continue
  73. x2 = math.cos(course)
  74. y2 = math.sin(course)
  75. u = np.array([-x1, y1])
  76. v = np.array([x2, -y2])
  77. angle = np.math.atan2(np.linalg.det([u,v]),np.dot(u,v))
  78. print([u,v], angle)
  79. if abs(angle) < 0.2:
  80. s.send(bytes([1]))
  81. elif angle < 0:
  82. s.send(bytes([4]))
  83. else:
  84. s.send(bytes([3]))
  85. s.send(bytes([0x65]))
  86. s.send(bytes([0x64]))