Site de support du club Création de jeux vidéo.
import SwiftUI
struct GameView : View {
@ObservedObject var viewModel: GameViewModel
@State private var grid = Array(repeating: Array(repeating: false, count: 3), count: 3)
@State private var score = 0
@State private var timer:Timer? = nil
@State private var time = 30
@State private var gameTimer:Timer? = nil
@State private var gameActive = false
@State private var activeTile: (row: Int, col: Int)? = nil
var body: some View {
VStack {
HStack {
Text("Score : \(score)")
.font(.title)
.padding()
Text("\(time)⏱️")
.font(.title)
.padding()
}
gridView
.padding()
Button(gameActive ? "STOP" : "START") {
if(gameActive) {
stopGame()
} else {
startGame()
}
}
.padding()
.background(gameActive ? .red : Color.blue)
.foregroundColor(Color.white)
.cornerRadius(10)
.font(.title)
}
}
var gridView : some View {
VStack() {
ForEach(0..<3) { row in
HStack(){
ForEach(0..<3) { col in
tileView(row:row, col:col)
}
}
}
}
}
func tileView(row: Int, col: Int) -> some View {
RoundedRectangle(cornerSize: CGSize(width: 20, height: 20))
.foregroundColor(grid[row][col] ? Color.yellow : Color.blue)
.frame(width: 80, height: 80)
.onTapGesture {
tapTile(row:row, col:col)
}
}
func tapTile(row:Int, col:Int) {
guard gameActive else { return }
if grid[row][col] {
score += 1
grid[row][col] = false
activeTile = nil
}
}
func startGame() {
gameActive = true
gameTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
time = max(0, time-1)
if time == 0 {
stopGame()
}
}
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in
lightRandomTile()
}
reset()
}
func lightRandomTile() {
// desactiver l'ancienne tuile
if let active = activeTile {
grid[active.row][active.col] = false
score = max(0, score - 1)
activeTile = nil
}
// Choisi une tile aleatoirement
let col = Int.random(in: 0..<3)
let row = Int.random(in: 0..<3)
grid[row][col] = true
activeTile = (row:row, col:col)
}
func stopGame() {
gameActive = false
timer?.invalidate()
timer = nil
gameTimer?.invalidate()
gameTimer = nil
}
func reset() {
score = 0
}
func swichOffAllTiles() {
// Eteint les cases
for row in 0..<3 {
for col in 0..<3 {
grid[row][col] = false
}
}
}
}
Langage du code : Swift (swift)