DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    Steps to do the Contextual Logging

Configuring one time which is very efficient.

log4j.properties -- text highlighted in green specifies contextual information

1) log4j.appender.stdout.layout.ConversionPattern=%-5p %-23d{MM-dd-yyyy HH:mm:ss:S} [%t] %X{clientRequestIP} %X{timestamp} %X{session} %X{loggedinuserid} %X{loggedinusername} %X{httpmethod}  %X{requesturl} %c:%L %m%n


2) Code Snippet
Put this code in Filter class. This will be invoked once per request and attach unique timestamp which will be prepended for each controller, service, dao, adapter methods

		import org.apache.log4j.MDC;
	    	. . . . . .
		. . . . . .
		final long timestamp = (new Date()).getTime();
		MDC.put("timestamp", timestamp);
		MDC.put("httpmethod", httpmethod);
		MDC.put("session", sessionid);
		MDC.put("requesturl", requestUrl);
		MDC.put("loggedinusername", username);                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
FILENAME = 'db.txt'
OPEN, CLOSE = 1 , 0

file = File.open(FILENAME, 'a')
file.write "#{OPEN} : #{Time.new}\n"
file.flush

begin
	loop { sleep 60 } # sleep for an hour in an endless loop

rescue SystemExit, Interrupt # on exit
	file.write "#{CLOSE} : #{Time.new}\n"
	file.close
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'open-uri'
require 'uri'
require 'net/http'

CODE_LIMIT = 10
$url = "https://eval.in/"
$languages = {
	'c' => 'c/gcc-4.7.2',					'c++' => 'c++/gcc-4.7.2',
	'fortran' => 'fortran/f95-4.4.3',		'haskell' => 'haskell/hugs98-sep-2006',
	'io' => 'io/io-20110912',				'javascript' => 'javascript/node-0.10.26',
	'lua' => 'lua/lua-5.2.1',				'ocaml' => 'ocaml/ocaml-4.00.1',
	'php' => 'php/php-5.5.1',				'perl' => 'perl/perl-5.16.1',
	'python' => 'python/cpython-3.2.3',		'ruby' => 'ruby/mri-2.1.0',
	'slash' => 'slash/slash-head',			'assembly' => 'assembly/nasm-2.07'
}

def evalin code, language

	return nil unless $languages.keys.include? language
	return nil if code.length < CODE_LIMIT

	params = {
		code: code,			lang: $languages[language],
		execute: 'on',		input: ''
	}

	postData = Net::HTTP.post_form(URI.parse($url), params)
	location = postData['location']
	if location
		evalin_data = JSON.parse open("#{location.gsub 'http://', 'https://'}.json").read
		return "#{evalin_data['output']}\n#{evalin_data['status']}\n#{location}"
	end
	return nil
end

puts evalin('10.times{ puts "done."}', 'ruby')                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require "selenium-webdriver" # gem install selenium-webdriver
require "highline/import" # gem install highline

def coderwall github_email, github_password, title, content, tags

	driver = Selenium::WebDriver.for :firefox

	driver.navigate.to "https://coderwall.com/auth/github"
	
	driver.find_element(:css, '#login_field').send_keys github_email
	passwordf = driver.find_element(:css, '#password')
	passwordf.send_keys github_password
	passwordf.submit

	driver.navigate.to "https://coderwall.com/p/new"
	driver.find_element(:css, '#protip_title').send_keys title
	driver.find_element(:css, '#protip_body').send_keys content
	driver.find_element(:css, '#protip_tags').send_keys tags
	driver.find_element(:css, '.new_protip').submit

	driver.quit
end

email = ask 'What is your github email address ? '
password = ask('And github password? '){ |q| q.echo = '*' }
coderwall email, password, 'Title here', 'Content here', 'ruby, test'                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'psych'
require 'commander/import' # gem install commander
program :version, '0.0.1'
program :description, 'Simple Key Value Storage Commandline Script'

FILENAME = 'storage.json'
storage = File.exists?(FILENAME) ? JSON.parse(File.read(FILENAME)) : {}

