当前位置: 首页 > 科技观察

用Python开发一个简单的猜数游戏

时间:2023-03-22 15:28:08 科技观察

本文介绍如何使用Python制作一个简单的猜数游戏。游戏规则玩家将猜测一个数字。如果猜对了,则玩家获胜。如果不正确,程序会提示玩家猜中的数字与实际数字相比是“高”还是“低”,以此类推,直到玩家猜对数字。为Python3做好准备首先,您需要在计算机上安装Python。可以从Python官网下载安装。本教程需要最新版本的Python3(版本3.x.x)。确保选中复选框以将Python添加到您的PATH变量。如果不这样做,运行该程序将非常困难。现在,在您的设备上打开一个文本/代码编辑器。就个人而言,我更喜欢使用Brackets。Notepad预装在Windows上,TextEdit包含在MacOS上,Vim可供Linux用户使用。打开文本编辑器,保存新文件。我把它命名为main.py,但你可以随意命名,只要它以.py结尾即可。本教程的编码说明将作为注释包含在代码中。在Python中,注释以#开头,一直持续到行尾。fromkeras.layersimportConv2D,MaxPooling2D,GlobalAveragePooling2D#First,weneedtoimportthe'random'module.#Thismodulecontainsthefunctionalityweneedtobeabletorandomlyselectthewinningnumber.importrandom#Now,weneedtoselectarandomnumber.#Thislinewillsetthevariable'correct'tobeequaltoarandomintegerbetween1and10.correct=random.randint(1,10)#Let'sgettheuser'sfirstguessusingthe'input'function.guess=input("Enteryourguess:")#Rightnow,theuser'sinputisformattedasastring.#Wecanformatitasanintegerusingthe'int'function.guess=int(guess)#Let'sstartaloopthatwillcontinueuntiltheuserhasguessedcorrectly.#Wecanusethe'!='operatortomean'notequal'.whileguess!=correct:#Everythinginthisloopwillrepeatuntiltheuserhasguessedcorrectly.#Let'sstartbygivingtheuserfeedbackontheirguess.Wecandothisusingthe'if'statement.#Thisstatementwillcheckifacomparisonistrue.#Ifitis,thecodeinsidetheif语句将运行。ifguess>正确:#Thiscodewillruniftheuserguessedtoohigh.#Wecanshowam使用'print'函数向用户发送消息。打印(“你猜得太高了。尝试猜测更低。”)else:#'else'语句添加到'if'语句。#Itwillruniftheconditionofthe'if'statementisfalse.#Inthiscase,itwillruniftheuserguessedtoolow,sowecangivethemfeedback.printed("Too'veguess.Tryguessinghigher.")#Nowweneedtolettheuserguessagain.#NoticehowIamcombiningthetwolinesofguessingcodetomakejustoneline.guess=int(input("Enteryourguess:"))#Ifauser'sguessisintheloopIfwhile'while'代码仍然不正确,thecode在代码中验证了这一点,这意味着他们猜对了,让我们这么说吧。打印(“恭喜!你猜对了。”)另外,请随意更改程序中的任何内容。例如,您可以将正确的数字设置为1到100而不是1到10,您可以更改程序在print()函数中所说的内容。您可以根据需要编写代码。运行程序根据您的操作系统,打开命令提示符(Windows/Linux)或终端(Mac)。按顺序尝试以下每个命令。如果正确安装了Python,至少其中一个应该可以工作。pythonC:/Users/username/Desktop/main.pypyC:/Users/username/Desktop/main.python3C:/Users/username/Desktop/main.py确保替换C:/Users/username/Desktop/main.pywithPython文件的完整路径。程序运行后,对其进行测试并玩几次!完成后,按向上箭头键复制上一条命令,然后按Enter再次运行它。这是一个没有任何注释的代码版本:importrandomcorrect=random.randint(1,10)guess=input("Enteryourguess:")guess=int(guess)whileguess!=correct:ifguess>correct:print("You'veguessedtoohigh.Tryguessinglower.")else:print("You'veguessedtolower.Tryguessinghigher.")guess=int(input("Enteryourguess:"))print("恭喜!你猜对了。")