JSFiddle - React, Tailwind, and code Playground
by Brenton Strine
HTML
<script src="https://unpkg.com/vue"></script>
<div id="rover">
<div id="line">
<div
class="block"
v-for="i in lineLength"
:class="{target: isTarget(i), rover: isRoverLocation(i)}"
@click="setNewTarget(i)">
{{ i }}
</div>
</div>
<button @click="rove">Rove</button>
</div>
CSS
.block {
display: inline-block;
width: 12px;
height: 12px;
border-left: solid 1px blue;
font-size: 8px;
text-align: center;
line-height: 12px;
vertical-align: top;
cursor:pointer;
}
#line {
border: solid 1px blue;
border-left: none;
height: 12px;
}
.target {
background-color: yellow;
}
.rover {
background-color: green;
}
JavaScript
var app = new Vue({
el: '#rover',
data: {
lineLength: 42,
target: 21,
roverLocation: 9,
roverLocationHistory: [],
movementAlgorithmHistory: [],
},
computed: {
// a computed getter
roverDistanceFromTarget: function () {
return this.target - this.roverLocation;
},
},
methods: {
distanceFromTarget: function (d) {
return this.target - d;
},
isTarget: function (i) {
return (this.target == i);
},
isRoverLocation: function (i) {
return (this.roverLocation == i);
},
setNewTarget: function(t){
this.target = t;
},
rove: function() {
var movement = this.getMovement();
console.log("Start: ", this.roverLocation);
if(movement) {
this.roverLocationHistory.unshift(this.roverLocation)
this.roverLocation += movement(this.roverDistanceFromTarget);
}
console.log("Finish: ", this.roverLocation);
},
moveRight: function(distance) {
console.log("a, move RIGHT")
this.movementAlgorithmHistory.unshift(this.moveRight);
if (distance == 0) {
return 0;
}else if (distance > 0) {
return 1;
} else {
return -1
}
},
moveLeft: function(distance) {
console.log("b, move LEFT")
this.movementAlgorithmHistory.unshift(this.moveLeft);
if (distance == 0) {
return 0;
} else if (distance < 0) {
return 1;
} else {
return -1
}
},
getMovement: function(distance) {
var previousMove = this.movementAlgorithmHistory[0];
if(previousMove && this.roverLocationHistory[0]){
var previousDistance = this.distanceFromTarget(this.roverLocationHistory[0]);
var currentDistance = this.roverDistanceFromTarget;
if(currentDistance < previousDistance) {
// went in the correct direction
return previousMove;
} else {
if (previousMove === this.movementA){
...