Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by MOROZAW · May 19, 2014 at 03:39 PM · movingtilealgorithm

2048 game moving tiles algorithm question

Hello everybody! I am looking for little help with my project. I have little problem with moving tiles algorithm in my version of 2048 game. It is very pre alpha code, I have a lot of work waiting for me in this project.

My game is storing every tile in GameObject[] table. I could get every tile by position [x,y] translated to index. Every tile have their own script with declared value.

How I could make this moving tile algorithm in proper way?

I found few source codes but I have problem with using it in my project.

I am sorry for polish variable names in project - I added few comments in English.

I think the idea of my code should be clear.

//here is my edited code of engineScript. - thanks Robert for comment!

 using UnityEngine;
 using System.Collections;
 
 public class engineScript : MonoBehaviour {
     public static int cols = 4; //maxX 
     public static int rows = 4; //maxY
     public static int minValue = 2, maxValue = 4;
     private int score = 0;
     private int currentTilesAmount;
     
     public Transform[,] tiles = new Transform[cols,rows];
     public GameObject tilePrefab;
     public float offset = 0.25f;
     
     // Use this for initialization
     void Start () {
         newTile();
         newTile();
     }
     
     // Update is called once per frame
     void Update () {
         if (Input.GetKeyDown(KeyCode.LeftArrow)){
             tilesLeft();
             newTile();
         }
         else
         if (Input.GetKeyDown(KeyCode.RightArrow)){
             tilesRight();
             newTile();
         }
         else
         if (Input.GetKeyDown(KeyCode.DownArrow)){
             tilesDown();
             newTile();
         }
         else
         if (Input.GetKeyDown(KeyCode.UpArrow)){
             tilesUp();
             newTile();
         }
         
     }
     
     void tilesLeft(){
 
     }
     void tilesRight(){
         
     }
     void tilesDown(){
         
     }
     void tilesUp(){
         
     }
     
     //generowanie losowej wartości startowej tiles - działa ok
     //generate random value for new tile
     int newTileValue(){
         int value;
         // find out if we are generating a tile with the lowest or highest value
         float highOrLowChance = Random.Range(0f, 0.99f);
         if (highOrLowChance <= 0.75f) {
             value = minValue;
         } else {
             value = maxValue;
         }
         return value;
     }
     
     //policz ile jest wolnych pozycji - działa OK
     //count of free positions in main table
     int freePositionAmount(){
         int freeSpace = 0, lockedSpace = 0;
         foreach(Transform t in tiles){
             if (t == null)
                 freeSpace++;
             else
                 lockedSpace++;
         }
         currentTilesAmount = lockedSpace;
 
         //number of free space
         Debug.Log("freePositionAmount: ilość wolnych miejsc w tablicy: " + freeSpace); //free space amount in table
         return freeSpace;
     }
     
     //losowanie wolnej pozycji w tablicy - działa OK
     //looking for free random position in table
     void randomFreePositon(out int posX, out int posY){
         //temporary variable for freePositionAmount
         int freeSpaceAmount = freePositionAmount();
 
         //tablica przechowująca wolne pozycje [x,y]
         //table with free position indexes [x,y]
         int[,] freePositions = new int[freeSpaceAmount,2];
         if(freeSpaceAmount > 0){
             int iterator = 0;
             for (int x = 0 ; x < cols ; x++)
                 for (int y = 0; y < rows; y++){
                     if (tiles[x,y] == null){
                     freePositions[iterator,0] = x; //free posX
                     freePositions[iterator,1] = y; //free posY
                     iterator++;
                     }
                 }
             
             //wybór randomowej pozycji w tablicy z wolnymi miejscami
             //select random free position in main table
             int random = Random.Range(0, freePositions.GetLength(0)-1);
             posX = freePositions[random,0];
             posY = freePositions[random,1];
         }
         else
         {
             Debug.Log("randomFreePosition: brak wolnych miejsc w tablicy!"); // there are no free space in table
             throw new UnityException("randomFreePosition: brak wolnych miejsc w tablicy!"); // there are no free space in table
         }
     }
     
     //tworzenie nowego obiektu tiles i dodanie do głównej tablicy kostek - działa OK
     //creating new tile and adding the object into main table
     void newTile(){
         //losowanie wolnej pozycji...
         //looking for free position...
         int x, y;
         randomFreePositon(out x, out y);
 
         //instantiate new tile at [x,y] position with offset
         GameObject tmp_tile = (GameObject) Instantiate(tilePrefab,new Vector3(x+(x*offset)-2,y + (y*offset)-2,0),Quaternion.identity);
 
         //add new tile to table
         if(tmp_tile){
             //przypisz losową wartość początkową 2 lub 4
             //random value for new tile
             tmp_tile.GetComponent<cubeScript>().value = newTileValue();
             
             //dodanie tiles do tablicy
             //add tile to table
             tiles[x,y] = tmp_tile.transform;
             Debug.Log("newTile: kostka została dodana do głównej tablicy!"); // new tile was succesfully added into main table
         }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · May 19, 2014 at 03:55 PM

How I could make this moving tile algorithm in proper way?

The proper way is to use a 2D array rather than a 1D array. So you declare your table:

 public Transform[,] kostki = new Transform[kolumn, wierszy];

Then you'll have to rewrite your dodajKostka to take an x, y and then do the assignment as:

 kostki[x,y] = kostka;

Or even replace dodajKostka with just this line.

With this change, you can get rid of intToXY() and xyToInt(). You can directly access any tile by accessing kostki[x,y]. Note that arrays in C# arrays are 0 based. It appears you are trying to use a 1 based system. I encourage you to think in terms of 0 based arrays. It will make your programming life much easier in the future.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MOROZAW · May 19, 2014 at 04:18 PM 0
Share

Thank You for great reply! I have to admit that I did not check this.. $$anonymous$$y $$anonymous$$cher said "You can not make 2D table of Transform. It is not possible." I will rewrite my code to using 2D array soon. I used 1 based system in my $$anonymous$$d - it was more visual representation of indexing in matrix ([1,1], [1,2]...) as temporary solution. I want in future improve it but yeah - it is good opinion :)

avatar image robertbu · May 19, 2014 at 04:25 PM 0
Share

While a 2D array is the right solution here, it is simple to treat a 1D array as 2D without all of your mappings. So given a 0 based column, row you could do with your existing code:

 Transform t = kostki[x + y * width];

...where 'width' is the width of your table.

avatar image MOROZAW · May 19, 2014 at 10:27 PM 0
Share

Thank You Robert for help. I uploaded updated version of my code in first post - that was not main problem so I decided to edit my code in question.

Here I think all should be clear in my script :)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

20 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Random tile map algorithm 0 Answers

Tile to Sphere world algorithm 1 Answer

My precedural Algorithm for Tidy TileMapper is not working! 3 Answers

Need help with a relatively simple issue. 1 Answer

board game algorithm 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges