python 实现猜4位数字的小游戏,初学了数据类型

猜一个四位数,没有相同数字.用户每猜一个数字,显示出“完全猜中的数字个数”和“猜中数字但位置错误的数字个数”,比如nAmB,数字n表示猜中的位置正确的数字个数,数字m表示数字正确而位置不对的数字个数。例如,正确答案为3864,如果用户猜8234,则显示:1A2B,数字1表示数字4及其位置猜对了,数字3和8这两个数字猜对了,但是位置没对,记为2B。然后,用户根据游戏提示的信息继续猜,直到猜中为止。设计思路产生随机数0-9,用列表存储以字符串类型的数字,不涉及计算 字符串 str,;输入数字,用while循环判断输入的数字是否符合要求,4个不同的数.列表转化集合用于删除列表中相同的值(即重复的数字).每猜一次计次数,可以设计成绩,越少用猜对,成绩越高.

代码如下:

# -*- coding=utf-8 -*-
#猜数字,原文曲星上的小游戏.算法很简单,4个不同的数字,猜到数字正确位置也正确记为A,只有数字正确但位置不对的记为B,猜到4个全部正确为止.
import random

def creatNums():
    n=4
    numbers=[]
    while n>0:
        number= str(random.randint(0,9))
        while number in numbers:#当出现重复数字时,再重新生成新的随机数字.
            number = str(random.randint(0, 9))
        numbers.append(number)
        n-=1
    return (numbers)
def numjud(numbers,gnums):
    i=npc = nc = 0
    for n in gnums:
        if n in numbers:
            nc += 1
            if numbers[i]==gnums[i]:
                npc += 1
                nc -= 1
        i += 1
    print('{}A{}B'.format(npc,nc)) #判断完全正确和仅位置错误的个数
    return npc
print('游戏开始了,请你猜4个数字[0-9]:)
numbers = creatNums()
npc=0
guesstimes=0
while npc<4:#当完全正确的个数不到4个时继续猜.
    while True: #循环判断输入的格式
        inputnums = input('请输入4个不同数字:')
        if len(inputnums)==4 and inputnums.isdigit():
            gnums = list(inputnums)
            if len(set(gnums))==4:#用集合删除相同元素,长度不变就说明无重复数字.
                break
            else:
                print('数字不能重复!')
        else:
            print('输入有错误!')
    gnums = list(inputnums)
    npc=numjud(numbers, gnums)
    guesstimes += 1
if guesstimes<8:
    print('你真棒,用了{}次就猜对了'.format(guesstimes))
elif guesstimes<12:
    print('恭喜!你猜对了,用了{}次机会'.format(guesstimes))
else: print('你终于猜对了,要多动脑子想一想居然用了{}次才猜对'.format(guesstimes))
input("按回车退出")

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值