In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use Python programming to build a simple dice game". In daily operation, I believe many people have doubts about how to use Python programming to build a simple dice game. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use Python programming to build a simple dice game". Next, please follow the editor to study!
Python is a very popular programming language that can be used to create desktop applications, 3D graphics, video games, and even websites. It is a very good preferred programming language because it is easy to learn, unlike some complex languages, such as C, C++, or Java. Even so, Python is powerful and robust enough to create advanced applications and is suitable for almost all industries that use computers. Python is a very good programming language for both experienced programmers and inexperienced novices.
Install Python
Before you can learn Python, you need to install it:
Linux: if you are using a Linux system, Python is already included. However, if you are sure you want to use Python 3. You should check the version of Python you installed, open a terminal window and type:
Python3-V
If prompted that the command is not found, you need to install Python 3 from your package manager.
MacOS: if you are using a Mac, you can check the introduction of Linux above to confirm that Python 3 is installed. MacOS does not have a built-in package manager, so if you find that Python 3 is not installed, you can install it from python.org/downloads/mac-osx. Even if macOS has Python 2 installed, you should still learn Python 3.
Windows: Microsoft Windows currently does not have Python installed. Install it from python.org/downloads/windows. Be sure to select Add Python to PATH in the installation wizard to put the Python executor in the search path.
Run in IDE
To write programs in Python, you need to prepare a text editor, and using an integrated development environment (IDE) is very practical. IDE integrates some convenient and useful Python functions in a text editor. IDLE 3 and NINJA-IDE are two options you can consider:
IDLE 3
A basic IDE that comes with Python is called IDLE.
IDLE
It is about keyword highlighting, can help you detect spelling errors, and has a "run" button to easily and quickly test the code.
To use it:
On Linux or macOS, launch a terminal window and enter idle3.
In Windows, start Python 3 from the start menu.
If you don't see Python in the start menu, start the Windows command prompt by typing cmd in the start menu, and then type C:\ Windows\ py.exe.
If it's not running, try reinstalling Python. And verify that "Add Python to PATH" is selected in the installation wizard. Refer to the detailed description in docs.python.org/3/using/windows.html.
If it still doesn't work, use Linux! It's free, as long as you save your Python file to a USB drive, you don't even need to install it to use it.
Ninja-IDE
Ninja-IDE is an excellent Python IDE. Its keyword highlighting features can help you detect spelling errors, quotation marks and parenthesis completion to avoid syntax errors, line numbers (helpful when debugging), indentation tags, and running buttons can easily do quick code testing.
Ninja-IDE
To use it:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Install Ninja-IDE. If you are using Linux, it is very easy to install using the package manager; otherwise, download the appropriate installation version from NINJA-IDE 's website.
Start Ninja-IDE.
Go to the Edit menu and select Preferences Settings.
In the Preferences window, click the Execution tab.
On the Execution tab, change python to python3.
Python3 in Ninja-IDE
Tell Python what he wants to do.
Keyword can tell Python what you want to do. Whether in IDLE or Ninja, go to the File menu and create a new file. For Ninja users: do not create a new project, just create a new file.
In your new empty file, enter the following in IDLE or Ninja:
Print ("Hello world.")
If you are using IDLE, go to the Run menu and select the Run module option.
If you are using Ninja, click the Run File button in the left button bar.
Run the file in Ninja
The keyword print tells Python to print out the text referenced in parentheses.
Although, this is not particularly exciting. Internally, Python can only access basic keywords, such as print, help, the most basic mathematical functions, and so on.
You can use the import keyword to load more keywords. Start a new file in IDLE or Ninja and name it pen.py.
Warning: do not name your file turtle.py, because the file named turtle.py is included in the turtle program you are controlling. Naming your file turtle.py will confuse Python because it will think you will import your own file.
Enter the following code in your file and run it:
Import turtle
Turtle is a very interesting module, try to do this:
Turtle.begin_fill () turtle.forward (100) turtle.left (90) turtle.forward (100) turtle.end_fill ()
Take a look at what shape you have drawn with the turtle module now.
To erase your turtle drawing area, use the turtle.clear () keyword. Think about what happens when you use the turtle.color ("blue") keyword.
Try more complex code:
Import turtle as t import time t.color ("blue") t.begin_fill () counter=0 while counter
< 4: t.forward(100) t.left(90) counter = counter+1 t.end_fill() time.sleep(5) 运行完你的脚本后,是时候探索更有趣的模块了。 通过创建一个游戏来学习 Python 想学习更多的 Python 关键字,和用图形编程的高级特性,让我们来关注于一个游戏逻辑。在这个教程中,我们还将学习一些关于计算机程序是如何构建基于文本的游戏的相关知识,在游戏里面计算机和玩家掷一个虚拟骰子,其中掷的最高的是赢家。 规划你的游戏 在写代码之前,最重要的事情是考虑怎么去写。在他们写代码 之前,许多程序员是先 写简单的文档,这样,他们就有一个编程的目标。如果你想给这个程序写个文档的话,这个游戏看起来应该是这样的: 鸿蒙官方战略合作共建--HarmonyOS技术社区 启动掷骰子游戏并按下 Return 或 Enter 去掷骰子 结果打印在你的屏幕上 提示你再次掷骰子或者退出 这是一个简单的游戏,但是,文档会告诉你需要做的事很多。例如,它告诉你写这个游戏需要下列的组件: 玩家:你需要一个人去玩这个游戏。 AI:计算机也必须去掷,否则,就没有什么输或赢了 随机数:一个常见的六面骰子表示从 1-6 之间的一个随机数 运算:一个简单的数学运算去比较一个数字与另一个数字的大小 一个赢或者输的信息 一个再次玩或退出的提示 制作掷骰子游戏的 alpha 版 很少有程序,一开始就包含其所有的功能,因此,它们的初始版本仅实现最基本的功能。首先是几个定义: 变量是一个经常要改变的值,它在 Python 中使用的非常多。每当你需要你的程序去"记住"一些事情的时候,你就要使用一个变量。事实上,运行于代码中的信息都保存在变量中。例如,在数学方程式 x + 5 = 20 中,变量是 x ,因为字母 x 是一个变量占位符。 整数是一个数字, 它可以是正数也可以是负数。例如,1 和 -1 都是整数,因此,14、21,甚至 10947 都是。 在 Python 中变量创建和使用是非常容易的。这个掷骰子游戏的初始版使用了两个变量: player 和 ai。 在命名为 dice_alpha.py 的新文件中输入下列代码: import random player = random.randint(1,6) ai = random.randint(1,6) if player >Ai: print ("You win") # notice indentation else: print ("You lose")
Start your game and make sure it works.
The basic version of the game has worked very well. It achieves the basic goal of the game, but it doesn't look like a game. The players don't know what they're shaking, the computer doesn't know what they're shaking, and even if the player still wants to play, the game is over.
This is the initial version of the software (commonly known as the alpha version). Now that you are convinced that you have implemented the main part of the game (roll a dice), it is time to add to the program.
Improve the game
In the second version of your game (called the beta version), some improvements will be made to make it look like a game.
1. Describe the result
Don't just tell players whether they win or lose, they are more interested in the result of their throw. Try the following changes in your code:
Player = random.randint (1mai 6) print ("You rolled" + player) ai = random.randint (1m 6) print ("The computer rolled" + ai)
Now, if you run the game, it will crash because Python thinks you're trying to do math. It thinks that you are trying to add the letter You rolled to the player variable, and what is stored in it is a number.
You have to tell Python to handle numbers in player and ai variables as if they were words in a sentence (a string) rather than a number (an integer) in a mathematical equation.
Make the following changes in your code:
Player = random.randint (1mai 6) print ("You rolled" + str (player)) ai = random.randint (1pr 6) print ("The computer rolled" + str (ai))
Run your game now and you will see the result.
2. Slow it down
The computer runs very fast. People can be quick sometimes, but in games, it is often better to have suspense. You can use Python's time function to slow down your game at this tense time.
Import random import time player = random.randint (1pc6) print ("You rolled" + str (player)) ai = random.randint (1pc6) print ("The computer rolls....") time.sleep (2) print ("The computer has rolled a" + str (player)) if player > ai: print ("You win") # notice indentation else: print ("You lose")
Start your game to test the changes.
3. Detection relationship
If you play your game a few more times, you'll find that even if your game looks right, it actually has a bug in it: when the player and the computer shake the same number, it doesn't know what to do.
To check whether one value is equal to another, Python uses = =. That's a "double" equal sign, not one. If you use only one, Python thinks you're trying to create a new variable, but you're actually trying to do math.
When you want to have more choices than the two options (that is, win or lose), you can use Python's elif keyword, which means "otherwise, if". This allows your code to check whether one of the "many" results is true, rather than just checking that the "one" is true.
Modify your code like this:
If player > ai: print ("You win") # notice indentation elif player = = ai: print ("Tie game.") Else: print ("You lose")
Run your game a few more times to see if you can draw a draw with the computer.
Write the final version
The beta version of your dice game functions and feels more like a game than the alpha version. For the final version, let's create your first Python function.
A function is a collection of code that can be called as a separate unit. Functions are very important because most applications have a lot of code, but not all code is run only once. Function enables the application and controls when and what can happen.
Turn your code into this:
Import random import time def dice (): player = random.randint (1Magne6) print ("You rolled" + str (player)) ai = random.randint (1Pie6) print ("The computer rolls....") time.sleep (2) print ("The computer has rolled a" + str (player)) if player > ai: print ("You win" ) # notice indentation else: print ("You lose") print ("Quit? Cont = input () if cont = = "Y" or cont = = "y": exit () elif cont = = "N" or cont = = "n": pass else: print ("I did not understand that. Playing again. ")
In this version of the game, after they play the game, they will ask the player whether to quit or not. If they respond with a Y or y, Python will call its exit function to exit the game.
More importantly, you will create your own function called dice. This dice function doesn't run immediately. In fact, if you try to run your game at this stage, it won't crash, but it won't officially run either. For the dice function to really run and do something, you have to call it in your code.
Add this loop under your existing code, the first two lines are the first two lines above, do not need to type again, and pay attention to what needs to be indented and what is not. Pay attention to the indentation format.
Else: print ("I did not understand that. Playing again.") # main loop while True: print ("Press return to roll your die.") Roll = input () dice ()
The while True code block runs first. Because True is defined as always true, this block of code will run until Python tells it to exit.
The while True code block is a loop. It first prompts the user to start the game, and then it calls your dice function. This is the beginning of the game. When the dice function ends, your loop runs or exits again, depending on the player's answer.
Using loops to run programs is the most common way to write applications. The loop ensures that the application remains available for a long time so that computer users can use the functions in the application.
At this point, the study on "how to program with Python to build a simple dice game" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.