0
0

Pythonを使って二人用しりとりゲームを作る

Posted at

初めに

今回は、判定に二分探索を使ってしりとりゲームを作りました。

コード

import re

wordList = []
#しりとりの初めの文字を初期値で入れる
LastTimeWord = ""
#ひらがな判定用
p = re.compile('^[ぁ-ゖ]+$')

#しりとりとして成り立っているか判定
def siritoriCheck(inputWord):
    global LastTimeWord
    if inputWord[0] == LastTimeWord[-1]:
        #成り立っていたら言葉を格納
        LastTimeWord = inputWord
        return False
    return True

#言葉が重複していないかをチェック
def wordCheck(inputWord):
    global wordList

    #最後の文字が「ん」だったらTrue
    if inputWord[-1] == "":
        return True
    
    #文字列が格納されているリストをソートする
    wordList=sorted(wordList)

    #2分探索で文字が重複していないかを探す
    left = 0
    right = len(wordList) - 1
    while left <= right:
        mid = (left + right) // 2
        if wordList[mid] == inputWord:
            return True
        elif wordList[mid] < inputWord:
            left = mid + 1
        else:
            right = mid - 1
    #リストに文字列を追加
    wordList.append(inputWord)
    return False



while True:
    inputWord = input()
    #ひらがなで入力されているかチェック
    if not p.fullmatch(inputWord):
        print("ひらがなで入力してください")
        continue

    #しりとりとして成り立っているかチェック
    if siritoriCheck(inputWord):
        print("文字が繋がってないよ!")
        continue

    #同じ言葉が入力されていないか、最後の文字が「ん」かチェック
    if wordCheck(inputWord):
        print("ゲームオーバー")
        break

0
0
1

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