Python编程学习第一篇——制作一个小游戏休闲一下

到上期结束,我们已经学习了Python语言的基本数据结构,除了数值型没有介绍,数值型用的非常广,但也是最容易理解的,将在未来的学习中带大家直接接触和学习掌握。后续我们会开始学习这门语言的一些基础语法和编程技巧,在这之前我们休闲一下,写一个小游戏娱乐一下。

小戏用到了Python内置的基础图形库turtle,用到了random来生成随机数,下面来看一下小游戏的效果,比较简陋。

首先运行程序,弹出游戏窗口,并提示,选择哪个颜色的乌龟会赢。

我们输入:red,鼠标点击OK,

屏幕上开始初始乌龟,一共出现6只不同颜色的乌龟,当它们站在起跑线上后,开始起跑。

小乌龟奋力向前跑去,这次你很幸运,押对了!恭喜你,你的红色小乌龟赢了比赛。

我们再来运行一次,这次我们还是选择red(红色)小乌龟,这次运气不太好,我们失败了。

下面分享一下小游戏程序的完整代码:

python 复制代码
import turtle
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)

user_bet = screen.textinput(title="Place your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [100, 60, 20, -20, -60, -100]
all_turtles = []
for turtle_index in range(0,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-230, y = y_positions[turtle_index])
    all_turtles.append(new_turtle)


is_race_on = True
while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 200:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"You've won!, The {winning_color} turtle is the winner.")
            else:
                print(f"You've lost!, The {winning_color} turtle is the winner.")
            break
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)
                                             

好了,本期到此结束,期待下期我们再来快乐的学习!

相关推荐
Hello 0 17 小时前
视频号直播视频录制
python·音视频·流媒体·直播视频录制
FreeCode7 小时前
LangSmith本地部署LangGraph应用
python·langchain·agent
mit6.8247 小时前
py期中实验选题:实现天气预测
python·算法
Rolei_zl8 小时前
AIGC(生成式AI)试用 41 -- 程序(Python + OCR)-3
python·aigc
eybk8 小时前
使用Beeware开发文件浏览器获取Android15的文件权限
python
柒柒钏8 小时前
VSCode 终端配置与 Python 虚拟环境使用指南
ide·vscode·python
环己酮8 小时前
py数据科学学习笔记day4-空间数据统计分析与可视化(2)
python
q***48259 小时前
基于python语言的网页设计(手把手教你设计一个个人博客网站)
开发语言·python
qq_22589174669 小时前
基于Python+Django餐饮评论大数据分析与智能推荐系统 毕业论文
开发语言·后端·python·信息可视化·数据分析·django
FreakStudio9 小时前
串口协议解析实战:以 R60ABD1 雷达为例,详解 MicroPython 驱动中数据与业务逻辑的分离设计
python·单片机·pycharm·嵌入式·面向对象·硬件·电子diy