Tom And Jerry TicTacToe With Swift

Overview

Tom And Jerry TicTacToe

Back with one of the most famous wars in the history of cats vs mice .. THE LEGENDS .. the long-life enemies TOM & JERRY are here to win the ULTIMATE TIC TAC TOE Game!

" TO WIN OR NOT TO WIN "

All what it takes is a good strategy to win .. but the real question is " WHOSE SIDE ARE U ON ? "

output.compress-video-online.com.mp4

Step 1: Pick a side !

Using alert dialog , The game starts by asking the players who will start first , u might as well consider tossing a coin to decide .. or simply enjoy the fight :) upon choice you'll notice that the (Turns Label) above the game board has changed text & color to indicate who the current player is !

func choosePlayerDialog(){
        // allow the user to decide who will start the game
        let alert = UIAlertController(title: "Choose Player", message: "Choose who will start the game ?" , preferredStyle: UIAlertController.Style.alert)
        // if the user chooses TOM, update the layout
        alert.addAction(UIAlertAction(title: "Tom", style: UIAlertAction.Style.cancel, handler: { [self] action in
            self.currentPlayer = "tom"
            self.turnLabel.text = "Tom's Turn"
            self.turnLabel.textColor = .systemIndigo
        }))
        // if the user choose JERRY, update the layout
        alert.addAction(UIAlertAction(title: "Jerry", style: UIAlertAction.Style.default, handler: { [self] action in
            self.currentPlayer = "jerry"
            self.turnLabel.text = "Jerry's Turn"
            self.turnLabel.textColor = .orange
        }))
        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
    
output2.mp4

Step 2 : Mark your territory !

Once you decide you move click on the spot to be marked as yours :) and this is how its happening:

  1. Checking that the spot isn't already taken (NO CHEATING)
  2. Check who the current player is (Tom || Jerry) using the variable [CurrentPlayer]
  3. Set the spot to display the current player's logo/image
  4. Set the [Turn label] text to display the player's name that should play next and set its' color too (orange = Jerry , Indigo = Tom)
@IBAction func buttonPressed(_ sender: UIButton) {

    // chack that the button is not taken alredy by eaither tom or jerry
        if !tom.contains(sender.tag) && !jerry.contains(sender.tag) {
        
        switch currentPlayer {
            case "tom":
            // if the current player who pressed the button is tom , set the button to tom's image
            sender.setImage(UIImage(named: "tom.png"), for: .normal)
            // add the button tag/position to tom's buttons array
            tom.append(sender.tag)
            // check if tom made a strike or not
            checkWinner(checkArray: tom,winnerName: "Tom")
            // if tom didn't score a win yet , move the turn to the next player JERRY
            currentPlayer = "jerry"
            turnLabel.text = "Jerry's Turn"
            turnLabel.textColor = .orange
            // 
            if tom.count+jerry.count == 9 && !win{
                    tieDialog()
            }else{
                // other wise go on with the game and set the wins to none
                win = false
            }
                
            case "jerry":
            // same situation going here so no need to repeat :)
            sender.setImage(UIImage(named: "jerry.png"), for: .normal)
            jerry.append(sender.tag)
            checkWinner(checkArray: jerry,winnerName: "Jerry")
            currentPlayer = "tom"
            turnLabel.text = "Tom's Turn"
            turnLabel.textColor = .systemIndigo
            
            else{
                win = false
            }
            default:
            // if something went wrong just restart the game and let the players choose who will start
            self.loadView()
            choosePlayerDialog()
            }
        }
    }

Step 3 : Strategy is Key !

Whether it's horizontal , vertical or even diagonal .. once you get 3 in a row YOU WILL BE THE WINNER ! so make sure to plan it well cuz you might end in a tie .. or worse .. YOU LOSE X_X

But no worries we will check for every strike possibility to make sure its' fare and square :)

func checkWinner(checkArray : [Int], winnerName:String){
        // check if tom's/jerry's buttons array contains any of these winning sets , if so , declare the one who has it as a winner
        if [1,2,3].allSatisfy(checkArray.contains) ||
            [4,5,6].allSatisfy(checkArray.contains) ||
            [3,5,7].allSatisfy(checkArray.contains) ||
            [7,8,9].allSatisfy(checkArray.contains) ||
            [1,4,7].allSatisfy(checkArray.contains) ||
            [2,5,8].allSatisfy(checkArray.contains) ||
            [3,6,9].allSatisfy(checkArray.contains) ||
            [1,5,9].allSatisfy(checkArray.contains){
            winDialog(winner: winnerName)
        }
    }

1) Win

once a strike is found , an alert dialog will appear declaring who the winner is ! and by clicking on "Play Again" the game will restart for the war to be continued :P

    func winDialog(winner: String){
        resetGame()
        // a win is found
        win = true
        let alert = UIAlertController(title: "Congrats !", message: "\(winner) Won The Game !" , preferredStyle: UIAlertController.Style.alert)
        // add an action (button)
        alert.addAction(UIAlertAction(title: "Play Again", style: UIAlertAction.Style.default, handler: { action in self.newGame()}))
        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
winDialog.mp4

2) Tie

And if you ran out of spots and yet with no wins .. this means the game has ended in a tie :O and a small alert wil pop up !

if tom.count+jerry.count == 9 && !win{
                tieDialog()
            }
            
    func tieDialog(){
        resetGame()
        let alert = UIAlertController(title: "Tie !", message: "This is a tie, no one won this round :)" , preferredStyle: UIAlertController.Style.alert)
        // add an action (button)
        alert.addAction(UIAlertAction(title: "Play Again", style: UIAlertAction.Style.default, handler: { action in self.newGame()}))
        // show the alert
        self.present(alert, animated: true, completion: nil)
    }            
tieDialog.mp4

3) Restart The game

