我正在尝试用 Python 编写这个游戏。
随机生成的具有不同数字的 4 位数字,将与用户输入的相同属性的数字(4 位数字,不同数字)进行比较。
是否有一种比较两个数字来评估并向用户返回以下内容的简短方法:
两个数字中具有相同小数位的数字有多少位匹配。
两个小数位不同的数字有多少位匹配。
对于上述条件 1 的每个输出将为 +1,对于条件 2 的每个输出将为 -1;指示; “+”号为右边位数,“+”后面的数字为右边位数; “-”号表示猜错的地方,“-”号后面的数字是待猜数字中错位的数字。
示例:计算机号码1234
猜测1:1572 反馈1:+1 -1
猜测2:1039 反馈2:+2 -0
猜测3:1243 反馈3:+2 -2
这种情况一直持续到反馈为+4 -0,这会返回用户在 x 次尝试中猜到的数字,他/她是个十足的白痴:)
我用了 70 行代码(只是第一个猜测比较部分)左右完成了这个工作,因为我不知道有关编码的第一件事,所以我确信有更好的方法来做到这一点。有几次我必须将数字转换为字符串,然后再转换回整数。
很可能,我不知道要使用的命令以及如何使用它来简化事情,所以我几乎 if/elif/else 了整个事情一一。(强调几乎:))我知道的很少,我是从网上的Python文档和这里学习的。
正确的简短方法是什么?只需比较/测试两个数字部分就足以让我更加乐观。
# 4 digit number guessing game
import random, sys
import pygame as pg # not used
from pygame.locals import * #not used
import time
import os#realized later on that if this is not there, I can't specify a
ValueError.
#pygame init()not necessary for the time being
global tahmin#don't know why I put this here. tried to overcome the error I
got saying the variable is referenced before it is assigned by changing the
variable into a global one. But did not work unless I wrote this line into
the function it is called. But since no harm done, I kept it here.
global sayı#same as above
def pick():#computer picks a number between min and max different 4 digit
range.
global sayı#above mentioned story
sayı = random.randint(1023, 9876)
sayı = str(sayı)
def testpick(): #testing the number generated by the computer for different
digits
while True:
if sayı[0] == sayı[1] or sayı[0] == sayı[2] or sayı[0] == sayı[3] or sayı[1] == sayı[2] or sayı[1] == sayı[3] or sayı[2] == sayı[3]:
print("geçersiz sayı")#invalid number
print("değiştiriyorum")#changing the number
pick()
print(sayı[0]+sayı[1]+sayı[2]+sayı[3])#just for testing for
myself
else:
#tahmin_gir() cancelled
print("Sayımı tuttum")#Picked my number
break
def tahmin_gir():#input guess function
global tahmin#same story above
try:#make sure it is a number
tahmin = int(input("Tahminini gir==>"))
except ValueError:
print("Sadece sayı girebilirsin!")
tahmin_gir()
def tahmin_test():#test the guess function
global tahmin#blody global same story above
tahmin_gir()
if tahmin >= 1023 and tahmin <= 9876:
tahmin = str(tahmin)
if tahmin[0] == tahmin[1] or tahmin[0] == tahmin[2] or tahmin[0] == tahmin[3] or tahmin[1] == tahmin[2] or tahmin[1] == tahmin[3] or tahmin[2] == tahmin[3]:
print("Basamaklar birbirinden farklı olmalı!")#Digits must be
different
tahmin_test()
elif tahmin < 0:
print("Pozitif bir sayı gir !")#must be positive number
tahmin_test()
else:
print("Sayı 4 basamaklı olmalı !")#must be 4 digits
tahmin_test()
print("Lütfen adını gir ve enter'a bas.")#name and enter
ad = input()
# mics. explaining the game below
print("Merhabalar! " + ad + " 4 basamaklı, basamakları birbirinden farklı
bir sayı tuttum.")
print("Bakalım kaç denemede bulabileceksin.")
print("Sana her tahmininden sonra geri bildirimler yapacağım.")
print("Örneğin tuttuğum 1234 sayısı için, senin yaptığın tahmin 1562
olsun.")
print("Benim sana cevabım +1 -1 olacaktır. Bunun anlamı, tahmininde 1 adet
doğru sayı doğru yerde,")
print("1 adet de, doğru sayı yanlış yerde. Yani tahmininde baştaki 1 sayısı
hem sayımın içinde var, hem de yeri")
print("doğru. Bunun için +1. Sondaki 2 sayısı da sayımda var ama yeri doğru
değil. Bunun için de -1")
print("2. tahminde 1249 dediğinizi varsayalım. Buna da +2 -1 olarak yanıt
vereceğim. Çünkü 2 adet doğru sayı doğru yerde,")
print("1 adet doğru sayı yanlış yerde.")
input("Hazır olduğunda <Enter>a bas.") # hit enter when ready
pick()
print(sayı[0]+sayı[1]+sayı[2]+sayı[3])#testing for me
testpick()
tahmin_test()
print("Bir saniye, hesaplıyorum...")# calculating effect pause
time.sleep(3)
tahmin = str(tahmin)
sayı = str(sayı)
#below x a b y are not used. Was planned to be used but wasn't.
x = 0
a = 0
b = 0
d = 0
y = 0
dsdy = 0#right number right place variable
dsyy = 0#right number wrong place variable 1
dsyy1 = 0#right number wrong place variable 2
abc = 0#another variable to sum dsyy and dsyy1 variables
test_sayısı = [sayı[0], sayı[1], sayı[2], sayı[3]]# for me to see
print(test_sayısı)#for me to see
test_tahmini = [tahmin[0], tahmin[1], tahmin[2], tahmin[3]]#for me to see
print(test_tahmini)#for me to see
for d in range(0, 4):# test the corresponding respective digits for matches
d = int(d)
if sayı[d] == tahmin[d]:
dsdy = int(dsdy) + 1
#print("dyds yok maalesef")
for d in range(1,4): # test the first three combinations for matched digits
in wrong decimal places
if sayı[0] == tahmin[d]:#test
dsyy1 = int(dsyy1) + 1
else:
continue
def sontest():# test all the remaining combinations, which I could not form
into a logical loop so the below stupidity.
global dsyy
if sayı[1] == tahmin[0]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[1] == tahmin[2]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[1] == tahmin[3]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[2] == tahmin[0]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[2] == tahmin[1]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[2] == tahmin[3]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[3] == tahmin[0]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[3] == tahmin[1]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[3] == tahmin[2]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[0] == tahmin[1]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[0] == tahmin[2]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
if sayı[0] == tahmin[3]:
dsyy = int(dsyy) + 1
else:
dsyy = int(dsyy)
sontest()
abc = int(dsyy1) + int(dsyy)
print("+" + str(dsdy))
print("-" + str(abc))
input("Press <Enter> to continue")
print ("afferim len dümbük !")
quit()
正如评论中提到的:这不是你应该在这里提问的方式。你需要表现出一些(编码)努力。请参加游览, 阅读如何提问 并提供一个最小、完整且可验证的示例 这重现了你的问题。
尽管如此,我对如何解决这个问题很感兴趣;这是我的尝试。我使用
collections.Counter
是为了允许重复的数字。这些都没有经过彻底测试,但应该可以帮助您开始。
from collections import Counter
def compare(n, guess):
not_matching_digits = Counter(guess) - Counter(n)
matching_digits = len(n) - sum(not_matching_digits.values())
right_place = sum(1 for i0, i1 in zip(n, guess) if i0 == i1)
wrong_place = matching_digits - right_place
return right_place, - wrong_place