Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

Array of Structs

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>
Avatar of Tom Knowlton
Tom Knowlton
Flag of United States of America image

ASKER

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.
Avatar of Zvonko
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>

SOLUTION
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
function myStruct(){
  this.health = 0
  this. value =0
  this.row = 0
  this.col = 0
}



This is a class in JavaScript?
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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
UPDATE:

Here is Zvonko's code on my web site:

http://www.knowltonfamily.com/robotzweb/test_board.html
I think this gives me the basic building blocks I need.

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

Tom
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>

Okay.
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.

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)}
    }
  }
}


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)}
    }
  }
}
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>