Skip to main content

Tic Tac Toe

Let's play the Tic Tac Toe game in this project. Two potentiometers (A0, A11) are used to move among 3x3 grids and two buttons (D1, D19) are used to select the grid.

Circuit

You will use the two buttons (D1, 19) and two potentiometers (A0, A11) on the kit to play the game.

Modules for this project

Project overview

  • The display is divided into 3x3 grids.
  • The first player rotates the potentiometer (A0) to choose a grid. Press the button (D1) to confirm the selection.
  • Then the second player rotates the potentiometer (A11) to choose a grid. Press the button (D19) to confirm the selection.
  • Two players take turns.
  • Finally, the first player who marks the grids in a row/column/diagonal wins.

Example code

You can download the project source code here.

// Import SwiftIO to set the communication and MadBoard to use pin id. 
import SwiftIO
import MadBoard
// Import the library to configure the LCD and write pixels on it.
import ST7789

@main
public struct TicTacToe {
public static func main() {
// Initialize the SPI pin and the digital pins for the LCD.
let bl = DigitalOut(Id.D2)
let rst = DigitalOut(Id.D12)
let dc = DigitalOut(Id.D13)
let cs = DigitalOut(Id.D5)
let spi = SPI(Id.SPI0, speed: 30_000_000)

// Initialize the LCD using the pins above. Rotate the screen to keep the original at the upper left.
let screen = ST7789(spi: spi, cs: cs, dc: dc, rst: rst, bl: bl, rotation: .angle90)

// Initialize the two players.
// The potentiometer is used to select grid and the button is to confirm the selection.
let player1 = Player(
pot: AnalogIn(Id.A0),
button: DigitalIn(Id.D1),
color: Color.orange
)

let player2 = Player(
pot: AnalogIn(Id.A11),
button: DigitalIn(Id.D19),
color: Color.lime
)

var game = TicTacToeGame(player1: player1, player2: player2, screen: screen)

// Play the game and check if anyone wins the game or the game ends in a tie.
// If a player wins, the screen will be filled with its color.
// If it's a tie, the screen will be filled with background color (white).
while true {
game.play()
sleep(ms: 10)
}
}
}