command :c do |c|
  c.syntax = 'storage c key value'
  c.description = 'create new key with a value in our storage'
  c.example 'store myname key with my name as a value', 'ruby storage c myname emad elsaid hamed'
  c.action do |args, options|
    storage[args[0]] = args[1..-1].join(' ')
    File.write FILENAME, storage.to_json
  end
end

command :r do |c|
  c.syntax = 'storage r key'
  c.description = 'read a key value or all values from storage'
  c.example 'read my name', 'ruby storage r myname'
  c.action do |args, options|
    puts( args[0] ? storage[args[0]] : storage.to_yaml )
  end
end

command :d do |c|
  c.syntax = 'storage d key'
  c.description = 'delete a key from storage'
  c.example 'remove my name from storage', 'ruby storage d myname'
  c.action do |args, options|
    storage.delete args[0]
    File.write FILENAME, storage.to_json
  end
end

                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'gosu'
include Gosu
DIMENSION, SPLITS, COLOR = 200, 50, Color::GREEN
# credits to: http://en.wikipedia.org/wiki/Maze_generation_algorithm
class GameWindow < Window
  def initialize
    super DIMENSION, DIMENSION, false, 1000
    self.caption = "Maze"
  end
  def draw
    complexity, density = 0.75, 0.75
    shape = [(SPLITS / 2) * 2 , (SPLITS / 2) * 2 ] # Only odd shapes
    # Adjust complexity and density relative to maze size
    complexity = (complexity * (5 * (shape[0] + shape[1])))
    density    = (density * (shape[0] / 2 * shape[1] / 2))
    z = Array.new(shape[0]){ Array.new(shape[1], 0) } # Build actual maze
    # Fill borders
    z[0] = z[-1].fill 1
    z.each { |l| l[0] = l[-1] = 1 }
    for i in 0...density # Make isles
        x, y = rand(shape[1] / 2) * 2, rand(shape[0] / 2) * 2
        z[y][x] = 1
        for j in 0...complexity
            neighbours = []
            neighbours << [y, x - 2] if x > 1
            neighbours << [y, x + 2] if x < shape[1] - 2
            neighbours << [y - 2, x] if y > 1
            neighbours << [y + 2, x] if y < shape[0] - 2
            unless neighbours.empty?
                y_,x_ = neighbours[rand(neighbours.size - 1)]
                if z[y_][x_] == 0
                    z[y_ + (y - y_) / 2][x_ + (x - x_) / 2] = z[y_][x_] = 1
                    x, y = x_, y_
                end
            end
        end
    end
    size = DIMENSION/SPLITS
  	z.each_with_index do |row, x|
        row.each_with_index do |value, y|
            draw_quad x*size, y*size, COLOR,
                      x*size+size, y*size, COLOR,
                      x*size+size, y*size+size, COLOR,
                      x*size, y*size+size, COLOR if value==1
        end
    end
  end
end
GameWindow.new.show                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'gosu'
include Gosu

$dimension = 200
$line_limit = 70

class GameWindow < Window

  def initialize
    super $dimension, $dimension, false
    self.caption = "Drawing board"
  	@points = []
  end

  def update
    @points << [ mouse_x, mouse_y ]
    @points.shift if @points.size > $line_limit
  end

  def draw
  	return if @points.empty?
	@points.inject(@points[0]) do |last, point|
		draw_line	last[0],last[1], Color::GREEN,
					point[0],point[1], Color::GREEN
		point
	end
  end
  
end
GameWindow.new.show
                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# Idea of : Thibault (@EyeWriteCode)
