Let's consider a simple grid, where any point is connected with at most 4 other points (North-East-West-South neighborhood).
I have to write program, that computes minimal route from selected initial point to any of goal points, which are connected (there is route consisting of goal points between any two goals). Of course there can be obstacles on grid.
My solution is quite simple: I'm using A* algorithm with variable heuristic function h(x) - manhattan distance from x to nearest goal point. To find nearest goal point I have to do linear search (in O(n), where n - number of goal points). Here is my question: is there any more efficient solution (heuristic function) to dynamically find nearest goal point (where time < O(n))?
Or maybe A* is not good way to solve that problem?
How many goals, tens or thousands? If tens your way will work fine, if thousands then nearest neighbor search will give you ideas on setting up your data to search quickly.
The tradeoffs are obvious, spatially organizing your data to search will take time and on small sets brute force will be simpler to maintain. Since you're constantly evaluating I think that structuring the data will be worthwhile at very low numbers of points.
An alternate way to do this would be a modified flood fill algorithm that stops once it reaches a destination point during the flood.
First, decide whether you need to optimize, because any optimization is going to complicate your code, and for a small number of goals, your current solution is probably fine for a simple heuristic like Manhattan distance.
Before taking the first step, compute the heuristic for each goal. Remember the nearest goal as the currently selected goal, and move toward it, but subtract the maximum possible progress toward any goal from all the other distances. You can consider this second value a "meta-heuristic"; it is an optimistic estimate of the heuristic for other goals.
On subsequent steps, compute the heuristic for the current goal, and any goals with a "meta-heuristic" that is less than or equal to the heuristic. The other goals can't possibly have a better heuristic, so you don't need to compute them. The nearest goal becomes the new current goal; move toward it, subtracting the maximum possible progress from the others. Repeat until you arrive at a goal.
Use Dijkstra's algorithm, which has as it's output the minimal cost to all reachable points. Then you just select the goal points from the output.
you may consider this article If your goals not too much and want simple ways
If you want to search for any of several goals, construct a heuristic
h'(x) that is the minimum of h1(x), h2(x), h3(x), ... where h1, h2, h3
are heuristics to each of the nearby spots.
One way to think about this is that we can add a new zero-cost edge
from each of the goals to a new graph node. A path to that new node
will necessarily go through one of the goal nodes.
If you want to search for paths to all of several goals, your best
option may be Dijkstra’s Algorithm with early exit when you find all
the goals. There may be a variant of A* that can calculate these
paths; I don’t know.
If you want to search for spot near a single goal, ask A* search to
find a path to the center of the goal area. While processing nodes
from the OPEN set, exit when you pull a node that is near enough.
You can calculate the f score using the nearest target. As others said, for naive approach, you can directly calculate all target distance from current node and pick the minimum, if you only have few targets to search. For more than 100 targets, you can probably find the nearest by KDTree to speed up the process.
Here is a sample code in dart.
Iterable<Vector2> getPath(Vector2 from, Iterable<Vector2> targets,
{double? maxDistance, bool useAStar = false}) {
targets = targets.asSet();
clearPoints();
var projectedTargets = addPoints(targets).toSet();
var tree = useAStar ? IKDTree(targets) : null;
var q = PriorityQueue<Node>(_priorityQueueComparor);
Map<Vector2, Node> visited = {};
var node = Node(from);
visited[from] = node;
q.add(node);
while (q.isNotEmpty) {
var current = q.removeFirst();
// developer.log(
// '${current.point}#${current.distance}: ${getEdges(current.point).map((e) => e.dest)}');
for (var edge in getEdges(current.point)) {
if (visited.containsKey(edge.dest)) continue;
var distance = current.distance + edge.distance;
// too far
if (maxDistance != null && distance > maxDistance) continue;
// it is a target
if (projectedTargets.contains(edge.dest)) {
return reconstructPath(visited, current, edge.dest);
}
// we only interested in exploring polygon node.
if (!_polygonPoints.contains(edge.dest)) continue;
var f = 0.0;
if (tree != null) {
var nearest = tree
.nearest(edge.dest, maxDistance: maxDistance ?? double.infinity)
.firstOrNull;
f = nearest != null ? edge.dest.distanceToSquared(nearest) : 0.0;
}
node = Node(edge.dest, distance, current.count + 1, current.point, f);
visited[edge.dest] = node;
q.add(node);
}
}
return [];
}
Iterable<Vector2> reconstructPath(
Map<Vector2, Node> visited, Node prev, Vector2 point) {
var path = <Vector2>[point];
Node? currentNode = prev;
while (currentNode != null) {
path.add(currentNode.point);
currentNode = visited[currentNode.prev];
}
return path.reversed;
}
int _priorityQueueComparor(Node p0, Node p1) {
int r;
if (p0.f > 0 && p1.f > 0) {
r = ((p0.distance * p0.distance) + p0.f)
.compareTo((p1.distance * p1.distance) + p1.f);
if (r != 0) return r;
}
r = p0.distance.compareTo(p1.distance);
if (r != 0) return r;
return p0.count.compareTo(p1.count);
}
and the implementation of KDTree
class IKDTree {
final int _dimensions = 2;
late Node? _root;
IKDTree(Iterable<Vector2> points) {
_root = _buildTree(points, null);
}
Node? _buildTree(Iterable<Vector2> points, Node? parent) {
var list = points.asList();
if (list.isEmpty) return null;
var median = (list.length / 2).floor();
// Select the longest dimension as division axis
var axis = 0;
var aabb = AABB.fromPoints(list);
for (var i = 1; i < _dimensions; i++) {
if (aabb.range[i] > aabb.range[axis]) {
axis = i;
}
}
// Divide by the division axis and recursively build.
// var list = list.orderBy((e) => _selector(e)[axis]).asList();
list.sort(((a, b) => a[axis].compareTo(b[axis])));
var point = list[median];
var node = Node(point.clone());
node.parent = parent;
node.left = _buildTree(list.sublist(0, median), node);
node.right = _buildTree(list.sublist(median + 1), node);
update(node);
return node;
}
void addPoint(Vector2 point, [bool allowRebuild = true]) {
_root = _addByPoint(_root, point, allowRebuild, 0);
}
// void removePoint(Vector2 point, [bool allowRebuild = true]) {
// if (node == null) return;
// _removeNode(node, allowRebuild);
// }
Node? _addByPoint(
Node? node, Vector2 point, bool allowRebuild, int parentDim) {
if (node == null) {
node = Node(point.clone());
node.dimension = (parentDim + 1) % _dimensions;
update(node);
return node;
}
_pushDown(node);
if (point[node.dimension] < node.point[node.dimension]) {
node.left = _addByPoint(node.left, point, allowRebuild, node.dimension);
} else {
node.right = _addByPoint(node.right, point, allowRebuild, node.dimension);
}
update(node);
bool needRebuild = allowRebuild && criterionCheck(node);
if (needRebuild) node = rebuild(node);
return node;
}
// checked
void _pushDown(Node? node) {
if (node == null) return;
if (node.needPushDownToLeft && node.left != null) {
node.left!.treeDownsampleDeleted |= node.treeDownsampleDeleted;
node.left!.pointDownsampleDeleted |= node.treeDownsampleDeleted;
node.left!.treeDeleted =
node.treeDeleted || node.left!.treeDownsampleDeleted;
node.left!.deleted =
node.left!.treeDeleted || node.left!.pointDownsampleDeleted;
if (node.treeDownsampleDeleted) {
node.left!.downDeletedNum = node.left!.treeSize;
}
if (node.treeDeleted) {
node.left!.invalidNum = node.left!.treeSize;
} else {
node.left!.invalidNum = node.left!.downDeletedNum;
}
node.left!.needPushDownToLeft = true;
node.left!.needPushDownToRight = true;
node.needPushDownToLeft = false;
}
if (node.needPushDownToRight && node.right != null) {
node.right!.treeDownsampleDeleted |= node.treeDownsampleDeleted;
node.right!.pointDownsampleDeleted |= node.treeDownsampleDeleted;
node.right!.treeDeleted =
node.treeDeleted || node.right!.treeDownsampleDeleted;
node.right!.deleted =
node.right!.treeDeleted || node.right!.pointDownsampleDeleted;
if (node.treeDownsampleDeleted) {
node.right!.downDeletedNum = node.right!.treeSize;
}
if (node.treeDeleted) {
node.right!.invalidNum = node.right!.treeSize;
} else {
node.right!.invalidNum = node.right!.downDeletedNum;
}
node.right!.needPushDownToLeft = true;
node.right!.needPushDownToRight = true;
node.needPushDownToRight = false;
}
}
void _removeNode(Node? node, bool allowRebuild) {
if (node == null || node.deleted) return;
_pushDown(node);
node.deleted = true;
node.invalidNum++;
if (node.invalidNum == node.treeSize) {
node.treeDeleted = true;
}
// update and rebuild parent
var parent = node.parent;
if (parent != null) {
updateAncestors(parent);
bool needRebuild = allowRebuild && criterionCheck(parent);
if (needRebuild) parent = rebuild(parent);
}
}
void updateAncestors(Node? node) {
if (node == null) return;
update(node);
updateAncestors(node.parent);
}
void _removeByPoint(Node? node, Vector2 point, bool allowRebuild) {
if (node == null || node.treeDeleted) return;
_pushDown(node);
if (node.point == point && !node.deleted) {
node.deleted = true;
node.invalidNum++;
if (node.invalidNum == node.treeSize) {
node.treeDeleted = true;
}
return;
}
if (point[node.dimension] < node.point[node.dimension]) {
_removeByPoint(node.left, point, false);
} else {
_removeByPoint(node.right, point, false);
}
update(node);
bool needRebuild = allowRebuild && criterionCheck(node);
if (needRebuild) rebuild(node);
}
// checked
void update(Node node) {
var left = node.left;
var right = node.right;
node.treeSize = (left != null ? left.treeSize : 0) +
(right != null ? right.treeSize : 0) +
1;
node.invalidNum = (left != null ? left.invalidNum : 0) +
(right != null ? right.invalidNum : 0) +
(node.deleted ? 1 : 0);
node.downDeletedNum = (left != null ? left.downDeletedNum : 0) +
(right != null ? right.downDeletedNum : 0) +
(node.pointDownsampleDeleted ? 1 : 0);
node.treeDownsampleDeleted = (left == null || left.treeDownsampleDeleted) &&
(right == null || right.treeDownsampleDeleted) &&
node.pointDownsampleDeleted;
node.treeDeleted = (left == null || left.treeDeleted) &&
(right == null || right.treeDeleted) &&
node.deleted;
var minList = <Vector2>[];
var maxList = <Vector2>[];
if (left != null && !left.treeDeleted) {
minList.add(left.aabb.min);
maxList.add(left.aabb.max);
}
if (right != null && !right.treeDeleted) {
minList.add(right.aabb.min);
maxList.add(right.aabb.max);
}
if (!node.deleted) {
minList.add(node.point);
maxList.add(node.point);
}
if (minList.isNotEmpty && maxList.isNotEmpty) {
node.aabb = AABB()
..min = minList.min()
..max = maxList.max();
}
// TODO: Radius data for search: https://github.com/hku-mars/ikd-Tree/blob/main/ikd-Tree/ikd_Tree.cpp#L1312
if (left != null) left.parent = node;
if (right != null) right.parent = node;
// TODO: root alpha value for multithread
}
// checked
final minimalUnbalancedTreeSize = 10;
final deleteCriterionParam = 0.3;
final balanceCriterionParam = 0.6;
bool criterionCheck(Node node) {
if (node.treeSize <= minimalUnbalancedTreeSize) return false;
double balanceEvaluation = 0.0;
double deleteEvaluation = 0.0;
var child = node.left ?? node.right!;
deleteEvaluation = node.invalidNum / node.treeSize;
balanceEvaluation = child.treeSize / (node.treeSize - 1);
if (deleteEvaluation > deleteCriterionParam) return true;
if (balanceEvaluation > balanceCriterionParam ||
balanceEvaluation < 1 - balanceCriterionParam) return true;
return false;
}
void rebuildAll() {
_root = rebuild(_root);
}
// checked
Node? rebuild(Node? node) {
if (node == null) return null;
var parent = node.parent;
var points = flatten(node).toList();
// log('rebuilding: $node objects: ${objects.length}');
deleteTreeNodes(node);
return _buildTree(points, parent);
// if (parent == null) {
// _root = newNode;
// } else if (parent.left == node) {
// parent.left = newNode;
// } else if (parent.right == node) {
// parent.right = newNode;
// }
}
// checked
Iterable<Vector2> flatten(Node? node) sync* {
if (node == null) return;
_pushDown(node);
if (!node.deleted) yield node.point;
yield* flatten(node.left);
yield* flatten(node.right);
}
void deleteTreeNodes(Node? node) {
if (node == null) return;
_pushDown(node);
deleteTreeNodes(node.left);
deleteTreeNodes(node.right);
}
double _calcDist(Vector2 a, Vector2 b) {
double dist = 0;
for (var dim = 0; dim < _dimensions; dim++) {
dist += math.pow(a[dim] - b[dim], 2);
}
return dist;
}
// checked
double _calcBoxDist(Node? node, Vector2 point) {
if (node == null) return double.infinity;
double minDist = 0;
for (var dim = 0; dim < _dimensions; dim++) {
if (point[dim] < node.aabb.min[dim]) {
minDist += math.pow(point[dim] - node.aabb.min[dim], 2);
}
if (point[dim] > node.aabb.max[dim]) {
minDist += math.pow(point[dim] - node.aabb.max[dim], 2);
}
}
return minDist;
}
void _search(Node? node, int maxNodes, Vector2 point, BinaryHeap<Result> heap,
double maxDist) {
if (node == null || node.treeDeleted) return;
double curDist = _calcBoxDist(node, point);
double maxDistSqr = maxDist * maxDist;
if (curDist > maxDistSqr) return;
if (node.needPushDownToLeft || node.needPushDownToRight) {
_pushDown(node);
}
if (!node.deleted) {
double dist = _calcDist(point, node.point);
if (dist <= maxDistSqr &&
(heap.size() < maxNodes || dist < heap.peek().distance)) {
if (heap.size() >= maxNodes) heap.pop();
heap.push(Result(node, dist));
}
}
double distLeftNode = _calcBoxDist(node.left, point);
double distRightNode = _calcBoxDist(node.right, point);
if (heap.size() < maxNodes ||
distLeftNode < heap.peek().distance &&
distRightNode < heap.peek().distance) {
if (distLeftNode <= distRightNode) {
_search(node.left, maxNodes, point, heap, maxDist);
if (heap.size() < maxNodes || distRightNode < heap.peek().distance) {
_search(node.right, maxNodes, point, heap, maxDist);
}
} else {
_search(node.right, maxNodes, point, heap, maxDist);
if (heap.size() < maxNodes || distLeftNode < heap.peek().distance) {
_search(node.left, maxNodes, point, heap, maxDist);
}
}
} else {
if (distLeftNode < heap.peek().distance) {
_search(node.left, maxNodes, point, heap, maxDist);
}
if (distRightNode < heap.peek().distance) {
_search(node.right, maxNodes, point, heap, maxDist);
}
}
}
/// Find the [maxNodes] of nearest Nodes.
/// Distance is calculated via Metric function.
/// Max distance can be set with [maxDistance] param
Iterable<Vector2> nearest(Vector2 point,
{int maxNodes = 1, double maxDistance = double.infinity}) sync* {
var heap = BinaryHeap<Result>((e) => -e.distance);
_search(_root, maxNodes, point, heap, maxDistance);
var found = math.min(maxNodes, heap.content.length);
for (var i = 0; i < found; i++) {
yield heap.content[i].node.point;
}
}
int get length => _root?.length ?? 0;
int get height => _root?.height ?? 0;
}
class Result {
final Node node;
final double distance;
const Result(this.node, this.distance);
}
class Node {
Vector2 point;
int dimension = 0;
Node? parent;
Node? left;
Node? right;
int treeSize = 0;
int invalidNum = 0;
int downDeletedNum = 0;
bool deleted = false;
bool treeDeleted = false;
bool needPushDownToLeft = false;
bool needPushDownToRight = false;
bool treeDownsampleDeleted = false;
bool pointDownsampleDeleted = false;
AABB aabb = AABB();
Node(this.point);
int get length {
return 1 +
(left == null ? 0 : left!.length) +
(right == null ? 0 : right!.length);
}
int get height {
return 1 +
math.max(
left == null ? 0 : left!.height,
right == null ? 0 : right!.height,
);
}
int get depth {
return 1 + (parent == null ? 0 : parent!.depth);
}
}
LinkedListA = 3->4->5
LinkedListB = 12->6->9
I am simply trying to add linkedlistB at the end of the first linkedlistA.
I am not able to figure out Why the final while loop is able to print
the complete linkedlistA WITH all the nodes added from linkedlistB!
public static void joinLists(Node headA, Node headB)
{
Node currentA = headA;
Node currentB = headB;
while( currentA.nextLink != null )
{
currentA = currentA.nextLink;
}
Node newElement = currentB;
currentA.nextLink = newElement; //there is not loop here as you can see to keep updating the list with newElement taking new currentB value
currentB = currentB.nextLink;
currentA = headA;
while(currentA != null)
{
System.out.println(currentA.data);
currentA = currentA.nextLink; //output 3->4->5->12->6->9 How!?
}
}
My initial logic was doing simply this:-
public static void joinLists(Node headA, Node headB)
{
Node currentA = headA;
Node currentB = headB;
while (currentB != null)
{
currentA = head;
while( currentA.nextLink != null )
{
currentA = currentA.nextLink;
}
Node newElement = currentB;
currentA.nextLink = newElement;
currentB = currentB.nextLink;
}
currentA = headA;
while(currentA != null)
{
System.out.println(currentA.data);
currentA = currentA.nextLink;
}
}
But this doesn't seem to work!
But before that tell me how the first code seems to work?
You made the last node in A (the 5) point to the first node in B (the 12), which exactly corresponds to your output. You don't need a loop because the connections are distributed: each node only knows where the next node is. In attaching B to the end of A, only 1 link changes: the one you changed.
The first loop appends the list headB at the end of list headA.
public static Node joinLists(Node headA, Node headB)
{
if (headA == null)
{
headA = headB;
}
else
{
Node currentA = headA;
while (currentA.nextLink != null)
{
currentA = currentA.nextLink;
}
currentA.nextLink = headB;
}
Node current = headA;
while (current != null)
{
System.out.println(current.data);
current = current.nextLink;
}
return headA;
}
Then the printing loop would work.
In your second loop you tried something out (curretnA = head;).
Less variables will make understanding easier, as shown here.
One must use the return value for the joined list, as headA could be null.
LinkedList Data Structure work by the principal of ValueByReference Logic, that means, each node of linkedList can be stored anywhere in the memory location, we are just linking each node by mapping memory address to "Node.next" field
In First logic Code
Node newElement = currentB;
currentA.nextLink = newElement;
currentB = currentB.nextLink;
Your directly mapping headB pointer to last element in LinkedListA, so it similar to connecting each node in LinkedList.
Given a linked List $link1, with elements (a->b->c->d->e->f->g->h->i->j), we need to reverse the linked list provided that the reversing will be done in a manner like -
Reverse 1st element (a)
Reverse next 2 elements (a->c->b)
Reverse next 3 elements (a->c->b->f->e->d)
Reverse next 4 elements (a->c->b->f->e->d->j->i->h->g)
....
....
I have created below code in PHP to solve this problem
Things I need -
I need to calculate the time complexity of reverseLinkedList function below.
Need to know if we can optimize reverseLinkedList function to reduce time complexity.
-
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function read_node()
{
return $this->data;
}
}
class LinkList
{
private $first_node;
private $last_node;
private $count;
function __construct()
{
$this->first_node = NULL;
$this->last_node = NULL;
$this->count = 0;
}
function size()
{
return $this->count;
}
public function read_list()
{
$listData = array();
$current = $this->first_node;
while($current != NULL)
{
echo $current->read_node().' ';
$current = $current->next;
}
}
public function reverse_list()
{
if(($this->first_node != NULL)&&($this->first_node->next != NULL))
{
$current = $this->first_node;
$new = NULL;
while ($current != NULL)
{
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->first_node = $new;
}
}
public function read_node($position)
{
if($position <= $this->count)
{
$current = $this->first_node;
$pos = 1;
while($pos != $position)
{
if($current->next == NULL)
return null;
else
$current = $current->next;
$pos++;
}
return $current->data;
}
else
return NULL;
}
public function insert($data)
{
$new_node = new ListNode($data);
if($this->first_node != NULL)
{
$this->last_node->next = $new_node;
$new_node->next = NULL;
$this->last_node = &$new_node;
$this->count++;
}
else
{
$new_node->next = $this->first_node;
$this->first_node = &$new_node;
if($this->last_node == NULL)
$this->last_node = &$new_node;
$this->count++;
}
}
}
//Create linked list
$link1 = new LinkList();
//Insert elements
$link1->insert('a');
$link1->insert('b');
$link1->insert('c');
$link1->insert('d');
$link1->insert('e');
$link1->insert('f');
$link1->insert('g');
$link1->insert('h');
$link1->insert('i');
$link1->insert('j');
echo "<b>Input :</b><br>";
$link1->read_list();
//function to reverse linked list in specified manner
function reverseLinkedList(&$link1)
{
$size= $link1->size();
if($size>2)
{
$link2=new LinkList();
$link2->insert($link1->read_node(1));
$elements_covered=1;
//reverse
$rev_size=2;
while($elements_covered<$size)
{
$start=$elements_covered+1;
$temp_link = new LinkList();
$temp_link->insert($link1->read_node($start));
for($i=1;$i<$rev_size;$i++)
{
$temp_link->insert($link1->read_node(++$start));
}
$temp_link->reverse_list();
$temp_size=$temp_link->size();
$link2_size=$link2->size();
for($i=1;$i<=$temp_size;$i++)
{
$link2->insert($temp_link->read_node($i));
++$elements_covered;
++$link2_size;
}
++$rev_size;
}
///reverse
//Flip the linkedlist
$link1=$link2;
}
}
///function to reverse linked list in specified manner
//Reverse current linked list $link1
reverseLinkedList($link1);
echo "<br><br><b>Output :</b><br>";
$link1->read_list();
It's O(n)...just one traversal.
And secondly, here tagging it in language is not necessary.
I have provided a Pseudocode here for your reference:
current => head_ref
prev => NULL;
current => head_ref;
next => null;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
I am making a platforming game in which I must switch between colliding the character between two Arrays (whiteBlocks and blackBlocks) as well as another Array (redBlocks) that is activated on button collision and is timed.
However, I am having trouble with the hitTest code I have used to ensure that I can use redBlocks as a platform as well as either whiteBlocks or blackBlocks at the same time. I was wandering if anyone could help me to have the redBlocks constantly active once the timer has been triggered and is not effective by switching between blackBlocks or whiteBlocks.
If you would like me to explain my problem in a clearer way I will do. Please note that I am quite new to actionscript and coding in general so apologies for errors I may make. I appreciate any help you can offer as I have been troubleshooting this for a while now.
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.events.Event;
import flash.display.MovieClip
import flash.display.DisplayObject;
//PLAYER MOVEMENT
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyLIST);
stage.addEventListener(KeyboardEvent.KEY_UP, keyLIST);
manMC.positionPNT = new Point (manMC.x, manMC.y);
//track using loop and keypresses, not just keyEvent
var leftKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
function keyLIST (ke:KeyboardEvent) {
//trace(ke.toString() );
//1. work out where we're going from where we are now
//characterPNT = new Point(manMC.x, manMC.y);
//2. offset our destination point
switch (ke.keyCode) {
//LEFT
case 37:
trace(ke.type);
leftKeyDown = (ke.type == "keyDown");
break;
//RIGHT
case 39:
//moveCharacter(manMC, "right");
rightKeyDown = (ke.type == "keyDown");
break;
//87UP, 83DOWN
//UP
case 38:
trace("true");
manMC.jump();
break;
//DOWN
case 83:
break;
default:
//trace ("this key does nothing");
break;
}// close switch
}// end function keyLIST
function movementCallback (ev:Event):void {
if (leftKeyDown == true) {
moveCharacter(manMC, "left");
}
if (rightKeyDown == true) {
moveCharacter(manMC, "right");
}
}
addEventListener (Event.ENTER_FRAME, movementCallback);
//a new movement function
function moveCharacter(char:character, dir:String ):void {//datatype as void as it returns nothing
//will need this
//var characterPNT:Point; //moved to character class
//maMC.positionPNT = new Point( manMC.x, manMC.y);
//copy current poistion before offsetting with movement, speed and direction
manMC.destinationPNT = manMC.positionPNT.clone();
//characterPNT = new Point(manMC.x, manMC.y);
//var colliding:Boolean;
//do multiple collision detection here
var offsetPNT:Point;//detecting the destination of the body points
switch (dir) {
case "left":
//move PNT to left
manMC.destinationPNT.x -= manMC.speedNUM;
offsetPNT = manMC.leftarmPNT;
break;
case "right":
//move PNT to right
manMC.destinationPNT.x += manMC.speedNUM;
offsetPNT = manMC.rightarmPNT;
break;
}
//set to true of false by the function that returns a Boolean value
var colliding:Boolean = multipleHitTest (manMC.positionPNT, manMC.destinationPNT, offsetPNT, activeArray);
//trace(colliding);
//trace ("moveMode: " + manMC.moveModeSTR);
if (!colliding /*&& manMC.moveModeSTR != "falling"*/) { //may be more complex to control player movement when falling&jumping
manMC.moveToPoint( manMC.destinationPNT );
//manMC.x = manMC.destinationPNT.x;
//manMC.y = manMC.destinationPNT.y;
//always update position PNT when character is moved
//manMC.positionPNT = manMC.destinationPNT.clone();//copies destination point
}
}
//Apply gravity at all times using a loop/callback
addEventListener(Event.ENTER_FRAME, gravityFUNC);
var gravityNUM:Number = new Number(10);
function gravityFUNC (ev:Event) {
var falling:Boolean;
var gravityPNT:Point = manMC.positionPNT.clone();
//trace(manMC.positionPNT.y);
gravityPNT.y += gravityNUM;
//trace(gravityPNT.y);
//EXPERIMENTAL
gravityPNT.y -= manMC.verticalVelocityNUM;
//decaying gravity, caping it at 0 to avoid negatives
manMC.verticalVelocityNUM = Math.max ( 0, manMC.verticalVelocityNUM - gravityNUM);
falling = !multipleHitTest (manMC.positionPNT, gravityPNT, manMC.feetPNT, activeArray);
//trace("falling " + falling);
if (falling == true) {
//manMC.y = gravityPNT.y;
manMC.moveToPoint(gravityPNT);
//either jumping or falling
if ( manMC.verticalVelocityNUM == 0) {
manMC.moveModeSTR = "falling";
}else {
manMC.moveModeSTR = "jumping";
}
} else {
manMC.moveModeSTR = "walking";
}
}
//======================================================================
//======================================================================
//add when declared
//varobstacles:Array = new Array (block0MC, block1MC, block2MC);
//declared and then new instance
//var obstacles:Array;
//obstacles = new Array (block6MC);
//declares and create empty array
/*var obstacles:Array = new Array();
//push adds an item to the front of an array
obstacles.push (block0MC); // add instance names of display objects (or other data)
obstacles.push (block1MC);
obstacles.push (block2MC);
obstacles.push (block3MC);*/
//trace("length of list" + obstacles.length);
//trace(obstacles[0]); //access first element of array
//trace( block0MC["x"] );// acessing x property using different method
function multipleHitTest( position:Point, destination:Point, offset:Point, targets:Array):Boolean { //these are ARGUMENTS
//track hittest true or false
var returnBOOL:Boolean = new Boolean (false);
// cap length of loop - ie.e how many iterations?
var limit:int = new int ( targets.length );// obstacles.length is 3 items long
//the "counter", increases or decreases each time
var i:int;
//chunks =
//start counter at 0;
// loop while counter is less than limit;
// increment counter by 1 each looop;
for( i=0; i<limit; i++) {
//will access each item in array, as "i" is an integer
//obstacles[1];
//because it's targeted as a movieclip we can ask it's name
//this is 'reference variable'
//we are creating an 'alias' of the item in the list
var testAgainstObject:DisplayObject = targets[i];
//track direction
var moveDirection:String;
//only hit test things we're moving towards...
if (position.x < destination.x) { //if we're moving right
moveDirection = new String( "right" );
} else if (position.x > destination.x) {//else if we're moving left
moveDirection = new String( "left" );
}
//
if(
(moveDirection == "right" && targets[i].x >= position.x && destination.x >= targets[i].x)
||//or
(moveDirection == "left" && targets[i].x <= position.x && destination.x <= (targets[i].x + targets[i].width) )
) {//obstacle is to the right
// obstacle moving right
// moving right
}
//create a copy of 'destination'
var offsetDestination:Point = destination.clone();
//apply our offset provided by our character limbs
offsetDestination.offset(offset.x, offset.y);
//if point is colliding with list item
//if( testAgainstObject.hitTestPoint (destination.x, destination.y) ) { //REMOVED FOR TESTING
if( testAgainstObject.hitTestPoint (offsetDestination.x, offsetDestination.y) ) {
//trace("collisiondetected " + targets[i].name);
returnBOOL = true;
} else {
//trace("no collision");
//do nothing if flase, as it would contradict a 'true' value set earlier in the loop
}
}
return (returnBOOL); //tesing only
}
//declares and create empty array
var blackBlocks:Array = new Array();
//push adds an item to the front of an array
blackBlocks.push (block0MC); // add instance names of display objects (or other data)
blackBlocks.push (block1MC);
blackBlocks.push (blackbarrier);
blackBlocks.push (blackbarrier2);
blackBlocks.push (blackbarrier3);
blackBlocks.push (blackbarrier4);
blackBlocks.push (blackbarrier5);
var whiteBlocks:Array = new Array();
//push adds an item to the front of an array
whiteBlocks.push (block2MC);
whiteBlocks.push (block3MC);
whiteBlocks.push (whitebarrier);
whiteBlocks.push (whitebarrier2);
whiteBlocks.push (whitebarrier3);
whiteBlocks.push (whitebarrier4);
whiteBlocks.push (whitebarrier5);
var redBlocks:Array = new Array();
redBlocks.push (redblock1MC);
//var activeArray:Array = new Array (blackBlocks);
var activeArray:Array = blackBlocks;
//active.push (redblock1MC);
//Adds an event listener to the button component with the mouse click event.
//hide_btn.addEventListener(MouseEvent.CLICK, toggleBlocks);
//show_btn.addEventListener(MouseEvent.CLICK, showObject);
stage.addEventListener(KeyboardEvent.KEY_DOWN, toggleBlocks);
// start toggle blocks
function toggleBlocks (event:KeyboardEvent):void {
var i:int = 0;
var lim:int = activeArray.length;
if(event.keyCode == Keyboard.SPACE){
trace("Toggle Blocks");
blocksVisibility( activeArray , false );
if( activeArray == blackBlocks) {
activeArray = whiteBlocks;
}else{
activeArray = blackBlocks;
}
blocksVisibility( activeArray , true );
} // end IF
} // end toggle blocks
function blocksVisibility( arrARG:Array , visBOOL:Boolean ){
var i:int = 0;
var lim:int = arrARG.length;
for( i=0; i<lim; i++) {
arrARG[i].visible = visBOOL;
}
}
blocksVisibility( this.whiteBlocks , false );
blocksVisibility( this.redBlocks , false );
//blocksVisibility( this.redBlocks , false );
//======== red block button ========
// on collision trigger button and make red platform appear
/*
var myTimer:Timer = new Timer(5000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void {
//logo_mc.x+=40;
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
//activeArray:Array = redBlocks;
}
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
function onComplete(e:TimerEvent):void {
//logo_mc.alpha=10;
//logo_mc.x=20;
blocksVisibility( this.redBlocks , false );
//redBlock1MC:Array = false;
//activeArray:Array = blackBlocks;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStart);
function onStart(e:KeyboardEvent):void {
if (e.keyCode == 88){
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
myTimer.start();
//logo_mc.alpha=.1;
//logo_mc.x=20;
}
} */
var myTimer:Timer = new Timer(10000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, timedPlatform);
//myTimer.start();
function timedPlatform(event:TimerEvent):void {
trace("timedPlatform() called # " + getTimer() + " ms");
blocksVisibility( this.redBlocks , false );
/*if (manMC.hitTestObject(redButton)){
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = redBlocks;
} */
}
redButton.addEventListener(Event.ENTER_FRAME, startTimer);
function startTimer(event:Event):void{
//if (e.keyCode == 88){
//if (manMC, hitTest(redButton)) {
if (manMC.hitTestObject(redButton)) {
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = blackBlocks;
//activeArray = blackBlocks;
/*if( activeArray == blackBlocks) {
activeArray = redBlocks;
activeArray = blackBlocks;
}else{
activeArray = blackBlocks;
}*/
}
}
Instead of making activeArray a reference to whiteBlocks or blackBlocks, make it a separate Array object. Then, in toggleBlocks, you can
remove all elements from activeArray
add all elements from redBlocks to activeArray (optional depending on the current state)
add all elements from whiteBlocks OR blackBlocks to activeArray
This way activeArray will have all red blocks AND (all whiteBlocks OR all blackBlocks).
I have the following code which is used to Push and Pend from a queue. The caller code has multiple MsgQ objects. It is possible that the Push and the Pend functions are waiting on the _notFull->wait() and the _notEmpty->wait() conditional waits. These waits are protected by the _mut mutex. The notFull and the notEmpty waits operate on the empty and full variables.
When the destructor is called, the _deleteQueue is called internally, from which I would like to signal to the waiting threads to cleanup and stop waiting for a signal to come. Once that is done, I delete my objects. However, in the _deleteQueue function, when I attempt to do _mut->acquire(), I am unable to acquire the mutex. Even if I ignore the acquire, I am unable to broadcast to these waiting threads. Where am I going wrong?
Thanks,
Vikram.
MsgQ::~MsgQ()
{
_deleteQueue();
delete _mut;_mut=NULL;
delete _notFull;_notFull=NULL;
delete _notEmpty;_notEmpty=NULL;
delete _PostMutex; _PostMutex = NULL;
delete _PendMutex; _PendMutex = NULL;
delete _PostInProgressMutex; _PostInProgressMutex = NULL;
delete _PendInProgressMutex; _PendInProgressMutex = NULL;
delete _DisconnectMutex; _DisconnectMutex = NULL;
free( _ptrQueue ); _ptrQueue = NULL;
}
int MsgQ::Post(Message* msg)
{
_PostMutex->acquire();
_postInProgress++;
_PostMutex->release();
if (msg)
msg->print();
_mut->acquire();
while (full)
{
_notFull->wait();
}
if (!_disconnectInProgress)
_queuePush(msg);
_mut->release();
_PostMutex->acquire();
_postInProgress--;
if (_postInProgress==0)
{
_PostInProgressMutex->signal();
}
_PostMutex->release();
return _notEmpty->signal();
}
int MsgQ::Pend(Message*& msg)
{
_PendMutex->acquire();
_pendInProgress++;
_PendMutex->release();
_mut->acquire();
while (empty)
_notEmpty->wait();
if (!_disconnectInProgress)
{
_queuePop(msg);
}
_mut->release();
_PendMutex->acquire();
_pendInProgress--;
if (_pendInProgress == 0)
{
_PendInProgressMutex->signal();
}
_PendMutex->release();
return _notFull->signal();
}
void MsgQ::_deleteQueue ()
{
_PostMutex->acquire();
if (_postInProgress != 0)
{
_PostMutex->release();
TRACE("Acquiring Mutex.");
_mut->acquire();
full = 0;
_notFull->broadcast();
_mut->release();
_PostInProgressMutex->wait();
}
else
{
_PostMutex->release();
}
_PendMutex->acquire();
if (_pendInProgress != 0)
{
_PendMutex->release();
TRACE("Acquiring Mutex.");
_mut->acquire();
empty = 0;
_notEmpty->broadcast();
_mut->release();
_PendInProgressMutex->wait();
}
else
{
_PendMutex->release();
}
}
void MsgQ::_initQueue()
{
_ptrQueue = (Message **)(malloc (size * sizeof (Message*)));
if (_ptrQueue == NULL)
{
cout << "queue could not be created!" << endl;
}
else
{
for (int i = 0; i < size; i++)
*(_ptrQueue + i) = NULL;
empty = 1;
full = 0;
head = 0;
tail = 0;
try{
_mut = new ACE_Mutex() ;
_notFull = new ACE_Condition<ACE_Mutex>(*_mut);
_notEmpty = new ACE_Condition<ACE_Mutex>(*_mut);
_PostMutex = new ACE_Mutex();
_PendMutex = new ACE_Mutex();
_PostInProgressMutex = new ACE_Condition<ACE_Mutex>(*_PostMutex);
_PendInProgressMutex = new ACE_Condition<ACE_Mutex>(*_PendMutex);
_DisconnectMutex = new ACE_Mutex();
_postInProgress = 0;
_pendInProgress = 0;
_disconnectInProgress = false;
}catch(...){
cout << "you should not be here" << endl;
}
}
}
There seem to be many problems with the code so I would suggest reworking it:
You have a potential for deadlock because you are acquiring _mut before you go into a wait condition in both Post and Pend functions.
Instead of using acquire and release on a ACE_Mutex I would suggest looking at using ACE_Guard class which can acquire mutex when created and release it when destroyed.
Why not use ACE_Message_Queue instead of creating your own?