searchQuick Apprise: EIGHT #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header


Bringing up to the rear of the summers, the project was brought to a penultimate stage by achieving the following tasks:

    • Handling empty string searches by raising error pop ups.
      searchButtonClicked
      searchBar accept .
      (myString isEmptyOrNil  ) 
      ifTrue: [self errorPopUp ] 
      ifFalse: [ 
           myString := searchBar getText asString .
                self printSearchResults
                     ] .
    • Adding Help, About and Feedback sections to give an authentic application look and required details to an interested developer.
    • Inserting ScrollPane for BrowseFile list menu
      browseScroll := ScrollPane new.
      browseScroll scroller addMorph: browse.
    • Truncating BrowseFile list menu file titles to have their extent within the #MenuMorph: boundary
      title := anObject truncateWithElipsisTo: 25. 
    • Removal of OK/CANCEL buttons from the Search results accordion widget
      dialog buttons: {}.
    • Implementation of a Search Bar for searching via Search results accordion widget.
    • Categorizing methods as: accessing, initializationsubmorphsadd/remove etc.
    • Removal of unwanted/redundant/commented code lines i.e. scrubbing dead-code.

UPCOMING: Wrap Up.


Continue ReadingsearchQuick Apprise: EIGHT #GoogleSummerOfCode #FOSSASIA

[Tutorial] Continuous Integration Automated Build for your Pharo Application

reposted from jigyasagrover.wordpress.com/ci-automated-build-for-your-pharo-application

Hello Fellas !

This post aims to put forward the basics of Build Automation and also brief the steps required to put up a Pharo application on Continuous Integration, Inria which is a platform for Scheduled Automated Build.
For simplicity, Build automation is the act of scripting or automating a wide variety of tasks that software developers do in their day-to-day activities including things like:
  • compiling computer source code into binary code
  • packaging binary code
  • running automated tests
  • deploying to production systems
  • creating documentation and/or release notes

Various types of automation are as:

  • On-Demand automation such as a user running a script at the command line
  • Scheduled automation such as a continuous integration server running a nightly build
  • Triggered automation such as a continuous integration server running a build on every commit to a version control system.
In recent years, build management tools have provided relief when it comes to automating the build process.
The dominant benefits of continuous integration include:
  • Improvement of product quality
  • Acceleration of compile and link processing
  • Elimination of redundant tasks
  • Minimization of ‘bad builds’
  • Have history of builds and releases in order to investigate issues
  • Save time and money – because of above listed reasons.

A build system should fulfill certain requirements.

Basic requirements:

  1. Frequent or overnight builds to catch problems early.
  2. Support for Source Code Dependency Management
  3. Incremental build processing
  4. Reporting that traces source to binary matching
  5. Build acceleration
  6. Extraction and reporting on build compile and link usage

Optional requirements:

  1. Generate release notes and other documentation such as help pages
  2. Build status reporting
  3. Test pass or fail reporting
  4. Summary of the features added/modified/deleted with each new build

