AI checks oponent next step to win

This commit is contained in:
Arnas Udovic 2024-01-27 23:16:47 +02:00
parent 2fde79ec59
commit ebc8813d36
4 changed files with 38 additions and 8 deletions

29
db.go
View file

@ -125,22 +125,45 @@ func saveGameLog(db *sql.DB, game *Game) {
}
}
func getWinnerNextStep(db *sql.DB, game *Game) string {
func getWinnerNextStep(db *sql.DB, game *Game) (string, bool) {
stmt, err := db.Prepare(
"SELECT game_flow FROM Games WHERE game_flow LIKE ? AND first_won = ? ORDER BY count DESC",
)
if err != nil {
return "", false
}
defer stmt.Close()
var gameFlow string
err = stmt.QueryRow(game.gameFlow+"%", !game.aiSecond).Scan(&gameFlow)
if err != nil {
return "", false
}
return gameFlow[len(game.gameFlow) : len(game.gameFlow)+1],
len(game.gameFlow)+1 == len(gameFlow)
}
func getOponentNextStepToWin(db *sql.DB, game *Game) string {
stmt, err := db.Prepare(
"SELECT game_flow FROM Games WHERE game_flow LIKE ? AND first_won = ? ORDER BY length(game_flow) ASC",
)
if err != nil {
return ""
}
defer stmt.Close()
var gameFlow string
err = stmt.QueryRow(game.gameFlow+"%", !game.aiSecond).Scan(&gameFlow)
err = stmt.QueryRow(game.gameFlow+"%", game.aiSecond).Scan(&gameFlow)
if err != nil {
return ""
}
return gameFlow[len(game.gameFlow) : len(game.gameFlow)+1]
if len(game.gameFlow)+2 == len(gameFlow) {
return gameFlow[len(game.gameFlow)+1 : len(game.gameFlow)+2]
}
return ""
}
func getStatsTable(db *sql.DB) [][]string {

11
main.go
View file

@ -160,7 +160,16 @@ func getGameFlow(c *gin.Context) (string, int) {
}
func getNewStep(db *sql.DB, game *Game) string {
nextStep := getWinnerNextStep(db, game)
nextStep, lastStep := getWinnerNextStep(db, game)
if "" != nextStep && lastStep {
return nextStep
}
oponentNextStepToWin := getOponentNextStepToWin(db, game)
if "" != oponentNextStepToWin {
return oponentNextStepToWin
}
if "" != nextStep {
return nextStep
}

View file

@ -24,8 +24,7 @@
<ul>
<li>2024-01-02: First version. AI checks won games.</li>
<li>2024-01-27: AI check the mostly won game.</li>
<li><i class="text-muted">todo: AI check competitor's next move to avoid defeat.</i></li>
<li>2024-01-27: AI check the mostly won game. AI check competitor's next move to avoid defeat.</li>
</ul>
<h3>About myself</h3>

View file

@ -24,8 +24,7 @@
<ul>
<li>2024-01-02: Pėrmuojė veikontė versėjė. DI veiz i laimietus žaidėmus.</li>
<li>2024-01-27: DI veiz i daugiausē kartu laimietus žaidėmus.</li>
<li><i class="text-muted">planūs: DI veiz i varžuova būsėma laimiejėma, ka bluokoutė.</i></li>
<li>2024-01-27: DI veiz i daugiausē kartu laimietus žaidėmus. DI veiz i varžuova būsėma laimiejėma, ka bluokoutė.</li>
</ul>
<h3>Aple monėm pati</h3>