Search code examples
methodsargumentssmalltalkworkspacepharo

How can i accept argument after invoking a method in transcript on Pharo Smalltalk?


I have created a Game class, and I have a method called Board which must accept stdin of 2 integers, and 1 integer will be assigned to the column variable, and the other integer will be assigned to the row variable. So for example, opening up Transcript on pharo and typing this in:

'Game new board 2 3'

should make column=2 and row =3 but I can't figure out how to do this.

Here is my code attempt

 board

| col rows |

col := stdin nextNumber

rows := stdin nextNumber

Transcript cr; show: col asString, rows asString

THIS DOESN'T WORK. I have to create a board game and I cant even figure out how to accept arguments from the transcript/workspace and I'm screwed it's due next monday!!


Solution

  • Let me show you the idiomatic way. If you type in your playground

    Game newBoardColumns: 2 rows: 3

    and then DoIt and go, a debugger will pop up telling you that that #newBoardColumns:rows:message is not understood by the Game. In your debugger, you have a create button that allows you to add that method. If you select to add it on the class side of Game, you can implement it as something like

    newBoardColumns: aColumns rows: aRows
        ^self basicNew
        initializeColumns: aColumns rows: aRows;
        yourself
    

    That will return a new instance of the Game class, and initialize it with the columns and rows method. If you save that and restart execution in the debugger, it will complain that it doesn't know #initializeColumns:rows: so you'll have to create that in the same way, this time at the instance side of Game.

    initializeColumns: aColumns rows: aRows
        columns := aColumns.
        rows := aRows. 
        self initialize.
    

    when trying to save, make sure to add columns and rows as instance variables. Now you can restart execution again and inspect your Game in the inspector pane.

    To show something in the Transcript, you could type in your playground

    (Game newBoardColumns: 2 rows: 3) show

    and DoIt. That will pop up a debugger again, telling you that #show is not understood. You can implement that in Game as

    show
        Transcript cr; show: columns asString,' ', rows asString