Solved

Array of Structs

Posted on 2004-03-29
17
638 Views
Last Modified: 2012-05-04
Can JavaScript support an array of structs?

Here is an example:


struct info
{
   health = 100;
   value = 512;
  row = 2;
  col = 5;
}


//array of info

array info i(100);


i[49].health = 70;

i[50].row = 3;


etc.

etc.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I want to display an HTML table on an ASP page, and then populate that table with info from a database.  Table would be 10 rows X  10 columns.

But then the TABLE CELLS info would be managed by JavaScript at runtime.


A click on cell would select the game piece.  A click on an empty square would move the game piece to that square.  This would all be managed by a JavaScript array of a struct....the struct would contain the info for each cell (health, value, whatever).



Here is a sample game board:

http://www.knowltonfamily.com/robotzweb/game.asp


Here is the current ASP code:


<!--#include File="connections.asp" -->
<!--#include File="gamefunctions.asp" -->


<%

Dim GLOBAL_SQL_Statements(20)

InitSQLArray

'ProcessSQLArray

Dim sInitGame
'Dim moveState
'squareOne = "One"
'squareTwo = "Two"
sInitGame = Request.Form("newgame")
'sInitGame = "New Game"

o_squareid = request("OldSqID")
o_squarehealth = request("OldSqHealth")
o_squareattack = request("OldSqAttack")
o_squareimage = request("OldSqImage")
o_squarevalue = request("OldSqValue")

n_squareid = request("NewSqID")
n_squarehealth = request("NewSqHealth")
n_squareattack = request("NewSqAttack")
n_squareimage = request("NewSqImage")
n_squarevalue = request("NewSqValue")

prod = o_squarevalue * n_squarevalue


'Process Game Action
if request("subform") = "Yes" then
      'Move to a blank square
      if(n_squarevalue=512)then
            'strUp = "UPDATE tblGameBoard, tblGameBoard tb SET tblGameBoard.ValueOfPiece = " & sv & ", tblGameBoard.[Image] = tb.[Image] WHERE tblGameBoard.SquareID="&request("NewSqID")&" AND tb.SquareID = "&request("OldSqID")&";"
            'strUp2 = "Update tblGameBoard set [Image]='blank' Where SquareID = "&request("OldSqID")
            'strUp3 = "Update tblGameBoard set ValueOfPiece ='512' Where SquareID = "&request("OldSqID")            
            
            'Update New Square
            strUpdateNewSquare = "UPDATE tblGameBoard SET [Health] = " & o_squarehealth & ", [Attack] = " & o_squareattack & ", [Image] = '" & o_squareimage & "', [ValueOfPiece] = " & o_squarevalue & " WHERE [SquareID] = "&n_squareid&";"

            'Update Old Square
            strUpdateOldSquare = "UPDATE tblGameBoard SET [Health] = 0, [Attack] = 0, [Image] = 'blank', [ValueOfPiece] = 512 WHERE [SquareID] = "&o_squareid&";"

            
            temp_count = UsedSQLArrayElements()
            Response.Write "Number of SQL statments:  " & temp_count & "<br>"
            GLOBAL_SQL_Statements(temp_count) = strUpdateNewSquare
            temp_count = UsedSQLArrayElements()
            Response.Write "Number of SQL statments:  " & temp_count & "<br>"
            GLOBAL_SQL_Statements(temp_count) = strUpdateOldSquare
            temp_count = UsedSQLArrayElements()
            Response.Write "Number of SQL statments:  " & temp_count & "<br>"
            
            
            ProcessSQLArray
            
            InitSQLArray

      end if
      
      'Is This an Attack?
      'prod<0 means an attack because attacks are always negative (ValueOfPieces multiplied together)
      'prod of 2048 or -2048 means Engineer is pushing a wall
      if( ((prod<0) and (prod > -2304)) and (n_squarevalue <> 512) and (n_squarevalue <> 256))then
            Response.Write new_health & n_squareid & o_squareid & o_squareimage & os_squareattack & o_squarevalue            
            new_health = n_squarehealth - o_squareattack
            
            ProcessAttack new_health,n_squareid,o_squareid, o_squareimage, os_squareattack, o_squarevalue, o_squarehealth            
      end if            
      
      'Medic is Healing own piece
      if((prod = 4) or (prod = 8) or (prod = 32) or (prod = 21) or (prod = 35) or (prod = 63)) then
            if(n_squarehealth < 100) then
                  n_squarehealth = n_squarehealth + 20
            end if
            
            if(n_squarehealth >= 100) then
                  n_squarehealth = 100
            end if
            
            'Update health of game piece
            strUpdateNewSquare = "UPDATE tblGameBoard SET [Health] = " & n_squarehealth  & "  WHERE [SquareID] = "&n_squareid&";"

            Conn.execute(strUpdateNewSquare)
      end if      
      
      
      'Pushing a wall
      if((prod = -2304) or (prod = 2048))then
            osr = fnGetValueFromGameBoard("Row","tblGameBoard","where SquareID=" & o_squareid)
            osc = fnGetValueFromGameBoard("Column","tblGameBoard","where SquareID=" & o_squareid)
            nsr = fnGetValueFromGameBoard("Row","tblGameBoard","where SquareID=" & n_squareid)
            nsc = fnGetValueFromGameBoard("Column","tblGameBoard","where SquareID=" & n_squareid)
            
            dir_to_push = fnDirToPush(osr, osc, nsr, nsc)
            
            move_okay = "no"
            
            if(dir_to_push = "n") and (nsr > 0)then
                  dest_row_for_wall = nsr - 1
                  dest_col_for_wall = nsc                  
                  move_okay = "yes"
            end if
            
            if(dir_to_push = "e") and (nsc < 9)then
                  dest_row_for_wall = nsr
                  dest_col_for_wall = nsc  + 1
                  move_okay = "yes"                  
            end if
            
            if(dir_to_push = "w") and (nsc > 0)then
                  dest_row_for_wall = nsr
                  dest_col_for_wall = nsc - 1
                  move_okay = "yes"
            end if

            if(dir_to_push = "s") and (nsr < 9)then
                  dest_row_for_wall = nsr + 1
                  dest_col_for_wall = nsc
                  move_okay = "yes"
            end if

            if(dir_to_push = "ne") and (nsr > 0) and (nsc < 9)then
                  dest_row_for_wall = nsr - 1
                  dest_col_for_wall = nsc + 1
                  move_okay = "yes"
            end if

            if(dir_to_push = "se") and (nsr < 9) and (nsc < 9)then
                  dest_row_for_wall = nsr + 1
                  dest_col_for_wall = nsc + 1
                  move_okay = "yes"
            end if

            if(dir_to_push = "nw") and (nsr > 0) and (nsc > 0)then
                  dest_row_for_wall = nsr - 1
                  dest_col_for_wall = nsc - 1
                  move_okay = "yes"
            end if
            
            if(dir_to_push = "sw") and (nsr < 9) and (nsc > 0)then
                  dest_row_for_wall = nsr + 1
                  dest_col_for_wall = nsc - 1
                  move_okay = "yes"
            end if

            'Move Wall to new location, move Engineer to where the wall used to be
            'This is effectively "pushing the wall
            if(move_okay = "yes")then
                  PerformMoveWall o_squarehealth, new_wall_sq_id, o_squareattack, o_squareimage, o_squarevalue, n_squareid, o_squareid, dest_row_for_wall, dest_col_for_wall
            end if

            Response.Write "Move Wall"
            Response.Write "<br>old r,c:  " & osr & "," & osc
            Response.Write "<br>new r,c:  " & nsr & "," & nsc
      end if
      
end if

%>

