Skip to content

Instantly share code, notes, and snippets.

@obelisk68
Last active October 29, 2018 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obelisk68/a6f9b1da3ab1633f9da403c836ddde3e to your computer and use it in GitHub Desktop.
Save obelisk68/a6f9b1da3ab1633f9da403c836ddde3e to your computer and use it in GitHub Desktop.
31ゲーム
package main
import "fmt"
import "math/rand"
import "time"
var goal = 31
func min_max(cards []int, turn bool, sum int) int {
if sum == goal { if turn {return -10} else {return 10} }
if sum > goal { if turn {return 10} else {return -10} }
if turn {
max := -100
for i := 0; i < 6; i++ {
if cards[i] == 0 {continue}
cards[i]--
score := min_max(cards, !turn, sum + i + 1)
cards[i]++
if score > max {max = score}
}
return max
} else {
min := 100
for i := 0; i < 6; i++ {
if cards[i] == 0 {continue}
cards[i]--
score := min_max(cards, !turn, sum + i + 1)
cards[i]++
if score < min {min = score}
}
return min
}
}
func input(cards []int) int {
for {
num := 0
fmt.Print("カードを選んで下さい(1~6): ")
fmt.Print(cards)
fmt.Scanf("%d", &num)
if 1 <= num && num <= 6 {
num--
if cards[num] != 0 {
cards[num]--
return num
}
}
}
}
func computer_thinking(cards []int, sum int) int {
win_hands := []int{}
for i := 0; i < 6; i++ {
cards[i]--
score := min_max(cards, false, sum + i + 1)
cards[i]++
if score > 0 {win_hands = append(win_hands, i)}
}
hand := 0
for {
hand = rand.Intn(6)
if cards[hand] > 0 {break}
}
hand = -(hand + 1)
l := len(win_hands)
if l > 0 {hand = win_hands[rand.Intn(l)]}
return hand
}
func you_win (sum int) {fmt.Printf("合計 %d で、あなたの勝ちです!\n", sum)}
func you_lose(sum int) {fmt.Printf("合計 %d で、あなたの負けです!\n", sum)}
func main() {
rand.Seed(time.Now().UnixNano())
cards := []int{4, 4, 4, 4, 4, 4}
count := 1
sum := 0
for {
fmt.Printf("\n**第%d手目**\n", count)
fmt.Printf("合計: %d\n", sum)
//fmt.Printf("ヒント: %d\n", computer_thinking(cards, sum) + 1)
hand := input(cards)
sum += hand + 1
if sum == goal {
you_win(sum)
return
} else if sum > goal {
you_lose(sum)
return
}
count++
fmt.Printf("\n**第%d手目**\n", count)
hand = computer_thinking(cards, sum)
if hand >= 0 && (hand + 1 + sum != goal) {
fmt.Println("---あなたの負けは確定しています")
}
if hand < 0 {hand = -(hand + 1)}
fmt.Printf("コンピュータの手は %d です\n", hand + 1)
sum += hand + 1
if sum == goal {
you_lose(sum)
return
} else if sum > goal {
you_win(sum)
return
}
cards[hand]--
count++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment