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)
                                             

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

相关推荐
LadenKiller17 小时前
近期AI量化辅助,工具重点要跟学习阶段变化
人工智能·python
phltxy18 小时前
LangChain_Agent中间件实战
人工智能·python·深度学习·语言模型·中间件·langchain
axinawang18 小时前
第14课:查找、统计、分割字符串
python
倒流时光三十年18 小时前
第一阶段 02 · Mapping 与数据类型(text vs keyword 是重点)
后端·python·django
小大宇18 小时前
python蓝图、拦截器、异常处理、redis队列、线程池、控制台及日志文件输出
python
喝茶与编码18 小时前
真实业务场景:高并发 Upsert 死锁频发?InnoDB 锁机制与重试机制深度解析
数据库·python
倒流时光三十年19 小时前
第一阶段 05 · Java 客户端查询类详解(Query / SearchCriteria / Response 与复杂拼接)
java·开发语言·python
CTA终结者19 小时前
近期AI量化学习,把规则改写接到策略开发
人工智能·python
有Li19 小时前
使用整合电子健康记录的大语言模型智能体实现前列腺癌患者教育个性化文献速递/医学智能体前沿
人工智能·python·机器学习·语言模型·医学生
米码收割机19 小时前
【Python】Flask+SQLite_web 宠物领养系统 (源码+文档)【独一无二】
前端·python·flask