<form name="GameForm" action="game.asp" method=get>

<%
call sbInitGame()

Sub sbInitGame()
      response.Write "Initializing Game"
      response.Write "<br><br><br>"
      response.Write "Game board:   Click a game piece to select it, then click new square to move game piece to"
      response.Write "<br><br><br>"
       set rs=Server.CreateObject("ADODB.recordset")
      rs.CursorType = 3
      sql="select [Row], [Column], [Image], [ValueOfPiece], [SquareID], [Health], [Attack] from tblGameBoard where GameNumber='1' Order by [Row], [Column]"
        rs.Open sql, Conn
      oldRow=""
      %><table border="0" cellspacing="0" cellpadding="0"><%
      if (rs.EOF or rs.BOF) then                
          response.write "No Row in the table<br>"
      else
            do until rs.eof    

                  currentRow = rs("row")
                  currentColumn = rs("Column")
                  currentImage = rs("Image")
                  ValueReadIn = rs("ValueOfPiece")
                  Health = rs("Health")
                  Attack = rs("Attack")
                  
                if (currentColumn = 0) then
                      %><tr><%                    
                end if


                  'A CELL....                  
                  %><td onclick="OnSquareClick(this,'<%=rs("SquareID")%>','<%=currentImage%>','<%=ValueReadIn%>','<%=Health%>','<%=Attack%>')"><img src="images\<%=currentImage%>.jpg"></td><%  

                  if (currentColumn = 9) then
                      %></tr><%                    
                end if

                 rs.MoveNext     'This tells the rows to move to the next row
            loop          'This tells the 'DO UNTIL' to move on and do it all over again.
            rs.close
          set rs=nothing     'Its a really good idea to close recordsets and connections when your done.
      end if                
      %></table><%
End Sub
%>


<!--#include File="closeconnections.asp" -->


Old Square ID:&nbsp;&nbsp;<input name="OldSqID" value="0">
<br>
Old Square Health:&nbsp;&nbsp;<input name="OldSqHealth" value="0">
<br>
Old Square Attack:&nbsp;&nbsp;<input name="OldSqAttack" value="0">
<br>
Old Square Image:&nbsp;&nbsp;<input name="OldSqImage" value="None">
<br>
Old Square Value:&nbsp;&nbsp;<input name="OldSqValue" value="0">
<br>

New Square ID:&nbsp;&nbsp;<input name="NewSqID" value="0">
<br>
New Square Health:&nbsp;&nbsp;<input name="NewSqHealth" value="0">
<br>
New Square Attack:&nbsp;&nbsp;<input name="NewSqAttack" value="0">
<br>
New Square Image:&nbsp;&nbsp;<input name="NewSqImage" value="None">
<br>
New Square Value:&nbsp;&nbsp;<input name="NewSqValue" value="0">
<br>

Sub Form:&nbsp;&nbsp;<input name="SubForm" value="No">
<br>

<br>
<br>
</form>


<script type="text/javascript"  language="Javascript">
var sLastClicked;

function OnSquareClick(theCell, square,imagename,ValueOfItem,Health,Attack)
{
      theForm = document.GameForm;

      SubForm = theForm.SubForm;
            

      if(!sLastClicked)
      {
            OldSquareID = theForm.OldSqID;
            OldSquareHealth = theForm.OldSqHealth;
            OldSquareAttack = theForm.OldSqAttack;
            OldSquareImage = theForm.OldSqImage;
            OldSquareValue = theForm.OldSqValue;

            sLastClicked = theCell;
            OldSquareID.value = square;
            OldSquareHealth.value = Health;
            OldSquareAttack.value = Attack;
            OldSquareImage.value = imagename;
            OldSquareValue.value = ValueOfItem;
          SubForm.value = "No";
        }
      else
      {
            if(sLastClicked == theCell)
            {
                  alert('Clicked same cell');
          }
            else
            {
                  NewSquareID = theForm.NewSqID;
                  NewSquareHealth = theForm.NewSqHealth;
                  NewSquareAttack = theForm.NewSqAttack;
                  NewSquareImage = theForm.NewSqImage;
                  NewSquareValue = theForm.NewSqValue;

                  NewSquareID.value = square;
                  NewSquareHealth.value = Health;
                  NewSquareAttack.value = Attack;
                  NewSquareImage.value = imagename;
                  NewSquareValue.value = ValueOfItem;
                SubForm.value = "Yes";
                document.forms[0].submit();
            }
    sLastClicked = null;
      }
}//End of OnSquareClick

