From dcb9e9e73a96074d6777b5c658b390bdc476f3f8 Mon Sep 17 00:00:00 2001 From: kepler155c Date: Mon, 5 Feb 2018 22:42:08 -0500 Subject: [PATCH] robot wars --- apps/robotWars.lua | 81 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 60 insertions(+), 21 deletions(-) diff --git a/apps/robotWars.lua b/apps/robotWars.lua index 1c78a49..5282e67 100644 --- a/apps/robotWars.lua +++ b/apps/robotWars.lua @@ -1,8 +1,3 @@ -_G.requireInjector(_ENV) - -local Event = require('event') -local Util = require('util') - local os = _G.os local peripheral = _G.peripheral @@ -11,25 +6,69 @@ if not ni then error("Cannot find neuralInterface") end -local TARGET = 'joebodo' +local RADIUS = 6 +local ROTATION = math.pi / 16 +local args = { ... } -local function look(entity) - local x, y, z = entity.x, entity.y, entity.z +local TARGET = args[1] or error('Syntax: robotWars ') + +local function yap(entity) + local x, y, z = entity.x, entity.y + 1, entity.z local pitch = -math.atan2(y, math.sqrt(x * x + z * z)) - local yaw = math.atan2(-x, z) + local yaw = math.atan2(-(x - .5), z - .5) - ni.look(math.deg(yaw), math.deg(pitch)) + return math.deg(yaw), math.deg(pitch) end -Event.addRoutine(function() - while true do - local target = Util.find(ni.sense(), 'name', TARGET) - if target then - look(target) - ni.shoot() - end - os.sleep(0) - end -end) +local function getUid() + for _,v in pairs(ni.sense()) do + if math.floor(v.x) == 0 and + math.floor(v.z) == 0 then + return v.id + end + end + error('Could not find myself') +end -Event.pullEvents() +local uid = getUid() + +local function findTarget(name) + for _, v in pairs(ni.sense()) do + if v.name == name and v.id ~= uid then + return v + end + end +end + +local function shootAt(name) + local target = findTarget(name) + if not target then + return + end + local yaw, pitch = yap(target) + debug('look: ' .. yaw) + ni.look(yaw, pitch) + debug('shoot') + pcall(ni.shoot, 1) +end + +while true do + local target = findTarget(TARGET) + if not target then + print('Won??') + break + end + local angle = math.atan2(-target.x, -target.z) + ROTATION + debug('walk: ' .. angle) + + ni.walk( + target.x + RADIUS * math.sin(angle), + 0, + target.z + RADIUS * math.cos(angle)) + os.sleep(.2) + repeat + os.sleep(0) + until not ni.isWalking() + + shootAt(TARGET) +end