Arrays In Unity UnityScript - class

I am learning from a book on unity and it used this array to store cards.
var aGrid:Card[,];
I understand that :Cards means that it will only hold instances of the Cards class, but I don't understand what the comma in the "[,]" means. There are no "," in my Card class. Can anyone explain to me what this does?
Here is the full code if you need it:
#pragma strict
class Card extends System.Object {
var isFace:boolean = false;
var isMatched:boolean = false;
var img:String;
function Card() {
img = "robot";
}
}
import System.Collections.Generic;
var cols:int = 4; //number of collumbs
var rows:int = 4; //the number of rows in a card grid
var totalCards;int = 16;//4*4=16, there are sixteen slots in our grid for 16 cards
var matchesNeededToWin:int = totalCards * 0.5;//two cards is one match
var matchesMade:int = 0;//At the outset, the player has not made any matches
var cardW:int = 100; // Each card is 100px by 100px
var aCards:List.<Card>;//We'll store all the cards we created in this list.
var aGrid:Card[,];//2d array to keep track of the shuffled, dealt cards
var aCardsFlipped:List.<Card>;//stores flipped cards
var playerCanClick:boolean;//prevent players from clicking wrong buttons
var playerHasWon:boolean = FalseString;//store wether or not the player has won

It would appear from the comment that the [,] notation is to create a 2D array, where presumably [] creates a single-dimension array.
For more information, see How to Write a 2d Array.

Related

Convert GameObject to image?

So I'm making a card game and want my users to be able to create custom cards and not only use them in the game but also be able to print them.
Currently, I'm stuck on converting the UI GameObject of the card into a single image.
The card GameObject has a template card background, several other images (resources, main image, etc), and multiple text boxes (title, type, and description). Then I want to take that card hierarchy and convert it to a single image.
I thought this would be a fairly simple task but it appears to be a non-trivial... Or am I being a melon here?
Good question !
A button calling Capture below upon press and some GameObject image to capture:
Code:
using System.IO;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public GameObject GameObject;
public void Capture()
{
var rectTransform = GameObject.GetComponent<RectTransform>();
var delta = rectTransform.sizeDelta;
var position = rectTransform.position;
var offset = new RectOffset((int) (delta.x / 2), (int) (delta.x / 2), (int) (delta.y / 2), (int) (delta.y / 2));
var rect = new Rect(position, Vector2.zero);
var add = offset.Add(rect);
var tex = new Texture2D((int) add.width, (int) add.height);
tex.ReadPixels(add, 0, 0);
var encodeToPNG = tex.EncodeToPNG();
File.WriteAllBytes("card.png", encodeToPNG);
DestroyImmediate(tex);
}
}
In short, get object rect on screen, copy pixels, voila!
Result:

Moving cards from one list to another

I am having an issue were my trello board won't update from my below code sets the "CurrentCard" to list 4 on my trello board. I looked at Manatee.Trello Moving Cards but i am not sure i am following.
var CurrentCard = Trelloboard.Lists[index].Cards[CardIndex];
CurrentCard.Position = 4;
var otherList = Trelloboard.Lists.Last();//The List to which you want to move the card to.
var CurrentCard = Trelloboard.Lists[index].Cards[0];// The current card you want to move
CurrentCard.List = otherList;//applying the "otherList" to the "CurrentCard"'s List attribute.

How correctly get object by screenshot point coordinates in Unity3d?

I want to make next:
get screenshot from camera
process it with python script and find some points
for each point - find object that projected to this point
Screenshot getting code works well. Python script output has next view:
x=X1 y=Y1 ... \n
x=X2 y=Y2 ... \n
Where 0 <= X1 < screenshot width, 0 <= Y1 < screenshot height.
E.g. in debug mode I can see next image :
As you can see - part of points located on chairs/table projections.
And I need to get this chair/table objects (each object have attached BoxCollider).
I trying to get ray with camera.ScreenPointToRay and Physics.Raycast, but I have wrong output:
private void ApplyClassTextures()
{
var screenshot = GetComponent<Screenshoter>().MakeScreenshot();
Debug.Log(screenshot);
var map = GetComponent<Scenemap>().MakeMap(screenshot);
var objectContours = new Dictionary<GameObject, List<Scenemap.MapContour>>();
var camera = GetComponent<Camera>();
foreach (var item in map)
{
var ray = camera.ScreenPointToRay(new Vector3(item.X, item.Y, 0.0f));
var rayHit = new RaycastHit();
if (Physics.Raycast(ray, out rayHit, raycastHitDistance))
{
var obj = rayHit.collider.gameObject;
if (!objectContours.ContainsKey(obj))
{
Debug.Log(obj);
objectContours.Add(obj, new List<Scenemap.MapContour>());
}
objectContours[obj].Add(item);
}
}
}
And there I can see few floor/wall plane and one chair, but not other and table.

Flash : How to write roll over coding for grid in array which is similar colour movieclips nearby?

