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)
                                             

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

相关推荐
zh路西法9 分钟前
【Qwen2.5本地部署】超简单pytorch-gpu部署教程
人工智能·pytorch·python
狐狐生风16 分钟前
LangGraph Human-in-the-loop 全解
python·langchain·prompt·langgraph·agentai
倒霉熊dd28 分钟前
Python 学习(第二部分:函数、模块与面向对象编程)
前端·数据库·python
铁皮哥31 分钟前
【力扣题解】LeetCode 25. K 个一组翻转链表
java·数据结构·windows·python·算法·leetcode·链表
lbb 小魔仙1 小时前
告别腾讯会议40分钟限制:用ToDesk协作版开在线会议,免费不限时远程会议新方案
python·langchain·jenkins
凯瑟琳.奥古斯特1 小时前
PyTorch动态计算图详解
人工智能·pytorch·python·深度学习
一个数据大开发1 小时前
企业知识工程的三条路线:Neo4j 知识中台、Agent + Action 与本体原生 Runtime
大数据·python·neo4j
没有感情的robot1 小时前
网页录制方法总结
python
m0_738120721 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(二)
python·网络协议·tcp/ip·安全·网络安全
Chase_______2 小时前
Java 基础语言 ③:流程控制与数组——从条件分支到数组遍历,一篇通关
java·数据库·python