среда, 30 октября 2013 г.

Sample Unity3D snake game

Play snake game online
Mouse position is captured to drive the snake. SmoothFollowTarget script is used to follow a captured mouse position, as well as for the tail to follow ancestor cell and a head of the snake.
Check out the Unity3D project files from here: https://dl.dropboxusercontent.com/u/50151183/blog/unity/SnakeSample/SnakeSample.zip 

Code:
using UnityEngine;
using System.Collections;

/// 
/// Smooth follow target
/// Used to follow a mouse position as well as for tyhe tail to follow its ancestor
/// 
[RequireComponent(typeof(CharacterController))]
public class SmoothFollowTarget : MonoBehaviour {

    public Transform target;
    public float distance=3;
    public float speed = 40;
    //public float rotationDamping=0.2f;

    private CharacterController controller;


 // Use this for initialization
 void Awake () {
        controller = GetComponent<CharacterController>()
}
 
 // Update is called once per frame
 void Update () {
        //return;
        // Early out if we don't have a target
        if (!target) return;
        // Always look at the target
        transform.LookAt(target);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        var newPos = target.position - transform.forward * distance;
        newPos.y =1; 
        var speedVector = newPos - transform.position;
        speedVector.y = 0;
        if (speedVector.magnitude>distance)
            controller.SimpleMove(speedVector.normalized * speed);

 }
}

понедельник, 28 октября 2013 г.

coding game contest: Snakes and ladders

Task
Snakes and Ladders (or chutes and ladders) is a board game wherein a player moves from square to square along the board in order to reach the end. Each square corresponds to a particular action which either gives the player an advantage or disadvantage. Each time a player takes his turn, he carries out an action depending on the square on which they land (throw the dice to move, move forward, move back, etc).

The objective of this program is to find out how many turns it takes for the luckiest player to win the game.

BOARD:
We consider a version of the game where the board is composed of a series of squares. Each square can contain either:
  • The character S which represents the starting square
  • The character E which represents the finishing square
  • A number representing how many squares a player should move forward (a positive number) or move back (a negative number)
  • The character R which indicates that the player should throw the dice to move
The start and finish squares are not necessarily situated at the start and end of the board.

GAME:
At the start of the game, the player begins on the starting square (labeled S). They start by throwing the dice and moving the number of squares indicated on the dice. They then carry out the action which is indicated on the square. Each action takes one turn (throw the dice to move, move forward, move back). The game is won when a player reaches the finishing square (labeled E).

If we were to have the following board :
  S  1  R  4  3  4  3  -5  2  -4  E

The fastest way to win in this case is to throw a 2 on the first throw of the dice, which will bring the player to the square R. Then they will throw the dice again and get 6, so they will move forward and land on a square with 2. On the last turn, they will not have a choice: they will move forward two squares and arrive on the square E.

The minimum number of turns to win this game is therefore 3.

Write a program that finds the minimum number of turns given the specified board.

In case a player cannot reach the finishing square, the program should displayimpossible.
INPUT:
Line 1: the number N of squares on the board
N following lines:  one square value per line (RSE or a number)
OUTPUT:
The minimum number of turns required to reach the finishing square or impossible.
CONSTRAINTS:
0 < N < 5000
-N < number value of a square < N

The dice has 6 sides: values are 1, 2, 3, 4, 5, 6.
S and E are unique and always exist.
EXAMPLE:
Input
11
S
1
R
4
3
4
3
-5
2
-4
E
Output
3



 class Task2
    {
        public int N { get; set; }
        List board = new List();

       
        public void Run()
        {
            using (new ConsoleManager("Test_2_input.txt", "Test_2_outputMy.txt"))
            {
                GetData();

                int steps = Go(board, 0);
                Console.WriteLine(steps);

            }
        }

        int Go(List board, int steps)
        {
            Debug.WriteLine("Step {0}: {1}", steps, string.Join(",", board));
            int val;
            Predicate isNumber = s => int.TryParse(s, out val);
            bool boardUpdated = false;
            for (int i = 0; i < board.Count; i++)
            {
                var cell = board[i];
                if (cell == "S" && board.GetRange(i + 1, 6).Contains("E"))
                    return steps + 1;
                else if (cell == "R" && board.GetRange(i + 1, 6).Contains("E"))
                { 
                    board[i] = "E"; 
                    boardUpdated = true; 
                }
                else if (isNumber(cell) && board[i + int.Parse(cell)] == "E")
                { 
                    board[i] = "E"; 
                    boardUpdated = true; 
                }
            }
            if (!boardUpdated) return 0;
            int stepsFinal = Go(board, steps + 1);
            return stepsFinal;
        }

        void GetData()
        {
            string line = Console.ReadLine();
            N = Convert.ToInt32(line);
            for (int i = 0; i < N; i++)
            {
                line = Console.ReadLine();
                board.Add(line);
            }
            Debug.Print("N =" + N + "; " + board.Print());
        }
    }