Flash AS3:
I just need to know how to check a condition for roll over effect on similar colour movieclips which is near by in a group of random colours movieclips in a grid whereas it is using 2D Array in flash AS3.or
I just need roll over event which i wrote is onBoxOver event function, in that the object which i am targetting is only getting rollover or getting alpha changes. But i need to know how to make rollover for similar colour which are all nearby.
The code which i wrote is below for your reference.
Flash AS3::
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class playGame extends MovieClip
{
public static var totalRowBoxes:Number = 13;
public static var totalColumnBoxes:Number = 12;
public static var rowGap:Number = 30;
public static var columnGap:Number = 30;
public static var totalColorBoxes:Number = 8;
public static var boxCollection:Array = new Array();
public static var boxCollection1:Array = new Array();
public function playGame(theGame:main)
{
// constructor code
addBoxOnStage();
}
private function addBoxOnStage():void
{
var borderCont:Banner = new Banner();
var scoreclipCont:scoreclip = new scoreclip();
addChild(borderCont);
addChild(scoreclipCont);
scoreclipCont.x = 0;
scoreclipCont.y = 0;
createLevel(1);
for (var i:Number = 0; i<totalRowBoxes; i++)
{
boxCollection[i] = new Array(i);
for (var j:Number = 0; j<totalColumnBoxes; j++)
{
var squareCont:square = new square();
squareCont.x = 30 + (i * rowGap);
squareCont.y = 30 + (j * columnGap);
squareCont.name = i + "_" + j;
var boxCollection1:Array = new Array();
boxCollection1[0] = Math.round(Math.random() * 8);
boxCollection1[1] = squareCont;
var boxColour:Number = new Number();
boxColour = boxCollection1[0];
boxCollection[i][j] = boxCollection1[1];
addChild(squareCont);
squareCont.gotoAndStop(boxCollection1[0]);
squareCont.addEventListener(MouseEvent.MOUSE_OVER, onBoxOver); squareCont.addEventListener(MouseEvent.MOUSE_OUT, onBoxOut);
squareCont.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
}
private function onBoxClick(eve:MouseEvent):void
{
}
private function onBoxOver(eve:MouseEvent):void
{
for (var i:Number=0; i< totalRowBoxes; i++)
{
for (var j:Number=0; j<totalColumnBoxes; j++)
{
eve.target.alpha = 0.3;
// trace(boxCollection[i][j].currentFrame)
trace(eve.target);
}
}
}
private function onBoxOut(eve:MouseEvent):void
{
eve.target.alpha = 1;
}
private function createLevel(lvl):void
{
}
}
}
![My Game screenshot here colourbox][1]
Thanks in Advance. Greatly Appreciable for the reply.
Hi this is the image or screenshot of my project. In that image there are 8 colours randomly arranged. whenever i make mouse position or rollover on any box , the condition should check whether the same colour occurs around the box(eg.top, down, left, right) which i am making rollover.
1.If the same colour occur on the top of the box which i am pointing the cursor , the top box and the box which i am pointing both should get less alpha, else only the pointing box should get less alpha. this is my concept friends. please go through the image and let me know if u have any doubts.
I am still unsure what you mean by 'nearby'. (neighbour tiles? adjacent of similar colour?...)
If 'nearby' means adjacent, you need to read about flood fill algorithms. There is a good wiki article about this. You would use that to crawl through the list of tiles similar enough to trigger the effect you want.
I also don't know what 'similar' colour means in your project. You will need a method to determine weather two colours are similar. There is a stackoverflow question re: similar colour detection. It has a good answer to start you out in your research. look here.

Pure ActionScript 3.0 - Memory Game

I'm a beginner of ActionScript 3.0. I'm making a simple memory game, the tool I'm using is Eclipse with flexsdk plugin. Right now I've done the shuffle and display images, and the cover of the images as well.
My idea is when clicking on the image, the cover will remove and show the image behind of it. After 2 covers are gone, the game will compare and check whether the selected images are match or not, if match both of the images will remain, otherwise the cover will reappear and the game keeps going on. If all of the images are match, a winning line will appear.
The problem I'm facing is I got no idea on how to deal with the images comparison part. I wanted to compare with the index number of array or the name of the images, but I really don't have any idea. I've refer some examples but all of them are develop in CS3 and uses the timeframe which is not exist in pure ActionScript.
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import myclasses.Cover;
public class Prototype extends Sprite {
protected static const WIDTH:int=3;
protected static const HEIGHT:int=2;
protected static const SPACINGX:int=100;
protected static const SPACINGY:int=74;
protected static const OFFSETX:int=96;
protected static const OFFSETY:int=100;
protected static const SIZE:Number=100;
protected static const COLOUR:uint=0x999999;
[Embed(source="images/pic1.jpg")]
protected static const PIC1:Class;
[Embed(source="images/pic2.jpg")]
protected static const PIC2:Class;
[Embed(source="images/pic3.jpg")]
protected static const PIC3:Class;
protected var imagesList:Array=[PIC1,PIC1,PIC2,PIC2,PIC3,PIC3];
protected var X:int;
protected var Y:int=27;
protected var count:int;
//protected var firstTap:Class;
//protected var secondTap:Class;
public function Prototype() {
var shuffled:Array = shuffleList(imagesList.length);
for(var i:int; i<imagesList.length; i++) {
//var colour:uint;
//colour=0x999999;
var j:int = shuffled[i];
var thing:Sprite=new Sprite();
thing.addChild(new imagesList[j]());
thing.x=X;
thing.y=Y;
addChild(thing);
new Cover(this,X,Y,SIZE,COLOUR);
X=X+SPACINGX+OFFSETX;
count++;
if(count == WIDTH){
Y=Y+SPACINGY+OFFSETY;
X=0;
}
addEventListener(MouseEvent.MOUSE_DOWN,selectImages);
}
}
public function selectImages(event:MouseEvent):void {
//(P/S: this is not the actual code)
var target:Sprite = Sprite(event.target)
if(firstTap == null){
firstTap = ; //1st selected image
removeChild(target);
}else if(secondTap == null){
secondTap = ; //2nd selected image
if(firstTap == secondTap){
firstTap = null;
secondTap = null;
}else{
//firstTap = ; //cover back
//secondTap = ; //cover back
secondTap = null;
firstTap = ; //selected another image
}
}
}
protected function shuffleList(n:Number):Array {
var startList:Array = new Array(n);
var endList:Array = new Array(n);
var i:Number, j:Number;
for (i=0; i<n; i++) {
startList[i] = i;
}
for (i=0; i<n; i++) {
j = Math.floor(Math.random()*startList.length);
endList[i] = startList.splice(j,1)[0];
}
return(endList);
}
}
}
Please help me figure out. Thanks.
Well I didn't really go through your code in details, but from looking at it, it seems you are making things really complex. So let me give you a hint in how I would do it...
1) First I would make a 'card' class, which extends sprite or bitmap, mainly containing the image of that card, image of the cover/mask, some animtion methods like hide/show e.t.c, and possibly an 'id' variable to recognize it later, though that is not needed. You can also get away with the array you have, and in that case, skip step 2.
2) Now push two copies of each card in an array.
example [new card('c1'),new card('c1'),new card('c2'),new card('c2'),.....].
3) Now comes the part where you made it most complex, that is, the shuffling of the array. Let's write a custom function for it, shall we?
function shuffleArr(arr):Array
{
var len:int = arr.length();
for(var i:int=0; i<len; i++)
{
//Swap the value at i with a random value within the array;
var tmp_pos:int = Math.floor(Math.random()*len);
while(tmp_pos==i)
{
tmp_pos = Math.floor(Math.random()*len);
}
var tmp_var:card = arr[tmp_pos];
arr[tmp_pos] = arr[i];
arr[i] = tmp_var;
}
}
4) Now that the array is shuffled, you simply have to lay them out in a grid.
for(var row:int=0; row<6; row++)
{
for(var col:int=0; col<6; col++)
{
card_arr[i].x = card_arr[i].width*cols+5;
card_arr[i].y = card_arr[i].height*row+5;
stage.addChild(card[i]);
}
}
5) Now you have to check for user click and take action, and there are many ways to do it, but I will tell one of them...
a) Give the cards a click event handler, this becomes easy if the cards are a class, or you can look into event.target property and use a general click handler. it's up to you.
b) On click, push the card's id in an array. If you did make them into a class, their ids should now be, c1, c2, e.t.c, and you can do
holder_arr.push(this);
this.removeCover();
6) Now you have to make sure, that the holder array can only hold two values at a time. Then do the checking. I am writing a semi-pseudo code with a lot of assumed functions and values:
//Insert
if(holder_arr.length()==2)
{
//flip back the cards and empty the array
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr = [];
}
holder_arr.push(this);
...
..
7) For checking make a function and run it every time a card is clicked, and also when a timer ends, to flip back the cards.
function checkCards()
{
if(holder_arr.length==2)
{
if(holder_arr[0].id==holder_arr[1].id)
{
//the cards match
holder_arr[0].vanishAnim();
holder_arr[1].vanishAnim();
holder_arr=[];
}
else
{
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr=[];
}
}
}
Obviously you will remove the cards from the actual card_arr too, but when to do that is up to you to figure out ;)
Personally , I find the problem has more to do with the way you shuffle your cards as it makes it a bit more difficult to identify what card is what.
Let's say for instance that instead of shuffling your embed assets , you were first creating your cards , naming them after the image they add , then creating an Array ( or Vector ) of cards and shuffle that Array ( or Vector ), identifying the cards would be fairly easy since you'd only have to compare their name property.
//PSEUDO CODE
- create Array ( Vector ) of embed assets [PIC1, PIC2 , PIC3]
- create cards and use Array ( Vector ) index to identify
each card with the name property
- create a set of six cards
- shuffle set