Python项目:有记录的猜数字游戏

这里制作了一个猜数字的游戏,主要涉及到Python知识点:

1. input([prompt])
prompt是输入的提示语,使用该方法后,终端会等待输入,并将输入对象作为string类型返回
2. random.randint(a, b)
随机返回a至b之间的一个整数,整数的范围是a<= x <=b
3. file
文件的操作,这里用到的如下部分

  • open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    打开一个文件,并返回一个file对象。
    file参数可以是文件路径(相对路径或决定路径都可以)。
    mode参数表示打开文件的模式,
    r 只读
    w 只写,首先删除文件内容
    x 执行文件
    a 写文件,将内容追加在文末
    b 二进制方式,返回bytes对象,没有编码
    t 文本模式,返回string对象,有编码
    +更新模式(读写)
    模式可以叠加,以实现复合功能
    buffering参数设置缓冲方式
    0用于关闭缓冲,只可在mode=‘b’模式下使用
    1用于行缓冲,只可在mode=‘t’模式下使用
    大于1设置缓冲值,单位bytes
    encoding参数设置编码方式
    errors参数定义编码或解码错误发生时如何处理
    newline参数控制换行符
  • write(data)
    将data写入文件中
  • close()
    关闭文件,使用该方法后,文件对象将不能被调用。
  • readlines([sizeint[,keepends]])
    读取所有的行内容,并将各行内容组成列表,将列表返回。
    sizeint参数指定读取文件的bytes数
  • seek(pos,whence=0)
    设置文件当前位置。
    pos参数 设定文件位置(字节)
    whence参数 0表示文件开始位置,1表示相对当前文件位置,2表示相对文件末
'''
Author: Ethan
Date: 2021-04-15 06:18:04
LastEditTime: 2021-04-17 08:33:15
Description: a guess number game
FilePath: \test\game.py
'''
def check_user(file_path, name) :
#check if this is a new user
    file = open(file_path,mode='a+')
    file.seek(0,0)
    user_status = 0
    for line in file.readlines():
        if line.startswith(name):
            user_status = 1
            break
    file.close()
    return user_status   

def print_ui(user_status, name):
#base on user status print different UI
    if user_status == 0:
        print(22*'*')
        print("Welcome to new game !")
        print(22*' ')
        print("****    "+name+"    ****")
        print(22*' ')
        print(22*'*')
    else:
        print(20*'*')
        print("Welcome back to game !")
        print("****    "+name+"    ****")
        print(20*' ')
        print(20*'*')

def update_file(file_path, name, user_status, cur_score):
#update record file
    status = check_user(file_path, name)
    if status == 0:
        file = open(file_path,mode="a+")
        content = name + "**"+ str(cur_score)+'\n'
        file.write(content)
        file.close()
    else:
        file = open(file_path,mode='r+')
        content = ''
        user_content = name + "**"+ str(cur_score)+'\n'
        for line in file.readlines():
            if line.startswith(name):
                org_score = int(line.split("**")[1])
                if cur_score < org_score:
                    content += user_content
                    continue
            content += line
        file.seek(0,0)
        file.write(content)
        file.close()
        
user = input("please input your name:")

mode = check_user(r'E:\software develop\test\record.txt',name= user)

print_ui(user_status= mode,name=user)

import random
# used to generate random number
level = input("Please choose your level: 1 for high, 2 for median, 3 for low:")
game_level = {
    '1':100,
    '2':50,
    '3':10
}
tar_num = random.randint(0,game_level[level])
flag = True
count = 0
while flag:
    guess_num = int(input("please input your guess number:"))
    count += 1
    if guess_num == tar_num:
        print("Congratulations! You Get the correct number, you score is ", count)
        update_file(r'E:\software develop\test\record.txt',name= user,user_status= mode, cur_score = count)
        exit_or_not = input("Do you want to play again?\n Yes for continue \n No for exit:")
        if(exit_or_not.strip().lower().startswith('y')):
            level = input("Please choose your level: 1 for high, 2 for median, 3 for low:")
            tar_num = random.randint(0,game_level[level])
            count = 0
            continue
        else:
            print(22*'*')
            print(22*' ')
            print("Hope to see you again")
            print(22*' ')
            print(22*'*')
            flag = False        
    elif guess_num < tar_num:
        print("Too small, try larger one")
    else:
        print("Too large, try smaller one")
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习_程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值