require 'Twitter' #gem install twitter
begin
	# Create a read application from : 
	# https://apps.twitter.com
	# authenticate it for your account
	# fill in the following
	config = {
		consumer_key:        '',
		consumer_secret:     '',
		access_token:        '',
		access_token_secret: ''
	}
	sClient = Twitter::Streaming::Client.new(config)
	rClient = Twitter::REST::Client.new(config)
	following = rClient.friend_ids.to_a
	topics = ['#NP', '#NW', '#nowplaying', '#now_playing']

	sClient.filter(track: topics.join(',')) do |tweet|
		if tweet.is_a?(Twitter::Tweet)
		  text = tweet.text
		  			.gsub(/[#@]\S+/,'')
		  			.gsub(/\n+/,' ')
		  			.gsub(/\s{2,}/,'')
		  			.strip
		  user = tweet.user
		  puts "#{user.screen_name} : #{text}" if following.include? user.id
		end
	end
rescue
	puts 'error occurred, waiting for 5 seconds'
	sleep 5
	retry
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'sinatra'

set :port, 3000
set :environment, :production

get '/' do
	<<-EOT
<html><head>
	</head><body style="padding:0px;margin:0px;">
	<form action="/upload" method="post" enctype="multipart/form-data" >
		Choose files <input type="file" name="files[]" multiple>
		<input type="submit" value="Upload" />
	</form>
</body></html>
EOT
end

post '/upload' do
	params['files'].each do |f|
		tempfile = f[:tempfile]
		filename = f[:filename]
		FileUtils.copy(tempfile.path, "./#{filename}")
	end
	redirect '/'
end                
                    namespace PathFindingSample
{
   
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D tileImage;

        A_Star a_star;
        
        Agent agent;

        MouseState mClick;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 500;
            graphics.PreferredBackBufferHeight = 500;
            this.IsMouseVisible = true;
        }
        
        public static TileInfo[,] tileInfo = new TileInfo[10, 10];

        public Point startLoc = new Point(3, 4);
        public Point endLoc = new Point(9, 9);

        protected override void Initialize()
        {
            // Create the tile objects in the array
            for (int x = 0; x < tileInfo.GetLength(0); x++)
            {
                for (int y = 0; y < tileInfo.GetLength(0); y++)
                {
                    tileInfo[x, y] = new TileInfo();
                }
            }

            // Change some tiles to walls
            tileInfo[4, 0].tileType = TileInfo.TileType.Wall;
            tileInfo[4, 1].tileType = TileInfo.TileType.Wall;
            tileInfo[4, 2].tileType = TileInfo.TileType.Wall;
            tileInfo[4, 3].tileType = TileInfo.TileType.Wall;
            tileInfo[4, 4].tileType = TileInfo.TileType.Wall;
            tileInfo[4, 5].tileType = TileInfo.TileType.Wall;
            tileInfo[3, 5].tileType = TileInfo.TileType.Wall;
            tileInfo[2, 5].tileType = TileInfo.TileType.Wall;
            tileInfo[1, 5].tileType = TileInfo.TileType.Wall;
            tileInfo[1, 4].tileType = TileInfo.TileType.Wall;
            tileInfo[1, 3].tileType = TileInfo.TileType.Wall;
            tileInfo[1, 2].tileType = TileInfo.TileType.Wall;

            tileInfo[7, 6].tileType = TileInfo.TileType.Wall;
            tileInfo[7, 7].tileType = TileInfo.TileType.Wall;
            tileInfo[7, 8].tileType = TileInfo.TileType.Wall;
            tileInfo[7, 9].tileType = TileInfo.TileType.Wall;


            // Pass the tile information and a weight for the H.
            // The lower the H weight value shorter the path
            // the higher it is the less number of checks it take to determine
            // a path.  Less checks might be useful for a very large number of agents.
            int hWeight = 2;
            a_star = new A_Star(tileInfo, hWeight);

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            tileImage = Content.Load<Texture2D>("tile");

            agent = new Agent(Content.Load<Texture2D>("agent"), startLoc, a_star);
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            mClick = Mouse.GetState();
            if (mClick.LeftButton == ButtonState.Pressed)
            {
                startLoc.X = (int)mClick.X / 50;
                startLoc.Y = (int)mClick.Y / 50;
            }
            if (mClick.RightButton == ButtonState.Pressed)
            {
                endLoc.X = (int)mClick.X / 50;
                endLoc.Y = (int)mClick.Y / 50;
            }
            agent.setDestination(startLoc.X, startLoc.Y, endLoc.X, endLoc.Y);
            base.Update(gameTime);
            agent.Update(gameTime);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            for (int x = 0; x < tileInfo.GetLength(0); x++)
            {
                for (int y = 0; y < tileInfo.GetLength(0); y++)
                {
                    if (tileInfo[x, y].tileType == TileInfo.TileType.Floor)
                        spriteBatch.Draw(tileImage, new Vector2(x * 50, y * 50), Color.White);
                    else if (tileInfo[x, y].tileType == TileInfo.TileType.Wall)
                        spriteBatch.Draw(tileImage, new Vector2(x * 50, y * 50), Color.DarkGray);
                }
            }

            for (int i = 0; i < agent.a_star.Path.Count; i++)
            {
                spriteBatch.Draw(tileImage, new Vector2(agent.a_star.Path[i].X * 50, agent.a_star.Path[i].Y * 50), Color.Yellow);
            }

            spriteBatch.Draw(tileImage, new Vector2(startLoc.X * 50, startLoc.Y * 50), Color.Green);
            spriteBatch.Draw(tileImage, new Vector2(endLoc.X * 50, endLoc.Y * 50), Color.Red);
            agent.Draw(spriteBatch);


            spriteBatch.End();
            base.Draw(gameTime);
        }

       
    }

    public class Agent
    {
        public bool isPlayer;
        enum AgentState { Pathing, Stopped };
        AgentState agentState = AgentState.Stopped;

        Point tileLocation;  // Which tile the agent is currently on
        Vector2 drawLocation;  // Where the agent is being drawn on screen

        Vector2 velocity; // Speed X Direction of the agent
        float speed = 3;  // rate the agent moves
        float distanceCheckValue; // distance to the nextPathLoc that is used to switch

        public A_Star a_star;  // Our pathfinding class instance

        Vector2 drawOrigin;  // The origin used to draw the agent
        Texture2D texture; // The image of the agent

        Vector2 nextPathLoc;  // The next location in the path we are trying to reach
        Point destination;  // the final destination tile we are trying to reach

        int setDestX;
        int setDestY;
        int setStartX;
        int setStartY;

        public void setDestination(int w , int x , int y , int z)
        {
            setStartX = w;
            setStartY = x;
            setDestX = y;
            setDestY = z;
        }

        public Agent(Texture2D tex, Point loc, A_Star A)
        {
            drawLocation = getDrawLoc(loc);            
            UpdateTileLoc();          
            velocity = Vector2.Zero;
            texture = tex;
            drawOrigin = new Vector2(texture.Width, texture.Height) * 0.5f;
            a_star = A;
            distanceCheckValue = speed * 1.75f;
        }

        Vector2 getDrawLoc(Point loc)
        {
            // Convert tile location to onscreen location
            return new Vector2(loc.X * 50 + 25, loc.Y * 50 + 25);
        }

        Vector2 getDrawLoc(Vector2 loc)
        {
            // Convert tile location from the path that is a vector to onscreen location
            return new Vector2(loc.X * 50 + 25, loc.Y * 50 + 25);
        }

        void UpdateTileLoc()
        {
            // Update the tile location based on the onscreen location
            Point tileLocationTmp = new Point((int)drawLocation.X / 50, (int)drawLocation.Y / 50);

            // It the agent has moved from one location to tile to another remove the reference to the agent from
            // the old tile, update the location and set a reference to the agent on the new tile            
            if (tileLocationTmp != tileLocation)
            {
                Game1.tileInfo[tileLocation.X, tileLocation.Y].unitOnTile = null;
                tileLocation = tileLocationTmp;
                Game1.tileInfo[tileLocation.X, tileLocation.Y].unitOnTile = this;
            }
        }

        public Point GetDestintation()
        {
            // This is a function that would find the goal of the path
            // For example this could be a function to find the closest player and set the enemy to move towards him.
            if (tileLocation == new Point(setDestX, setDestY))
                return new Point(setStartX, setStartY);
            else
                return new Point(setDestX, setDestY);
        }

        public void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (agentState == AgentState.Stopped)
            {
                destination = GetDestintation();

                if (destination != tileLocation)
                {
                    a_star.start(tileLocation.X, tileLocation.Y, destination.X, destination.Y);
                    if (a_star.pathAvailable)
                    {
                        // Start in the direction of the first part of the path
                        agentState = AgentState.Pathing;
                        nextPathLoc = getDrawLoc(a_star.Path[0]);
                        velocity = nextPathLoc - drawLocation;
                        velocity.Normalize();
                        velocity *= speed;

                    }
                }
            }

            if (agentState == AgentState.Pathing)
            {
                if (a_star.pathAvailable && a_star.Path.Count > 1)
                {
                    // Check if we need to start moving toward the next path part
                    if ((nextPathLoc - drawLocation).Length() < distanceCheckValue)
                    {
                        // remove the path part we are currently moving towards
                        a_star.Path.RemoveAt(0);
                        // set the location in screen co-ordinates for the new path part
                        nextPathLoc = getDrawLoc(a_star.Path[0]);

                        // Set the velocity pointing towards the next path part
                        velocity = nextPathLoc - drawLocation;
                        velocity.Normalize();
                        velocity *= speed;
                    }
                }

                // Update the draw location and tile location
                drawLocation += velocity;
                UpdateTileLoc();

                // Check if we have reached the overall goal of the path
                if (a_star.Path.Count == 1 && (nextPathLoc - drawLocation).Length() < distanceCheckValue)
                {
                    // Stop the agent and make sure it is on the exact location of the goal
                    drawLocation = nextPathLoc;
                    velocity = Vector2.Zero;
                    agentState = AgentState.Stopped;
                }
            }

        }


        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, drawLocation, null, Color.White, 0, drawOrigin, 1, SpriteEffects.None, 0);
        }
    }
}

