Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 2 FirstFirst 12
Results 16 to 23 of 23
  1. #16
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,215
    Thanks
    12
    Thanked 338 Times in 334 Posts
    When you say reference in JavaScript does this imply that the variable ThisObject wouldn't actually take up any space in memory but rather point to ThatObject so if I made a change to ThisObject the change would actually take effect in ThatObject.
    you still need the memory for the reference memory address, but that’s nitpicking.


    Since whatever I hand to this function will be changed because functions pass by reference in JavaScript whereby a classical language you would have to use a symbol to tell the compiler this was a reference such as the & operater in C++.
    not everything is passed by reference, but essentially—yes.
    PHP Code:
    function foo(obj) {
      
    obj.foo "bar";
    }
    // works
    var = { one};
    console.log(x); // Object { one=1 }
    foo(x);
    console.log(x); // Object { one=1, foo="bar" }

    // doesn't work
    var 1;
    console.log(x); // 1
    foo(x);
    console.log(x); // 1 

    (I’ll think about the other issue tomorrow)
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  2. #17
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,324 Times in 4,290 Posts
    JavaScript does *NOT* pass by reference. At least not in the C++ sense of the word. By C++ terms, JavaScript always passes by a CONST reference (not a reference to a CONST, which is completely different).

    It's more correct, actually, to say JavaScript always passes by value.

    But the definition of "value" may seem tricky when it comes to object references.

    The reference ITSELF is what is passed by value. Meaning you can alter the contents of the object by USING that reference. But you can't actually alter the reference.
    Code:
    <script>
    function swap( v1, v2 )
    {
        var temp = v1;
        v1 = v2;
        v2 = temp;
    }
    
    function test( a1, a2 )
    {
        document.write("Before swap, a1 is " + a1 + ", a2 is " + a2 + "<br/>" );
        swap( a1, a2 );
        document.write("After swap, a1 is " + a1 + ", a2 is " + a2 + "<hr/>" );
    }
    
    test( 37, 48 );
    test( "alcatraz", "zamboni" );
    test( [1,"first"], [2,"second"] );
    
    function foo( n, s )
    {
        this.num = n;
        this.str = s;
        this.toString = function() { return "{ num: " + n + ", str: " + s + "}"; };
    }
    
    test( new foo(11,"eleven"), new foo(99,"ninety nine") );
    </script>
    You see? Even using object references, the swap isn't visible outside the swap() function.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  3. #18
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,215
    Thanks
    12
    Thanked 338 Times in 334 Posts
    regarding 2.

    first, the CopyBoard function does something fishy (due to my lack of knowing what all concerned object are (code-wise))
    PHP Code:
    // slight changes to the original code to make it a constructor
    function Solver(board){   
      
    // create a new data board and save it in the Solver object
      
    this.Board = new DataBoard();
      
    // replace all values in this.Board (the newly created data board) with the values in board
      
    CopyBoard(this.Boardboard);

    essentially, what you do is a deep copy (of a part) of an object you pass to the constructor (assuming the DataBoard object has more properties than just .Cells). now if DataBoard is also creating Cells, you let it do work that is not necessary (because they get overwritten anyways). so I would recommend to either split the DataBoard object or if all the above said does not apply, omit CopyBoard.

    ... so they can work independantly of each other and yet pass to each other using the Copy function. This will allow you to generate more puzzles in the background while the Game runs ...
    that’s what you usually use objects for. you create an object instance (e.g. via Constructor) you can work with, and when you need another one, you run the creational code (the object instantiation, a.k.a. Constructor) anew (or in the background) and get independent objects (save the methods, but you don’t want to overwrite those anyways, do you?)

    though currently, I don’t have a clear understanding what Game Solver and Generator do, but assuming from the names I’d probably do
    * Game: the GUI object aka game board
    * Generator: creates playable board data
    * Solver: watches over the game rules
    my strategy (out of the blue)
    - pass an initial playable Board to the client
    - run Generator to create more Boards (maybe to something like a queue)
    - create a Game
    - pass in a Board (from the queue)
    - pass in a Solver instance
    - both Solver and Game can operate on the same Board, no need for a copy here (because then you’d have to synchronise those copies)

    see also the example code at the end that (maybe) demonstrates that a bit.


    This whole parasitic inheritence concept is completely new, ...
    if you don’t like it, leave it be.

    this talk is from 2006 and ECMAScript 5 (which introduced Object.create() (that which he described as the object() function)) is from 2009.


    but I can see his point that people (like me) bringing baggage from other languages into this language only stops them from realizing its full potential.
    then you are one of the few who do.


    this is a typical game design of mine:
    PHP Code:
    <!DOCTYPE html>
    <
    html>
        <
    head>
            <
    title>Tic Tac Toe</title>
            <
    meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <
    meta name="Author" content="Bertold von Dormilich">
            <
    style type="text/css">
    td {
        
    border1px solid black;
        
    width:  2em;
        
    height2em;
        
    text-aligncenter;
        
    vertical-alignmiddle;
    }
            </
    style>
        </
    head>
        <
    body>

            <
    div id="tictactoe"></div>
            
            <
    script type="text/javascript">
    Array.
    prototype.intersect = function (arr) {
        return 
    this.filter(function(item) {
            return (-
    !== arr.indexOf(item));
        });
    };

    var 
    TicTacToe = {};
    TicTacToe.Model = {
        
    players: [],
        
    turn_no0,
        
    current_player: {},
        
    winLines: function memo() 
        {
            if (!
    memo.solution) {
                if (!(
    "size" in TicTacToe.Model)) {
                    throw new 
    Error("Field size not given.");
                }
                var 
    i= [], = [], d1 = [], d2 = [], win = [],
                    
    size TicTacToe.Model.size;
                for (
    0sizei++) {
                     
    h.push(i);
                     
    v.push(size);
                    
    d1.push(* (size 1));
                    
    d2.push(size * (size 1));
                }
                for (
    0sizei++) {
                    
    win.push(h.map(function(item) {
                        return +
    item size;
                    }));
                    
    win.push(v.map(function(item) {
                        return +
    item i;
                    }));
                }
                
    win.push(d1);
                
    win.push(d2);
                
    memo.solution win;
            }
            return 
    memo.solution;
        },
        
    initWithField: function(size
        {
            
    Object.defineProperty(TicTacToe.Model"size", { valuesizeenumerabletrue });
            return 
    TicTacToe.Model.reset();
        },
        
    reset: function()
        {
            var 
    TicTacToe.Model;
            if (
    M.players.length 2) {
                throw new 
    Error("Not enough players.");
            }
            for (var 
    M.players.lengthl--;) {
                
    M.players[l].fields = [];
            }
            
    M.current_player M.players[0];
            
    M.turn_no        1;
            return 
    M;
        },
        
    nextTurn: function() 
        {
            var 
    TicTacToe.Model;
            
    M.current_player M.players[M.turn_no M.players.length];
            
    M.turn_no       += 1;
        },
        
    hasWinner: function() 
        {
            var 
    M      TicTacToe.Model,
                
    fields M.current_player.fields,
                
    winArr M.winLines(),
                
    tempArr;
            for (var 
    winArr.lengthl--;) {
                
    tempArr winArr[l];
                if (
    tempArr.length === fields.intersect(tempArr).length) {
                    throw (
    M.current_player.name " wins!");
                }
            }
        },
        
    isOver: function() 
        {
            var 
    TicTacToe.Model;
            if (
    M.turn_no >= M.size M.size) {
                throw 
    "It’s a draw.";
            }
        }
    };

    TicTacToe.Controller = {
        
    createView: function(size
        { 
            var 
    cellrow
                
    table document.createElement("table"),
                
    count size size;
            
    table.cellSpacing 0;
            
    table.border 1;
            for (var 
    0counti++) {
                if (
    === (size)) {
                    
    row table.insertRow(Math.floor(i/size));
                }
                
    cell row.insertCell(size);
                
    cell.field i+1;
            }
            return 
    table;
        },
        
    initWith: function(model
        { 
            var 
    TicTacToe.Controller;
            
    C.model model;
            
    C.view  C.createView(model.size);
            
    C.view.addEventListener("click"C.action);
            return 
    C;
        },
        
    action: function(evt
        {
            var 
    td evt.target,
                
    C  TicTacToe.Controller;
            if (
    td.textContent.length || td.tagName.toLowerCase() !== "td") {
                return 
    false;
            }
            try {
                var 
    game   C.model,
                    
    player game.current_player;
                
    td.textContent player.symbol;
                
    player.fields.push(+td.field);
                
    game.hasWinner();
                
    game.isOver();
                
    game.nextTurn();
            }
            catch (
    msg) {
                if (
    typeof msg == "string") {
                    
    alert(msg);
                    
    C.quit_game();
                    return 
    null;
                }
                throw 
    msg;
            }
            return 
    true;
        },
        
    quit_game: function() 
        {
            var 
    TicTacToe.Controller;
            
    C.view.removeEventListener("click"C.action);
        }
    };

    TicTacToe.Model.players.push({name:"Player 1"symbol:"X"});
    TicTacToe.Model.players.push({name:"Player 2"symbol:"O"});
    TicTacToe.Model.initWithField(3);
    document.getElementById("tictactoe").appendChildTicTacToe.Controller.initWith(TicTacToe.Model).view );

            
    </script>
        </body>
    </html> 
    note: Model, View & Controller have slightly different meanings in a web-based environment.
    Last edited by Dormilich; 09-06-2013 at 08:38 AM.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  4. #19
    New to the CF scene
    Join Date
    Sep 2013
    Location
    Houston
    Posts
    8
    Thanks
    0
    Thanked 1 Time in 1 Post
    Your strategy is very similar to mine. Though due to my lack of experience in the language my finished product is not going to look nearly as clean as yours, and I have already used new so much as a duct tape to make JavaScript objects function like a class.

    The game works now and I've got plently of cleanup and a few more functions to add to the game.

    http://www.lesshardtofind.com/Sudoku/main.html

    Still to be added is the initial delivery of a pre-made board as I haven't resolved how I was going to make this new board unique day to day without having to manually add new Sudokus and without making the user wait for a new one.

    There is a way using JavaScript to send infromation to my server and maybe store unused sudoku puzzles in a database right?

    Also have to add solution validation and end game conditions. Right now after solving you'd have to refresh the browser to get a new board.

    Your tictactoe solution looks alot cleaner than mine as well lol. Tictactoe was the first game I made in the language though and overall the third app in JS. So of course its going to look ugly in the code. It serves its purpose though and as far as I am aware is glitch free. If you check it out don't yell at me about the globals. I know not to use them and won't with any future projects but I don't see the need to touch up my old stuff lol.

    http://www.lesshardtofind.com/TicTacToe/tictactoe.html

    Thanks a bunch for your info and thoughts Dormilich. It has helped me get a better understanding of the language though I still have much to learn.

    @Old Pendant I apologize I misquoted what I had learned Objects are passed by reference and non-objects are passed by value is the correct way to look at it I believe.

  5. #20
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,215
    Thanks
    12
    Thanked 338 Times in 334 Posts
    The game works now and I've got plently of cleanup and a few more functions to add to the game.
    doesn’t work for me on FF20/Ubuntu (for each() not supported any more, consider using Array.forEach())

    There is a way using JavaScript to send infromation to my server and maybe store unused sudoku puzzles in a database right?
    that’s called AJAX.

    Still to be added is the initial delivery of a pre-made board as I haven't resolved how I was going to make this new board unique day to day without having to manually add new Sudokus and without making the user wait for a new one.
    see above. let the users calculate sudokus (in the background) and send these to your DB, from where you can distribute them.

    Your tictactoe solution looks alot cleaner than mine as well lol.
    it does less (computer does not play) and had a different focus (it can let 4 people play Tic Tac Toe)
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  6. #21
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,028
    Thanks
    75
    Thanked 4,324 Times in 4,290 Posts
    Quote Originally Posted by Lesshardtofind View Post
    The game works now and I've got plently of cleanup and a few more functions to add to the game.

    http://www.lesshardtofind.com/Sudoku/main.html
    ??? Nothing happens on that URL with either Chrome or MSIE 10 browsers.
    @Old Pendant I apologize I misquoted what I had learned Objects are passed by reference and non-objects are passed by value is the correct way to look at it I believe.
    Again, sort of. Just so long as you realize that "by reference" doesn't mean quite the same thing it does in C++. But close enough to think of them that way.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  7. #22
    New to the CF scene
    Join Date
    Sep 2013
    Location
    Houston
    Posts
    8
    Thanks
    0
    Thanked 1 Time in 1 Post
    Ugh. I updated my atiquated firefox 18.02 to 23.0. I am running ubuntu as well I was surprised when it didn't work for you.

    I also removed my for each statements, and made them for statements. Thank you for the bug reports.

    On this note though do you have any effective methods for checking cross browser compatibility and versioning with your code?

    If you guys have time revisit and let me know if it runs now.

    Old Pendant did you have any errors or logs of what didn't execute on your browsers?

  8. #23
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,215
    Thanks
    12
    Thanked 338 Times in 334 Posts
    Quote Originally Posted by Lesshardtofind View Post
    On this note though do you have any effective methods for checking cross browser compatibility and versioning with your code?
    if I have to concern cross-browser compatibility, I use an appropriate framework (mostly jQuery). though most proof-of-concept or personal helper applications are coded specifically for the browsers I use (latest FF/Chrome).

    a neat trick is also to exclude IE specifically by using XHTML. the remaining browsers tend to understand the code then.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


 
Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •