iT邦幫忙

2022 iThome 鐵人賽

DAY 19
0

前情提要:

經過一連串~ brain storming, debug, paper studying, writing articles, positive of covid... hahaha jk lmao /images/emoticon/emoticon37.gif/images/emoticon/emoticon39.gif

However, I realised that my health is the piority! As a life where you have the energy to focus on everything else you want and dream of.
So, let's have a break for coding some simple python games.

Those games are my first side project, which also my self-study of Python before I start the AI and Big Data program. I learned it from the "小象學堂" which is a wechat account (kinda like wechat python learning robot ?!) that I have given from my brother. (p.s. My siblings were engineer before I be an AI RD/PM... but I'm the only one, who still alive in this field/images/emoticon/emoticon02.gif ... well life is hard... it's another story~ haha LOL, let come back to the article /images/emoticon/emoticon33.gif)

https://ithelp.ithome.com.tw/upload/images/20220930/201516813M7pw38vd2.jpg
1A2B是一種猜數字的益智遊戲,遊戲人數為兩人,或一人與一個運算機器。此篇文章所採用的模式為1人對1台電腦對玩的小遊戲。此專案採用 Python 程式碼撰寫, 讓玩家可以即時輸入所猜的數字, 並即時輸出答對的數字與位置的結果。

此程式會隨機(import random)設定一組四碼的數字作為謎底,另一方猜。每猜一個數,出數者就要根據這個數字給出提示,提示以XAYB形式呈現,直到猜中為止。其中X表示位置正確的數的個數,而Y表示數字正確而位置不對的數的個數。

舉例如下:

  • 當謎底為8123,而猜謎者猜1052時,出題者必須提示0A2B。
  • 當謎底為5637,而猜謎者猜4931時,出題者必須提示1A0B。
  • 小叮嚀: 此專案需輸入4個不同的數字, 不能有重複的數字。
    https://ithelp.ithome.com.tw/upload/images/20220930/20151681WSuQlwCvLQ.png

實作完整程式碼(如下):

#1A2B
import random
ans = set({})
while len(ans) < 4:
    ans.add(random.randint(1,9))
list(ans)
anslist = list(map(lambda x: str(x), list(ans)))
def inerror(x):
    while True:
        try:
            int(x)
            if type(int(x)) == int and len(set(x)) == 4 and len(x) == 4:
                break
            else:
                x = input("請輸入四個不同數字 = ")
        except:
            x = input("請輸入四個不同數字 = ")
    return x
guess = input("猜測的密碼 = ")
correctguess = inerror(guess)
c = list(correctguess)
a = 0
b = 0
while c != anslist:
    for i in range(4):
        if c[i] == anslist[i]:
            a += 1
        else:
            pass
        if c[i] in anslist and c[i] != anslist[i]:
            b += 1
    print(f"{a}A{b}B")
    a = 0
    b = 0
    guess = input("重新猜測的密碼 = ")
    correctguess = inerror(guess)
    c = list(correctguess)
print("恭喜答對,答案為 : ", anslist)

開始來玩啦~ /images/emoticon/emoticon42.gif

注意要輸入4個不同的數字喔! 如果不滿4個會需要再重輸一次喔~
算是蠻幸運, 很快就猜中了!
https://ithelp.ithome.com.tw/upload/images/20220930/20151681QyvfmTSUJV.png


上一篇
ML 機器學習: ARIMA 基本介紹 & 實作 (Full Eng Ver.)
下一篇
Python 小遊戲實作: 終極密碼- (猜1個1~100的數字)
系列文
轉職AI軟體工程師的自我學習分享筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言