// This is a new class Astar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace PathFindingSample
{
    //public class Unit
    //{
    //    public bool isPlayer;
    //}

    public class TileInfo
    {
        public enum TileType { Floor, Wall, Door, OpenDoor };
        public TileType tileType = TileType.Floor;
        public Agent unitOnTile;
    }

    public class A_Star
    {
        TileInfo[,] colMap;
        Dictionary<Point, listitem> list = new Dictionary<Point, listitem>();
        List<listitem> openList = new List<listitem>();

        int hWeight;

        int goalX;
        int goalY;
        int startX;
        int startY;


        int Width, Height;

     
        public List<Vector2> Path;

        public bool pathAvailable = false;

        public struct listitem
        {
            public listitem(int X, int Y)
            {
                x = X;
                y = Y;
                opened = false;
                closed = false;
                F = 0;
                G = 0;
                H = 0;
                parentX = 0;
                parentY = 0;
            }
            public int x;
            public int y;
            public bool opened;
            public bool closed;
            public int F;
            public int G;
            public int H;
            public int parentX;
            public int parentY;
        }

        public A_Star(TileInfo[,] ColMap, int _hWeight)
        {
            hWeight = _hWeight;
            colMap = ColMap;
            Path = new List<Vector2>();
            Width = colMap.GetLength(0);
            Height = colMap.GetLength(1);
        }

        public bool start(int Sx, int Sy, int Gx, int Gy)
        {
            pathAvailable = false;

            goalX = Gx;
            goalY = Gy;

            startX = Sx;
            startY = Sy;

            Path.Clear();

            openList.Clear();
           
            list.Clear();

            bool noPath = false;

            if ((Gx - 1 < 0 || colMap[Gx - 1, Gy].tileType == TileInfo.TileType.Wall) &&
               (Gx + 1 > Width || colMap[Gx + 1, Gy].tileType == TileInfo.TileType.Wall) &&
                (Gy - 1 < 0 || colMap[Gx, Gy - 1].tileType == TileInfo.TileType.Wall) &&
                (Gy + 1 > Width || colMap[Gx, Gy + 1].tileType == TileInfo.TileType.Wall))
                noPath = true;


            if (!(Sx == Gx && Sy == Gy) && colMap[Gx, Gy].tileType != TileInfo.TileType.Wall && !noPath)
            {
                list.Add(new Point(Sx, Sy), new listitem(Sx, Sy));
                list.Add(new Point(Gx, Gy), new listitem(Gx, Gy));
                openList.Add(new listitem(Sx, Sy));

                setOpenOnLowestF(Sx, Sy, Gx, Gy);

                if (pathAvailable)
                {
                    makePath(Gx, Gy, Sx, Sy);
                }
                else if (colMap[Gx, Gy].unitOnTile != null && colMap[Gx, Gy].unitOnTile.isPlayer
                    && Math.Abs(goalX - startX) < 2 && Math.Abs(goalY - startY) <  2)
                {
                    // If the player is on the goal tile then return true so we can attack him
                    Path.Add(new Vector2(Gx, Gy));
                    return true;
                }


            }

            //Console.WriteLine(Path.ToString);

            return pathAvailable;
        }


        void setOpenOnLowestF(int Sx, int Sy, int Gx, int Gy)
        {
            int test = 0;
            int loops = 0;
            int removeIndex = 0;

            do
            {
                Point startLoc = new Point(Sx, Sy);
                listitem ListItem = list[startLoc];
                loops++;


                ListItem.opened = false;
                openList.RemoveAt(removeIndex);
                ListItem.closed = true;
                list[startLoc] = ListItem;

                int YFin = Sy + 1;
                int XFin = Sx + 1;
                for (int y = Sy - 1; y <= YFin; ++y)
                {
                    if (y < 0 || y > Height - 1)
                        continue;

                    for (int x = Sx - 1; x <= XFin; ++x)
                    {
                        Point Location = new Point(x, y);

                        if (!list.ContainsKey(Location))
                            list.Add(new Point(x, y), new listitem(x, y));

                        if ((x == Sx && y == Sy) || (x < 0 || x > Width - 1)
                                || (!isWalkable(x, y)) || (list[Location].closed)) // || npcthere(x, y))
                            continue;

                        TileInfo ColNode = colMap[x, y];

                        listitem tempListItem = list[Location];

                        if (tempListItem.opened)
                        {
                            int tempG = 0;
                            if (x == Sx || y == Sy)
                            {
                                if (ColNode.unitOnTile == null)
                                    tempG = 10 + list[Location].G;
                                else
                                {

                                    tempListItem.G = 45 + tempListItem.G;
                                }

                            }
                            else
                            {
                                if (ColNode.unitOnTile == null)
                                    tempG = 14 + tempListItem.G;
                                else
                                {

                                    tempListItem.G = 62 + tempListItem.G;

                                }

                            }

                            if (tempG < list[Location].G)
                            {
                                tempListItem.G = tempG;
                                tempListItem.parentX = Sx;
                                tempListItem.parentY = Sy;
                                tempListItem.F = tempListItem.G + tempListItem.H;
                            }

                            list[Location] = tempListItem;
                            continue;

                        }

                        if (x == Sx || y == Sy)
                        {


                            if (ColNode.unitOnTile == null)
                                tempListItem.G = 10 + list[new Point(Sx, Sy)].G;
                            else
                            {
                                        tempListItem.G = 45 + list[new Point(Sx, Sy)].G;

                            }
                            tempListItem.opened = true;
                            tempListItem.x = x;
                            tempListItem.y = y;
                            tempListItem.parentX = Sx;
                            tempListItem.parentY = Sy;
                            tempListItem.H = calculateH(goalX, x) + calculateH(goalY, y);
                            tempListItem.F = tempListItem.G + tempListItem.H;
                            openList.Add(tempListItem);
                            list[Location] = tempListItem;
                        }
                        else
                        {
                            if ((x + 1 < Width && !isWalkable(x + 1, y)) || 
                                (x - 1 >= 0 &&!isWalkable(x - 1, y)) || 
                                (y - 1 >= 0 && !isWalkable(x, y - 1)) || 
                                (y + 1 < Height && !isWalkable(x, y + 1)))
                            {
                                tempListItem.opened = false;
                                list[Location] = tempListItem;
                                continue;
                            }

                            if (ColNode.unitOnTile == null)
                                tempListItem.G = 14 + list[new Point(Sx, Sy)].G;
                            else
                            {
                                tempListItem.G = 62 + list[new Point(Sx, Sy)].G;
                            }

                            tempListItem.opened = true;
                            tempListItem.x = x;
                            tempListItem.y = y;
                            tempListItem.parentX = Sx;
                            tempListItem.parentY = Sy;
                            tempListItem.H = calculateH(goalX, x) + calculateH(goalY, y);
                            tempListItem.F = tempListItem.G + tempListItem.H;
                            openList.Add(tempListItem);
                            list[Location] = tempListItem;

                        }
                    }
                }

                if (!(list[new Point(Gx, Gy)].opened))
                {
                    int lowestF = 10000;
                    test = 0;
                    int ITEMS = openList.Count;
                    for (int index = 0; index < ITEMS; ++index)
                    {
                        test++;
                        if (openList[index].F < lowestF)
                        {
                            lowestF = openList[index].F;
                            Sx = openList[index].x;
                            Sy = openList[index].y;
                            removeIndex = index;
                        }

                    }

                }
                //diplayCurrent(new Point(Sx, Sy));                
            } while (test != 0 && !list[new Point(Gx, Gy)].opened && loops < 300);

            //diplayCurrent(new Point(Sx, Sy));

            if (test == 0 || loops > 249)
                pathAvailable = false;
            else
                pathAvailable = true;

        }



        bool isWalkable(int x, int y)
        {
            listitem tempItem = new listitem();
            Point Loc = new Point(x, y);

            if (colMap[x, y].tileType == TileInfo.TileType.Wall)
            {
                tempItem.closed = true;
                if (!list.ContainsKey(Loc))
                    list.Add(Loc, tempItem);
                list[new Point(x, y)] = tempItem;
                return false;
            }
            else if (colMap[x, y].unitOnTile != null && colMap[x, y].unitOnTile.isPlayer && x != goalX && y != goalY)
            {
                tempItem.closed = true;
                if (!list.ContainsKey(Loc))
                    list.Add(Loc, tempItem);
                list[new Point(x, y)] = tempItem;
                return false;
            }

            return true;
        }

        int calculateH(int G, int S)
        {
            if (S > G)
                return (S - G) * hWeight;
            else if (G > S)
                return (G - S) * hWeight;
            else
                return 0;
        }


        void makePath(int Gx, int Gy, int Sx, int Sy)
        {
            Vector2 temp = new Vector2(Gx, Gy);


            while (!(temp.X == Sx && temp.Y == Sy))
            {
                Path.Insert(0, temp);

                int x = (int)temp.X;
                int y = (int)temp.Y;
                Point loc = new Point(x, y);
                temp = new Vector2(list[loc].parentX, list[loc].parentY);
            }
        }

        Vector2 getParentof(int x, int y)
        {
            Point loc = new Point(x, y);
            return new Vector2(list[loc].parentX, list[loc].parentY);
        }



        public bool getOpened(int x, int y)
        {
            Point loc = new Point(x, y);
            return list[loc].opened;
        }

        public bool getClosed(int x, int y)
        {
            Point loc = new Point(x, y);
            return list[loc].closed;
        }

        public int getF(int x, int y)
        {
            Point loc = new Point(x, y);
            return list[loc].F;
        }

        public int getG(int x, int y)
        {
            Point loc = new Point(x, y);
            return list[loc].G;
        }

        public int getH(int x, int y)
        {
            Point loc = new Point(x, y);
            return list[loc].H;
        }

#if WINDOWS
        public void diplayCurrent(Point p)
        {
            Console.Clear();

            Console.WriteLine("Open or Closed");

            for (int y = -1; y < colMap.GetLength(1); ++y)
            {
                for (int x = -1; x < colMap.GetLength(0); ++x)
                {
                    if (x == -1 || y == -1)
                    {
                        if (y == -1 && x == -1)
                            Console.Write("\t");
                        if (y == -1 && x != -1)
                        {
                            if (x < 10)
                                Console.Write("  " + x);
                            else
                                Console.Write(" " + x);
                        }
                        if (y != -1 && x == -1)
                            Console.Write(y + "\t");
                    }
                    else
                    {
                        Point loc = new Point(x, y);
                        if (startX == x && startY == y)
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.Write(" S ");
                        }
                        else if (p.X == x && p.Y == y)
                        {
                            Console.ForegroundColor = ConsoleColor.Magenta;
                            Console.Write(" X ");
                        }
                        else if (goalX == x && goalY == y)
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.Write(" G ");
                        }
                        else if (list.ContainsKey(loc) && getOpened(x, y))
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.Write(" O ");
                        }
                        else if (list.ContainsKey(loc) && getClosed(x, y))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.Write(" C ");
                        }
                        else if (colMap[x, y].tileType == TileInfo.TileType.Wall)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.Write(" # ");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.White;
                            Console.Write(" x ");
                        }

                    }


                }
                Console.WriteLine();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.White;
                
            }
            //Console.ReadKey();
            //Console.WriteLine("Values");

            //for (int y = -1; y < colMap.GetLength(1); ++y)
            //{
            //    for (int x = -1; x < colMap.GetLength(0); ++x)
            //    {
            //        if (x == -1 || y == -1)
            //        {
            //            if (y == -1 && x == -1)
            //                Console.Write("\t");
            //            if (y == -1 && x != -1)
            //            {
            //                if (x < 10)
            //                    Console.Write("   " + x);
            //                else
            //                    Console.Write("  " + x);
            //            }
            //            if (y != -1 && x == -1)
            //                Console.Write(y + "\t");
            //        }
            //        else
            //        {
            //            Point loc = new Point(x, y);
            //            if (list.ContainsKey(loc))
            //            {
            //                Console.ForegroundColor = ConsoleColor.Yellow;
            //                if (list[loc].F < 10)
            //                    Console.Write(" 00" + list[loc].H + " ");
            //                else if (list[loc].F < 100)
            //                    Console.Write(" 0" + list[loc].H + " ");
            //                else
            //                    Console.Write(" " + list[loc].H + " ");
            //            }
            //            else
            //                Console.Write(" XXX");
            //        }


            //    }
            //    Console.WriteLine();
            //    Console.WriteLine();
            //    Console.ForegroundColor = ConsoleColor.White;
            //}


            //Console.WriteLine();
            //Console.WriteLine("Values of G");

            //for (int y = 0; y < colMap.GetLength(1); ++y)
            //{
            //    for (int x = 0; x < colMap.GetLength(0); ++x)
            //    {
            //        Point loc = new Point(x, y);
            //        if (list.ContainsKey(loc))
            //        {
            //            if (list[loc].G > 9)
            //                Console.Write("" + list[loc].G + " ");
            //            else
            //                Console.Write(" 0" + list[loc].G + " ");
            //        }
            //    }
            //    Console.WriteLine();
            //    Console.WriteLine();
            //}

            //Console.WriteLine();
            //Console.WriteLine("H Values");

            //     for (int y = 0; y < colMap.GetLength(1); ++y)
            //{
            //    for (int x = 0; x < colMap.GetLength(0); ++x)
            //    {
            //        Point loc = new Point(x, y);
            //        if (list.ContainsKey(loc))
            //        {
            //            if (list[loc].H > 9)
            //            Console.Write(" " + list[loc].H + " ");
            //                else
            //            Console.Write(" 0" + list[loc].H + " ");
            //        }
            //    }
            //    Console.WriteLine();
            //    Console.WriteLine();
            //}


            //Console.ReadKey();



        } // End of Function
#endif



    }
}