Considering the above mentioned advantages of automated build, the below enlisted steps will help to put up your own Pharo application hosted on github on the CI server for continuous integration/scheduled build.
 1. Log on to Continuous Integration, Inria website (https://ci.inria.fr/).

Screenshot from 2015-08-08 15:53:49
2. Click on ‘Sign Up‘ at the top-right corner, enter the required details and register for CI.

Screenshot from 2015-08-08 15:54:02
3. From the ‘Dashboard‘ option located at the top most of the screen click on ‘Join an existing project‘ blue button as shown .

Screenshot from 2015-08-08 15:59:22
4. Search ‘pharo-contribution‘ in the enlisted public projects and click on ‘Join

5. On clicking the ‘Join‘ button, a message stating: “Request to join the project ‘pharo-contribution’ sent.” appears.

6. It might take a day or two for the request approval mail to deliver at your registered Email ID.

The E-Mail content is as follows:
        Your request to join pharo-contribution has been accepted
        Hi _ _ _,
        Your request to join the project pharo-contribution has been accepted !
        Regards,
        Support team.

7. Click on ‘My Account‘ option and under ‘My Projects‘ check the status of pharo-contribution project. It should state ‘member‘.

Screenshot from 2015-08-08 16:17:55
8. Now, visit the LINK: https://ci.inria.fr/pharo-contribution/job/JobTemplate/  to create a ‘New Job

Screenshot from 2015-08-08 16:21:06
9. Read all the steps mentioned carefully. After going through all the points, click on the ‘New Job‘ mentioned in point 2 on the Project Job Template web page.

10. Enter the ‘Project Name‘ in the ‘Item Name: ‘ box and choose ‘Copy from existing item‘ option and fill ‘JobTemplate

Screenshot from 2015-08-08 16:30:01
11. After clicking OK, You will be directed to your project configuration.

12. Fill in the description of the project in the desired box.

Screenshot from 2015-08-08 16:32:31
13. Fill int the configuration details of your project like:

* Maximum number of builds
*  Link to GitHub Project
*  Source Code Manager
* Build Triggers
*  Schedule of build (@hourly, @daily, @weekly, @fortnightly, @monthly, @yearly etc.)
*  Configuration Matrix (User Defined Axis: Name && Version Values- stable, development etc.)
* Build environment options
* Post-build actions
*  Report regressed tests

14. The main task is to carefully write the commands in the ‘Execute Shell
The default commands are as:

Screenshot from 2015-08-08 16:39:06
15. After saving and applying the changes, the application is all set for automated build.

16. Each build’s ‘Console Output‘ can be used to analyse the steps and highlight the weak areas of the project.
For instance: The below output is of a project whose stable version build was successful.

Screenshot from 2015-08-08 16:49:05

TIP: Keep a regular tab on the build results and analyze each line of the Console Output with utmost care.

Hope this post was able to help you start with the automation build process of Pharo Application.

Do like if it was worth a read !
Post queries/suggestions as comments 🙂 Looking forward to them.


UPCOMING: Next, I plan to share experience of putting up my Pharo application searchQuick on CI Inria for automated build. I intend to detail about the various configuration settings applied along with the Execute Shell commands utilized for a GitHub project 🙂


Introduction Accredits: Wikipedia 
Resources:  Build Automation and Continuous Integration .


Continue Reading[Tutorial] Continuous Integration Automated Build for your Pharo Application

searchQuick Apprise: SEVEN #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header


After the chief tasks of search functionality and automated build were done with, the next undertaking included working on finer details and embellishments.

  • Embedding Jenkins automated build status icon in GitHub markdown file
  • Relative widget re-sizing by using ‘World extent x‘ and ‘World extent y‘ co-ordinates instead of hard coded co-ordinates
  • Modifying the Accordion Widget by addition of ‘Search Bar‘ at the top
  • Checking for duplicates in the ‘Browse Files‘ menu, thus reducing the CPU consumption
  • Equalizing the sizes of all the windows to bring uniformity
  • Addition of ‘Scroll Pane‘ in accordion search result display list
  • Multi-line search result display by extending the Expander Title Morph and use of new line character in labels (otherwise not supported by default)
  • Truncating file content to first n characters for neater look in Expander Title

Latest Screenshot of Accordion Widget:
Screenshot from 2015-08-18 18:38:06
UPCOMING:

  • Removal of OK & CANCEL buttons (present by default in Pluggable Dialog Window) from Accordion Widget
  • Implementing of Search via the result window as well
  • Relative re-sizing of background images (Image Morphs)

Continue ReadingsearchQuick Apprise: SEVEN #GoogleSummerOfCode #FOSSASIA

searchQuick Apprise: SIX #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header



The main task achieved was putting up the application up on Continuous Integration, Inria for automated build. It was indeed a beneficial idea as it helped me keep a check on the builds and work on issues.
Being a newbie, this work was cumbersome initially but with the help of my mentors and the #pharo community, I was able to accomplish it. To assist fellow Pharo-ers, I have compiled all the information regarding CI Automated Build for yout Pharo Application and published the same on my blog-spot. Kindly go through it for a complete understanding 🙂

Other tasks completed as of now include:

  • Putting up the project for automated build on https://ci.inria.fr/
  • Successful ‘stable’ and ‘development’ version builds
  • Accessing resource folder via MCGitHubRepository, Removal of manual download option
  • By default full screen system window open
  • Removing redundant code by creating open argument methods
  • Abolishment of hard-coded font family and font point size
  • Categorization of methods & classes
  • GUI Embellishment with background colors, borders etc.

Upcoming: 

  • Dynamic widget re-sizing
  • Multi-line search result title
  • Putting up Help and About sections
  • Removal of old configurations

Continue ReadingsearchQuick Apprise: SIX #GoogleSummerOfCode #FOSSASIA

searchQuick Apprise: FIVE #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header



As the rudimentary structure of the application is sewn up, embellishment of GUI and rigorous testing are the major part of course of action.
On eMBee’s ( +Martin Bähr ) suggestion to build up an accordion widget to display the search results, various trials were conducted to design a similar one in Pharo.

The task of developing the accordion widget in Pharo was achieved using Expander Morphs. Looping through the search results array, a #newExpander: was added in each #newRow: of the modal built.

A challenging chore was to add a scroll-able content on the click of the desired search result expander. Sundry experiments with #newLabel: and #newText: in #newScrollPaneFor: {i.e. adding text model and labels in scroll pane} had no effect. Eventually, #newTextEditorFor: did the trick and the desired look was created.
Next on the cards is putting up sQuick for automated build on the CI Server, as suggested by +Sean DeNigris for its various advantages which include:
  • Improvement of product quality
  • Acceleration of compile and link processing
  • Elimination of redundant tasks
  • Minimization of ‘bad builds’
  • Have history of builds and releases in order to investigate issues
  • Save time and money – because of above listed reasons.
For simplicity, Build automation is the act of scripting or automating a wide variety of tasks that software developers do in their day-to-day activities including things like:
  • compiling computer source code into binary code
  • packaging binary code
  • running automated tests
  • deploying to production systems
  • creating documentation and/or release notes
UPCOMING:
To achieve Build Automation for sQuick, I have already registered on CI and configured sQuick.
Next endeavor is to look into the red signal in the build evaluation.
 

Stay tuned for more….Post any queries, will be happy to help 🙂
Continue ReadingsearchQuick Apprise: FIVE #GoogleSummerOfCode #FOSSASIA

Intriguing Read (Bootstrapping Reflective Systems: The Case of Pharo)

Hiya Fellas 😀

So, while I was browsing through various developments in Pharo, I came across a very eye-catching paper on Bootstrapping Reflective Systems: The case of Pharo .

For beginners, Bootstrapping is basically the process of writing a compiler or an assembler in the source programming language in which it is intended to compile. Applying this technique leads to self-hosting compiler that proceeds without external input.

Though, I am still a newbie and in the process of grasping all this ingenious stuff.
But I am sure that this paper ( Poli12-BootstrappingSmalltalk-SCP ) by G. Polito , S. Ducasse , L. Fabresse , N. Bouraqadi , B. van Ryseghem would make for an interesting read.

Do scan through it and post below your ideas and queries !


Continue ReadingIntriguing Read (Bootstrapping Reflective Systems: The Case of Pharo)

Pharo Launcher : What? How? #PharoInProgress

reposted from jigyasagrover.wordpress.com/pharolauncher-tutorial-what-how-pharoinprogress

This tutorial has been included as a chapter in  Pharo In Progress.



This post aims to provide a basic overview of what PharoLauncher is and give a step-by-step approach on how to use this application of great advantage.

Overview

Pharo is an open source implementation of the programming language and environment Smalltalk. Pharo is not Smalltalk. Pharo is Smalltalk-inspired.

Pharo offers strong live programming features such as immediate object manipulation, live update, and hot recompilation. Live programming environment is in the heart of the system. Pharo also supports advanced web development with frameworks such as Seaside and more recently Tide.

The official Pharo website defines it as: ”Pharo is a pure object-oriented programming language and a powerful environment, focused on simplicity and immediate feedback (think IDE and OS rolled into one). ”

Pharo relies on a virtual machine that is written almost entirely in Smalltalk itself. Pharo environment is its own little world, designed around a conception of a computer with a minimal operating system and populated with living objects. A Smalltalk implementation is composed of an image (binary code), a major source file and a ‘changes’ file. The image is called Virtual Image (VI) because is independent of the platform you use for running Smalltalk. Smalltalk systems store the entire program state (including both Class and non-Class objects) in an image file. The image can then be loaded by the Smalltalk virtual machine to restore a Smalltalk-like system to a prior state.

As Pharo is open source, it growing rapidly owing to the contributions of people all around the world. Each day we have a new update of the image of Pharo which makes it cumbersome to keep track of updates. It becomes quite a task when one has to download a new image seperately each he/she plans to work on something having the latest issues fixed, new features added etc. That’s where the PharoLauncher comes in the picture. Pharo Launcher, a cross-platform application that

  • lets you manage your Pharo images (launch, rename, copy and delete);
  • lets you download image templates (i.e., zip archives) from many different sources (Jenkins, files.pharo.org, and your local cache) and create new images from any template.

The idea behind the Pharo Launcher is that you should be able to access it very rapidly from your OS application launcher. As a result launching any image is never more than 3 clicks away. “PharoLauncher” is useful to a user who develops and needs to constantly switch between images. PharoLauncher is also a very handy tool to download specific image update versions if you want to reproduce or fix Pharo bugs.Pharo Launcher is a Pharo-based application allowing you to manage a list of images (download, rename, delete) and switch between them without aditional tools.

Downloading/Installing PharoLauncher

As discussed earlier about the rapid evolvement of Pharo , kindly check out http://www.pharo.org/download to get the latest download/install instructions for Pharo Launcher.

Linux Ubuntu:

(http://pharo.org/download#ubuntu) Ubuntu users can use the dedicated ppa to install Pharo

sudo add-apt-repository ppa:pharo/stable
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install pharo-launcher

If you don’t have the add-apt-repository command, install the software-properties-common package and try again. If you are on a server (no GUI), you can get a Pharo Virtual Machine by installing pharo-vm-core.

On Ubuntu, the Launcher is installed as /usr/bin/pharo, so you can type the following command on the terminal to start the Pharo Launcher.

pharo 

ArchLinux :

(http://lists.pharo.org/pipermail/pharo-users_lists.pharo.org/2014-March/010932.html)

$ yaourt pharo-vm-latest
$ pharo /path/to/your/image

There’s also a pharo-launcher package that depends on pharo-vm:

$ yaourt pharo-launcher
$ pharo-launcher

Windows:

Download and install the executable from the link provided here.

MacOS:

Use the link (http://files.pharo.org/platform/launcher/latest.dmg)to install Pharo Launcher on Mac system. After installation , you’ll observe that the Launcher is installed in /Applications.

Using PharoLauncher

Launch the Pharo launcher image using the platform-specific VM. The image below depicts how a PharoLauncher looks like when it is opened.

pharolauncher_edited_new

The screen displayed initially has been divided into two parts.

The left part ‘Existing Images’ displays the images already created by the user. Initially after the installation the left side with local images is empty. Whereas the the right side is the ‘Templates’ section which displays the image templates from various resources available for download from the internet. The ‘Existing Images’ section has 3 buttons : Launch, Delete and Refresh. The ‘Templates’ section has 2 buttons : Create Image and Refresh.

At the bottom of the launcher we have the buttons for quit and settings.

Select the image you wish to work on from the list and the sources provided in the ‘Templates’ section and download it. For instance you can download “Pharo4.0 (beta)” from the options provided which is the latest image as of today. By clicking on the ‘Create Image’ button at the top right corner.

Note that also the images from contribution CI are available. So you can easily download “Artefact”, “Moose”, … images according to your choice.

It will download the image into a specific directory somewhere in your users home directory. Each image gets an own folder. Use the “Show in folder” menu item to open this location.

The location of the images can be changed through the ‘Settings Browser’ option located at the bottom-right corner. Go to the ‘Open Settings’ > ‘Location of your images’. Now enter the desired path in the place provided as shown in the figure.

location

After ‘Creating an image’ , a dialog box appears which asks you to give a name to the image as shown in figure below.

rename

After entering the suitable name , the image is displayed in the ‘Existing Images’ section.

myimage

To launch the image, simply select your option and click on the ‘Launch’ button located at the top right corner of the ‘Existing Images’ section and voila ! You have the pharo image of your choice running with the name of your choice.

myimg

You could watch this video on Pharo Launcher by Kilon Alios to get a clearer view (https://www.youtube.com/watch?v=fNim2Yxs320) Resources to explore further:

Do like the post if it was helpful. For any queries/suggestions please comment below. Thank You

Continue ReadingPharo Launcher : What? How? #PharoInProgress

searchQuick Apprise: FOUR #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended “searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header



After indexing the content and the next task that was covered was searching for the user input string. The #queryString: does a fantastic job as of now.
The search results were printed in a scroll-able pane by iterating through a loop so as to cover each and every existence of the desired string. The search results window also enables the user to view the content of the chosen file.

02Search Results Display

Acting on the suggestion of my mentor, I have also loaded the Pharo image with text versions of large books (Thank You Project Gutenberg 🙂 )  to test the working of the search function.

UPCOMING

  • GUI Modification
  • Integrated Exhaustive Testing
  • Addition of help/tutorial

PS: The GUI of the application is under constant evolvement, Kindly ignore the poorly structured window 😛

Stay tuned for more…
Post any queries , will be happy to help 🙂


Continue ReadingsearchQuick Apprise: FOUR #GoogleSummerOfCode #FOSSASIA

searchQuick Apprise: THREE #GoogleSummerOfCode #FOSSASIA

banner-gsoc2015.png.pagespeed.ce.1-XG35qq3R8SQJ5DGgL9

The intended “searchQuick” (sQuick) is an application to enable a user to search a set of books or texts, like an encyclopedia, or some other topical book collection offline built in the open source platform Pharo 4.0.

header



After the GUI was designed with minimal features, the next task was to develop the cardinal search function.

Indubitably, a well-run search application/engine requires indexing.

Search Application/Engine Indexing basically collects, parses and stores data to facilitate fast and accurate information retrieval.

That being, the index for sQuick was built using the Dictionary data structure in Pharo which works like HashTable of other programming languages/platforms.

index := Dictionary new.

Pharo describes a Dictionary as: “I represent a set of elements that can be viewed from one of the two perspectives: a set of associations, or a container of values that are extremely named where the name can be any object that responds to =. The external name is referred to as the key. I inherit many operations from the Set. “

The contents of the text files present in the current Pharo image were split at whitespaces and added to the index along with the corresponding file title.

tokens := ‘ ‘ split: aDocument contents.

The method #indexFiles was used to iterate over all the text files in the current Pharo image to index all the files before the searching begins.

Index

Dictionary Entries after File Content Indexing

The #queryString method has been temporarily build using #includesSubstring which matches the user input string with all the entries of the index and gives the result in an array form with #tally output as the number of search results.

Various test methods are now built to inspect the functioning of the methods designed. Continuous debugging is being done to check out and remove errors, if any 😉

UPCOMING:

  • Improve the indexing technique
  • Explore methods to quicken the search functionality
  • Integrate the search routine with the GUI already built
  • Design more test cases to develop a bug-free application

Stay tuned for more…
Post any queries , will be happy to help 🙂


Continue ReadingsearchQuick Apprise: THREE #GoogleSummerOfCode #FOSSASIA

TicTacToe Tutorial #FunWithPharo

reposted from jigyasagrover.wordpress.com/tictactoe-tutorial-funwithpharo

This tutorial has been included as a chapter in  Fun With Pharo!



Tic-tac-toe (or Noughts and crosses, Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three respective marks in a horizontal, vertical, or diagonal row wins the game.

Because of the simplicity of Tic-tac-toe, it is often used as a pedagogical tool for teaching the concepts of good sportsmanship and the branch of artificial intelligence that deals with the searching of game trees. It is straightforward to write a computer program to play Tic-tac-toe perfectly, to enumerate the 765 essentially different positions (the state space complexity), or the 26,830 possible games up to rotations and reflections (the game tree complexity) on this space.

t

So , here we make a Pharo version of this well-known game by using Morph. This post provides a step-by-step approach on how to go about building this simple application.

TTT2

A game package will be built having 3 subclasses :

  • TicTacToe
  • TicTacToeCell
  • TicTacToeModel

Initially , we have created TicTacToe a subclass of the Object class. The subclasses we will make will be combined in the package game as mentioned in the category: parameter.

Object subclass: #TicTacToe
instanceVariableNames: 'container model'
classVariableNames: ''
poolDictionaries: ''
category: 'game'

A category name is not required in order for the class to work, but you will not be able to access the class to make changes or to look at existing code unless you provide a category name. (The category name used can be a new category name or the name of an existing category.)

The poolDictionaries: parameter is seldom used and will not be discussed here, and the category: parameter specifies the category under which this class will be grouped in the system browser.

As we know, a class encapsulates data values and methods, and every object contains a set of the data values and can receive any of the methods as a message. The data values in each object are specified by providing a set of names of variables whose values will be an object’s internal data values. Each object has its own set of these values, and the set of data values for an object represents the object’s state (or value). The variables that contain the data values of an object are called the instance variables for the object, and the instanceVariableNames: parameter is a list of names, separated by blanks, for the instance variables. In the above code snippet , we have declared container and model as two instanceVariables.

The classVariableNames: parameter lists the identifiers that are the names of variables shared by the class and all of its objects. That is, there is only one set of these, and they are used by the class and all of its objects. Class variables (so called because they belong to the class, of which there is only one, rather than to the objects that are instances of the class) are rarely needed.

An example of a class variable that could be useful is in a case where we wanted a unique “serial number” to be assigned to each instance of the class as it is created. The variable containing the next available (or last used) serial number would appropriately be a class variable, and each time a new instance (object) is created the serial number would be recorded as an instance variable value in the object and the serial number in the class variable would be incremented. Thus, each object can be serially numbered as it is created (without using one of those nasty global variables!).

After executing the code above, class TicTacToe will exist. However, it will have no methods other than those that are inherited from class Object. To make it useful, we must add the methods that are needed for our implementation.

Adding methods to classes :

The subClasses interact by passing messages through objects only.

TicTacToe>>#initialize 
container := Morph new 
              layoutPolicy: TableLayout new; 
              color: Color transparent.
model := TicTacToeModel new:3.
self addRows.
self addControls.
^self.

The notation TicTacToe>>#initialize means that we have a method named initialize in the subclass TicTacToe.

In the initialize: method above , we have a container which is the instance of the class Morph (Morphic is the name given to Pharo’s graphical interface. ). We define the various attributes of the container such as layoutPolicy: and color:. model is another instance of the class TicTacToeModel which we will be creating further in this example.

self refers to the receiver of the message. It is usually used within a method to send additional messages to the receiver. self is frequently used when it is desired to pass the sender object (self), as a message argument, to a receiver who requires knowledege of the sender or who will in some way manipulate the sender.

In short, self refers to the object itself that defines the method.

TicTacToe>>#addRows
| rowMorph aCell rowCol |
1 to:3 do:[ :row |
rowMorph := Morph new layoutPolicy: RowLayout new.
1 to: 3 do: [ :col |
aCell := TicTacToeCell new.
aCell setModel: (model) row: row col: col.
rowMorph addMorph: aCell.
].
container addMorph: rowMorph.
]

The method addRows (the name is self explanatory) is used to add rows in the Tic Tac Toe grid. It declares temporary (local) variables rowMorph , aCell and rowCol which can’t be used beyond this method.

1 to:3 do:[ :row |

rowMorph := Morph new layoutPolicy: RowLayout new.

1 to: 3 do: [ :col |

aCell := TicTacToeCell new.

aCell setModel: (model) row: row col: col.

rowMorph addMorph: aCell.

].

The above code snippet works as a nested loop that runs thrice for each three rows to create a 3X3 grid as per requirement.

TicTacToe>>#addControls
| rowMorph newGameButton exitGameButton |
rowMorph := Morph new 
             layoutPolicy: RowLayout new; 
             color: Color transparent.
newGameButton := self createCtrlLabelled: 'New'    onClickExecutes: [self restart].
exitGameButton := self createCtrlLabelled: 'Exit'  onClickExecutes: [container delete].
rowMorph addMorph: exitGameButton.
rowMorph addMorph: newGameButton.
container addMorph: rowMorph.

This method adds controls to the game. The local variables are : rowMorph , newGameButton and exitGameButton.

rowMorph defines an instance of the class Morph which would be the placeholder for the two control buttons located at the top. The two control buttons are defined as New using the variable new GameButton which on click would restart the game , and Exit using the exitGameButton which on click would close the game. The buttons are created using a method createCtrlLabelled which we define next.

rowMorph addMorph: newGameButton adds the button to the Morph instance created earlier.

TicTacToe>>#createCtrlLabelled: aString onClickExecutes: aBlock
| aCtrlButton |
aCtrlButton := SimpleButtonMorph new label: aString.
aCtrlButton color: (Color black alpha: 0.2).
aCtrlButton extent: 120@50.
aCtrlButton on: #click send: #value to: aBlock.
^aCtrlButton.

TicTacToe>>#createCtrlLabelled: aString onClickExecutes: aBlock method makes a simple button using Morph adds label and control to it.

TicTacToe>>#open 
container openInWindow.

The open method defines as to how the game/TicTacToe class would open. Here we have defined it to open in a dialog box.

TicTacToe>>#restart
container delete.
Smalltalk garbageCollect.
TicTacToe new open.

It closes the game and calls for Garbage Collection (Garbage Collection (GC) is a form of automatic memory management. It finds data objects in a program that cannot be accessed in the future and reclaims the resources used by those objects.)

SimpleButtonMorph subclass: #TicTacToeCell
instanceVariableNames: 'parentModel rowNum colNum'
classVariableNames: ''
poolDictionaries: ''
category: 'game'

Here a subclass TicTacToeCell is defind in the SimpleButtonMorph class with parentModel , rowNum and colNum as the instance variables. This class defines the button for each cell of the grid.

TicTacToeCell>>#initialize 
super initialize.
self label: ''.
self extent: 80@80.
self color: Color yellow .
self on: #click send: #value to: (self onClickExecutionBlock).
^self.

This initialize method initialises the button size as 80X80 and gives it the color: yellow. An ‘onClick’ control is given to the button which then calls the onClickExecutionBlock method present in the same class.

TicTacToeCell>>#setModel: ticTacToeModel row: aRow col: aCol
parentModel := ticTacToeModel.
rowNum := aRow.
colNum := aCol.

The setModel: row: col: takes three arguments ticTacToeModel , aRow and aCol. The parentModel is assigned ticTacToeModel , roNum becomes the value of aRow and similiarly colNum has the value aCol.

TicTacToeCell>>#onClickExecutionBlock
^[
(self label size) == 0
ifTrue:[
self label: (parentModel updateAtRow: rowNum 
                Col: colNum).
parentModel checkWinCondition.
self extent: 80@80.
].
 ]

This method defines what should happen when each cell in the grid is clicked. At every click , the label of the cell is changed to X or O depending upon whose turn it is , the row numbers and coloumn numbers are updated in the parentModel and win condition is checked by calling the checkWinCondition method of the class TicTacToeModel defined next.

Matrix subclass: #TicTacToeModel
instanceVariableNames: 'filledCellCount currentFill winner'
classVariableNames: ''
poolDictionaries: ''
category: 'game'

A subclass TicTacToeModel is defined in the Matrix class with filledCellCount , currentFill and winner as the instance variables.

TicTacToeModel>>#initialize 
super initialize.
filledCellCount := 0.
currentFill := nil.
winner := nil.

This initialize methods defines that initially no cell in the grid is filled and there is no winner as of now.

TicTacToeModel>>#updateAtRow: r Col: c
currentFill == nil
ifTrue:[ currentFill := 'X'. ]
ifFalse:[
currentFill == 'X'
ifTrue: [ currentFill := 'O'. ]
ifFalse: [ currentFill := 'X'. ]
].
self at: r at: c put: currentFill.
filledCellCount := filledCellCount + 1.
^currentFill.

The updateRowAt: Col: method takes two arguments r and c used to update the currentFill and filledCellCount variables.

TicTacToeModel>>#checkWinCondition
filledCellCount >= 5 "for optimization. Win can occur minimum at 5th turn"
ifTrue: [
Transcript show: 'Yes'.
1 to: 3 do: [:idx |
self checkWinConditionInRow: idx.
self checkWinConditionInColumn: idx.
].
self checkWinConditionInDiagonals.
].
checkWinConditionInRow: rowNum
|set|
winner isNil
ifTrue: [
set := (self atRow: rowNum) asSet.
self checkWinConditionInSet: set
].
^winner.

The method checkWinCondition is self explanatory. It is used to check if we have a winner or not at every move.

TicTacToeModel>>#checkWinConditionInColumn: colNum
|set|
winner isNil
ifTrue: [
set := (self atColumn: colNum) asSet.
self checkWinConditionInSet: set.
].
^winner.
TicTacToeModel>>#checkWinConditionInDiagonals
|set1 set2 |
winner isNil
ifTrue: [
set1 := (self diagonal) asSet.
set2 := Set newFrom: {(self at: 1 at: 3). (self at: 2 at: 2). (self at: 3 at: 1)} asOrderedCollection.
self checkWinConditionInSet: set1.
self checkWinConditionInSet: set2.
].
^winner.
TicTacToeModel>>#checkWinConditionInSet: aSet
aSet size == 1
ifTrue: [
(aSet includes: 'X')
ifTrue: [
        winner := 'P1'. 
        Transcript open. 
        Transcript show: 'Player 1 is the winner!!'.
    ].

(aSet includes: 'O')

ifTrue: [
        winner := 'P2'.  
        Transcript open. 
        Transcript show: 'Player 2 is the winner!!'.
    ].
].

example2.

Now , we have made the game. To open the game , simply execute the following in the playground/workspace.

TicTacToe new open.

The messages : ‘Yes’ , ‘Player x is the winner’ will be displayed in the Transcript.

PS – This was just the basic implementation. I plan to improvise it further with graphics and other functionality/features.

Do like the post if it was helpful.
For any queries/suggestions please comment below.

Thank You

Continue ReadingTicTacToe Tutorial #FunWithPharo