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)
                                             

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

相关推荐
哈里谢顿8 分钟前
Python 依赖注入详解
python
冬天vs不冷35 分钟前
Java基础(九):Object核心类深度剖析
java·开发语言·python
TS的美梦36 分钟前
【1:1复刻R版】python版火山图函数一键出图
开发语言·python·r语言·scanpy·火山图
CF14年老兵1 小时前
Python万物皆对象:从懵懂到顿悟的奇妙之旅
后端·python·trae
这里有鱼汤1 小时前
发现个用《道德经》+价值投资大咖的智慧,做A股的AI诊股神器,居然还开源了
python
陈天伟教授1 小时前
(二)Python + 地球信息科学与技术 (GeoICT)=?
开发语言·python
之歆2 小时前
大模型微调分布式训练-大模型压缩训练(知识蒸馏)-大模型推理部署(分布式推理与量化部署)-大模型评估测试(OpenCompass)
人工智能·笔记·python
人工干智能2 小时前
pygame的帧处理中,涉及键盘的有`pg.event.get()`与`pg.key.get_pressed()` ,二者有什么区别与联系?
python·游戏·计算机外设·pygame
R-G-B2 小时前
【P18 3-10】OpenCV Python—— 鼠标控制,鼠标回调函数(鼠标移动、按下、。。。),鼠标绘制基本图形(直线、圆、矩形)
python·opencv·计算机外设·鼠标回调函数·鼠标控制·鼠标移动·鼠标绘制图形
IT古董5 小时前
第四章:大模型(LLM)】06.langchain原理-(3)LangChain Prompt 用法
java·人工智能·python