0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIで作ったCPU対戦トランプ「七並べ」アプリの実装ポイント

0
Posted at

はじめに

この度、SwiftUIを使ってiOS向けの「七並べ」アプリを開発し、App Storeにリリースしました。本記事では、開発中に工夫した点や技術的な実装ポイントを紹介します。

アプリ概要

実装のポイント

1. カードの状態管理

カードは各スート(♠♥♦♣)× ランク(A〜K)の52枚。ゲームの進行に合わせて「手札」「場札」「捨て札」の状態を管理する必要があります。今回はObservableObjectでゲーム全体の状態を保持し、@PublishedプロパティでUIに反映させました。

class GameState: ObservableObject {
    @Published var playerHand: [Card] = []
    @Published var cpuHands: [[Card]] = [[], [], []]
    @Published var table: [Suit: [Int]] = [:] // 各スートに出ている数字
    @Published var currentPlayer: Int = 0
    // ...
}

2. 出せるカードの判定

七並べでは、場にある各スートの7を中心に、前後の数字が出せるかどうかを判定します。具体的には、各スートについて「場に出ている数字の最小値-1」と「最大値+1」のカードが出せるため、これを毎ターン計算してハイライト表示しました。

func canPlay(card: Card) -> Bool {
    guard let numbers = table[card.suit] else { return false }
    if let min = numbers.min(), card.number == min - 1 { return true }
    if let max = numbers.max(), card.number == max + 1 { return true }
    // 7は常に出せる(初期配置用)
    return card.number == 7
}

3. CPUの思考ロジック

CPUは単純なルールベースで実装しました。まず出せるカードがあれば、できるだけ長いスートを伸ばすように選択します。パスが3回に達したらペナルティとして手札から1枚ランダムに捨てる処理を入れています。

4. 勝敗記録の保存

勝敗はUserDefaultsに保存し、通算成績を一覧表示できるようにしました。

使用技術

  • SwiftUI
  • Combine (ObservableObject)
  • UserDefaults
  • アニメーションはSwiftUIのwithAnimationを使用

今後の改善点

  • オンライン対戦対応
  • 難易度設定(CPUの思考を強くする)
  • カードデザインのカスタマイズ

おわりに

シンプルなゲームですが、状態管理やCPUロジックなど学びが多い開発でした。ソースコードの参考になれば幸いです。アプリは無料で公開していますので、ぜひ遊んでみてください。

App Storeでダウンロード

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?