You chose a wrong move ? someone cheated ? no worries just click restart and the game will start all over :D

       
    func myResetDialog(){
        // clear the game progress to start a new one
        resetGame()
        let alert = UIAlertController(title: "Reset Game", message: "Are You Sure You Want To Reset The Game ? You'll Lose Your Progress !" , preferredStyle: UIAlertController.Style.alert)
        // add an action (button)
        alert.addAction(UIAlertAction(title: "Reset", style: UIAlertAction.Style.destructive, handler: { action in
            self.newGame()
            self.choosePlayerDialog()
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
        // show the alert
        self.present(alert, animated: true, completion: nil)
    }
reset.mp4
You might also like...
Swift playground teaching basics of buffer overflow vulnerability and ARM64 assembly by exploiting vulnerable app on ARM64 emulator (WWDC22 Swift Student Challenge Winner)
Swift playground teaching basics of buffer overflow vulnerability and ARM64 assembly by exploiting vulnerable app on ARM64 emulator (WWDC22 Swift Student Challenge Winner)

Pwnground Project overview Pwnground is a project created as my submission for WWDC22 Swift Student Challenge (winner). It is an interactive Swift Pla

KHabit an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more.

an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more. The app is completely open source, it does not contain in-app or ads, and does not track the user in any way.

iOS app that detects LaTeX symbols from drawings. Built using PencilKit, SwiftUI, Combine and CoreML for iOS 14 and macOS 11.

DeTeXt Finding the symbol you want to use in LaTeX can be hard since you can't memorize all the possible commands and packages for every symbol you mi

an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more.

KHabit an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more. The app is completely open source, it d

Native and encrypted password manager for iOS and macOS.
Native and encrypted password manager for iOS and macOS.

Open Sesame Native and encrypted password manager for iOS and macOS. What is it? OpenSesame is a free and powerful password manager that lets you mana

SwiftUI iOS Widget and WatchOS app that randomly shows a word of the day with description and example.
SwiftUI iOS Widget and WatchOS app that randomly shows a word of the day with description and example.

Word Of The Day iOS Widget and WatchOS app made in SwiftUI that displays a random word of the day with description and example of usuage. Requirements

A SwiftUI implementation of React Hooks. Enhances reusability of stateful logic and gives state and lifecycle to function view.

SwiftUI Hooks A SwiftUI implementation of React Hooks. Enhances reusability of stateful logic and gives state and lifecycle to function view. Introduc

iOS App to display game lists and details with the ability to add games to your favorites list and see metacritic ratings.
iOS App to display game lists and details with the ability to add games to your favorites list and see metacritic ratings.

Game Data System - GDS Author: Heitor Silveira ([email protected]) iOS App to view games from various platforms, their description, release

Social Media platform build with swiftUI and Firebase with google and apple account integration for Signing In Users
Social Media platform build with swiftUI and Firebase with google and apple account integration for Signing In Users

Social Media platform build with swiftUI and Firebase with google and apple account integration for Signing In Users . Providing Users availability to upload posts and images add caption allowing other users to comment , with Find section to explore new people , new stories , User Profile section to allow the user to take control of his account .

Owner
Reem
I'm just a Cloud ☁️
Reem
Tictactoe-ultimatum - iOS implementation of Ultimate Tic-Tac-Toe game

TicTacToe Ultimatum An iOS app in Swift implementing the classic game of Ultimat

Max Khrapov 1 Jan 21, 2022
In this mini app covered the concepts like basics of SwiftUI and Navigations and Animations and List with CRUD functions and MVVM and App Launch and App icons adding and also applied persistence using UserDefaults Concept.

TodoList In this application used the concepts from the beginner level project of SwiftUI_Evolve_1 The following concepts covered in this mini app Swi

Sivaram Yadav 2 Dec 4, 2021
Mahmoud-Abdelwahab 5 Nov 23, 2022
This To-Do app was developed using Swift and SwiftUI and works on iOS, MacOS (Apple Silicon) and WatchOS. The tasks are kept on storage even when the app is restarted.

ToDo-SwiftUI This app has a lot of sentimental value for me, given that it helped me a lot to understand the process of doing an iOS app and became th

Augusto Galindo Ali 6 Jul 12, 2022
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

Gabriel Denoni 11 Dec 27, 2021
🎮 Favorite your games filter and see the upcoming games and ! Swift + Combine = 💜 Hacktoberfest 🎃 👾

✨ Revill is App to list games and search best games ✨ Design in Swift UI + Combine ✨ The idea is develop this app in Hacktober Fest Expected To Do Des

Vinicius Mangueira 21 Dec 17, 2022
A swift package(SPM) with iOS UI component that loads and displays images from remote urls or local assets and displays in a slide-show form with auto scroll feature.

MDBannersView A swift package with an iOS UI component that loads and displays images from remote urls, local assets and displays in a slide-show form

Madhav Deva 2 Feb 5, 2022
Github repo search with using mvvm-c and clean architecture and using combine swift

GitSearchWithMVVM-C-CleanArchitecture Github repo search with using mvvm-c and clean architecture and using combine swift. Content Overview How To Run

Muhammad Qasim Majeed 1 Mar 16, 2022
A collection of Swift functions, extensions, and SwiftUI and UIKit Views.

J's Helper A collection of Swift functions, extensions, and SwiftUI and UIKit Views. Legend: ?? UIKit ?? SwiftUI ?? Shared Installation In XCode 12 go

Jem Alvarez 3 Oct 1, 2022
This is an app for a craft beer company called Cacique Bier that allows to see their available products and place orders. Made with Swift and SwiftUI.

Cacique Bier App This is an app for a Craft Beer company that shows their catalogue of products and in the future will allow purchases. The app is com

Augusto Galindo Ali 5 Jun 21, 2022