</script>
0
Comment
Question by:knowlton
  • 10
  • 5
  • 2
17 Comments
 
LVL 5

Author Comment

by:knowlton
ID: 10707750
If you can even just build a sample HTML   /   Javascript  page that demonstrates how to do this......I can take that and modify it to suit my needs.

Sort of a "hello world"  page that displays a table with 4 cells and when a cell is clicked the info is stored in an struct.
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10708065
Here an example:

<script>

function info(health, value, row, col){
  this.health = health;
  this.value = value;
  this.row = row;
  this.col = col;
}

var infoarray = new Array(100);
for(n = 0; n<infoarray.length;n++){
  infoarray[n] = new info(100, 512, Math.floor(n/10), n%10);
}

msg = "";
for(p in infoarray[17]){
  msg+=p+": "+infoarray[17][p]+"\n";
}
alert(msg);
</script>

0
 
LVL 31

Assisted Solution

by:GwynforWeb
GwynforWeb earned 100 total points
ID: 10708110
there is no struct data type in javascript. :-(

you must define a class like so eg

function myStruct(){
  this.health = 0
  this. value =0
  this.row = 0
  this.col = 0
}
 and then define objects of the class like so

A = new Array()
for (i=0;i<100;i++)
  A[i]=new myStruct()

now you can say things like A[20].col=30 and A[10].value=10
 

You can also define the class constructor with parameters

 function myStruct(health,value,row,col  ){
  this.health = health
  this. value =value
  this.row = row
  this.col = col
}

and then A[35]=new myStruct(20,10,2,33)
0
 
LVL 5

Author Comment

by:knowlton
ID: 10708126
Zvonko:

How would this work in an HTML page?


This may help you....

http://www.knowltonfamily.com/robotzweb/game.asp


Notice how you can move pieces around the board by clicking the piece and then clicking on a blank square.

I want to do THE EXACT SAME THING......but have JavaScript controlling the piece movement, etc.

~~~~~~~~~~~~~~~~~~~~~~~


I you could give me a tiny demo........one that displays images in a 4 x 4 table and allows me to click an image and move it from one cell to another.....while keeping the cell attributes aligned.....I can take this and integrate it into my game.



Thanks so much,

Tom
0
 
LVL 5

Author Comment

by:knowlton
ID: 10708203
function myStruct(){
  this.health = 0
  this. value =0
  this.row = 0
  this.col = 0
}



This is a class in JavaScript?
0
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 10708272
odd syntax yes and is it the class contructor for the class myStruct, JS is a stippped down intepreter for efficiency and can be weird in places. In reality is a pseudo-OR language.

Concerning the 'a 4 x 4 table example' I gather I am not invited to contribute.
0
 
LVL 63

Accepted Solution

by:
Zvonko earned 400 total points
ID: 10708287
Here a html page demo:

<html>
<head>
<script>
function info(health, value, row, col){
  this.health = health;
  this.value = value;
  this.row = row;
  this.col = col;
}

function getInfo(theInfo){
  msg = "Health: "+theInfo.health;
  msg += "\nValue: "+theInfo.value;
  msg += "\nRow: "+theInfo.row;
  msg += "\nCol: "+theInfo.col;
  alert(msg);
}

function initBoard(){
  var infoarray = new Array(100);
  for(r=0; r<10; r++){
    for(c=0; c<10; c++){
      n = r * 10 + c;
      document.images[n].info = new info(100, 512, r, c);
      document.images[n].src = "images/blank.jpg";
      document.images[n].onclick = function(){getInfo(this.info)}
    }
  }
}

</script>
</head>
<body onLoad="initBoard()">
<table>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
<tr><td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td>
<td><img ></td><td><img ></td><td><img ></td><td><img ></td><td><img ></td></tr>
</table>
</body>
</html>

and yes, you assign an Object (you call Object class or structure) by assigning a init function to an Object.
In front of init function you use the constructir method: new





0
 
LVL 5

Author Comment

by:knowlton
ID: 10708295
UPDATE:

Here is Zvonko's code on my web site:

http://www.knowltonfamily.com/robotzweb/test_board.html
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 5

Author Comment

by:knowlton
ID: 10708299
I think this gives me the basic building blocks I need.

Thank you so much, Zvonko!!!!!!

Tom
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10708321
There is also an Object assignment without "new" constructor and without function definition.
Like this:

<script>

var myObject = { health: 100, value: 255, row: 3, col: 4};

alert(myObject.health);

</script>

0
 
LVL 5

Author Comment

by:knowlton
ID: 10708332
Okay.
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10708386
The last example with curly braces could be seen as structure assignment.
Basicaly is everything in JavaScript an Object.
So you define Object attributes and the attribute values by upper curly braces syntax or by the new function() assignment.

More complex Object in JavaScript have their native construstors, like: new Date(), new String(), new RegExp() and so on.

0
 
LVL 5

Author Comment

by:knowlton
ID: 10708502
Zvonko:

In your code example:


      document.images[n].info = new info(100, 512, r, c);


is referring to just the images inside the table?

what about images outside the table?


function initBoard(){
  var infoarray = new Array(100);
  for(r=0; r<10; r++){
    for(c=0; c<10; c++){
      n = r * 10 + c;
      document.images[n].info = new info(100, 512, r, c);
      document.images[n].src = "images/blank.jpg";
      document.images[n].onclick = function(){getInfo(this.info)}
    }
  }
}


0
 
LVL 5

Author Comment

by:knowlton
ID: 10708530
Can I reference the TABLE only?

Like this????


function initBoard(){
  var infoarray = new Array(100);
  for(r=0; r<10; r++){
    for(c=0; c<10; c++){
      n = r * 10 + c;

//Reference only table images for infoarray????????????

      document.table.images[n].info = new info(100, 512, r, c);
      document.table.images[n].src = "images/blank.jpg";
      document.tableimages[n].onclick = function(){getInfo(this.info)}
    }
  }
}
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10708592
Sorry, that was only for simplicity.

Here a more realistic example:

<html>
<head>
<script>
function info(health, value, row, col){
  this.health = health;
  this.value = value;
  this.row = row;
  this.col = col;
}

function getInfo(theInfo){
  msg = "Health: "+theInfo.health;
  msg += "\nValue: "+theInfo.value;
  msg += "\nRow: "+theInfo.row;
  msg += "\nCol: "+theInfo.col;
  alert(msg);
}

function initBoard(){
  tBody = document.getElementsByTagName('table')[0];
  for(r=0; r<10; r++){
    for(c=0; c<10; c++){
      newImg = new Image();
      newImg.src = "images/blank.jpg";
      newImg.info = new info(100, 512, r, c);
      newImg.onclick = function(){getInfo(this.info)}
      tBody.rows[r].cells[c].appendChild(newImg)
    }
  }
}

</script>
</head>
<body onLoad="initBoard()">
<table>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td><td></td></tr>
</table>
</body>
</html>

0
 
LVL 5

Author Comment

by:knowlton
ID: 10708622
0
 
LVL 5

Author Comment

by:knowlton
ID: 10709028
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now