codingame contest: "Scrabble" task

Task
When playing Scrabble©, each player draws 7 letters and must find a word that scores the most points using these letters.

A player doesn't necessarily have to make a 7-letter word; the word can be shorter. The only constraint is that the word must be made using the 7 letters which the player has drawn.

For example, with the letters  etaenhs, some possible words are: ethanehates,saneant.

LETTER SCORING:
In Scrabble©, each letter is weighted with a score depending on how difficult it is to place that letter in a word. You will see below a table showing the points corresponding to each letter:
LettersPoints
      e, a, i, o, n, r, t, l, s, u   1
      d, g   2
      b, c, m, p   3
      f, h, v, w, y   4
      k   5
      j, x   8
      q, z   10
The word banjo earns 3 + 1 + 1 + 8 + 1 = 14 points.

A dictionary of authorized words is provided as input for the program. The program must find the word in the dictionary which wins the most points for the seven given letters. If two words win the same number of points, then the word which appears first in the order of the given dictionary should be chosen.
All words will only be composed of alphabetical characters in lower case. There will always be at least one possible word.
INPUT:
Line 1: The number N of words in the dictionary
N following lines: The words in the dictionary. One word per line.
Last line: The 7 letters available.
OUTPUT:
The word that scores the most points using the available letters (1 to 7 letters). The word must belong to the dictionnary. There is always a solution.
CONSTRAINTS:
0 < N < 100000
Words in the dictionary have a maximum length of 30 characters.
EXAMPLE:
Input
5
because
first
these
could
which
hicquwh
Output
which



   class Task1
    {
        public int N { get; set; }
        List board = new List();
        public string Letters { get; set; }

        public void Run()
        {
            using (new ConsoleManager("Test_1_input.txt", "Test_1_outputMy.txt"))
            {
                GetData();
                var filtered = board.Where(w => FromLetters(w, Letters.ToCharArray())).ToList();
                var scores = filtered.Select(w => Score(w)).ToList();
                var max = scores.Max();
                var index = scores.FindIndex(score=>score==max);
                if (index >= 0)
                {
                    var word = filtered[index];
                    Console.WriteLine(word);
                }
            }
        }

        bool FromLetters(string word, char[] letters)
        {
            bool yes = true;
            var list = letters.ToList();
            for (int i = 0; i < word.Length; i++)
            {
                var index = list.FindIndex(w=>w==word[i]);
                if (index < 0) { yes = false; break; }
                list.RemoveAt(index);
            }

            
            return yes;
        }

        int Score(string word)
        {
            int score = 0;
            var arr = new String(word.ToCharArray().Distinct().ToArray());
            for (int i = 0; i < arr.Length; i++)
            {
                if ("eaionrtlsu".Contains(word[i])) score++;
                else if ("dg".Contains(word[i])) score+=2;
                else if ("bcmp".Contains(word[i])) score += 3;
                else if ("fhvwy".Contains(word[i])) score += 4;
                else if ("k".Contains(word[i])) score += 5;
                else if ("jx".Contains(word[i])) score += 8;
                else if ("qz".Contains(word[i])) score += 10; 
                 
            }
            return score;
        }

        void GetData()
        {
            string line = Console.ReadLine();
            N = Convert.ToInt32(line);
            for (int i = 0; i < N; i++)
            {
                line = Console.ReadLine();
                board.Add(line);
            }
            Letters = Console.ReadLine();
            Debug.Print("N =" + N + "; " + board.Print());
            Debug.Print("Letters =" + N + "; " + Letters);
        }
    }


воскресенье, 27 октября 2013 г.

Test


public static void Run()
        {
            List numbers = new List();
            string line = Console.ReadLine();
            //int item = 0;
            int n = Convert.ToInt32(line);
            if (n > 0)
            {
                for (int i = 0; i < n; i++)
                {
                    line = Console.ReadLine();
                    numbers.Add(line);
                }
            }

            BuildTree(numbers.Distinct().ToList());

            Console.WriteLine(counter);
        }