10个python经典小游戏(上)(动图演示+源码分享)(上)

简介: 10个python经典小游戏(上)(动图演示+源码分享)

1.贪吃蛇


👉游戏规则:使用方向键控制蛇去吃球。每吃一次球,蛇身就长出一格。吃到自己或者出界游戏结束。


from random import randrange
from turtle import *
from freegames import square, vector
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
def change(x, y):
    """Change snake direction."""
    aim.x = x
    aim.y = y
def inside(head):
    """Return True if head inside boundaries."""
    return -200 < head.x < 190 and -200 < head.y < 190
def move():
    """Move snake forward one segment."""
    head = snake[-1].copy()
    head.move(aim)
    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')
        update()
        return
    snake.append(head)
    if head == food:
        print('Snake:', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    else:
        snake.pop(0)
    clear()
    for body in snake:
        square(body.x, body.y, 9, 'black')
    square(food.x, food.y, 9, 'green')
    update()
    ontimer(move, 100)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
move()
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/9dd03ec7d1314e5e828456704eb8c234.gif#pic_center


2.吃豆人


👉游戏规则:用箭头导航控制黄色吃豆人吃掉所有白色食物,若被红色的鬼魂抓住,游戏结束。


from random import choice
from turtle import *
from freegames import floor, vector
state = {'score': 0}
path = Turtle(visible=False)
writer = Turtle(visible=False)
aim = vector(5, 0)
pacman = vector(-40, -80)
ghosts = [
    [vector(-180, 160), vector(5, 0)],
    [vector(-180, -160), vector(0, 5)],
    [vector(100, 160), vector(0, -5)],
    [vector(100, -160), vector(-5, 0)],
]
# fmt: off
tiles = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1, 1, 1, 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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
# fmt: on
def square(x, y):
    """Draw square using path at (x, y)."""
    path.up()
    path.goto(x, y)
    path.down()
    path.begin_fill()
    for count in range(4):
        path.forward(20)
        path.left(90)
    path.end_fill()
def offset(point):
    """Return offset of point in tiles."""
    x = (floor(point.x, 20) + 200) / 20
    y = (180 - floor(point.y, 20)) / 20
    index = int(x + y * 20)
    return index
def valid(point):
    """Return True if point is valid in tiles."""
    index = offset(point)
    if tiles[index] == 0:
        return False
    index = offset(point + 19)
    if tiles[index] == 0:
        return False
    return point.x % 20 == 0 or point.y % 20 == 0
def world():
    """Draw world using path."""
    bgcolor('black')
    path.color('blue')
    for index in range(len(tiles)):
        tile = tiles[index]
        if tile > 0:
            x = (index % 20) * 20 - 200
            y = 180 - (index // 20) * 20
            square(x, y)
            if tile == 1:
                path.up()
                path.goto(x + 10, y + 10)
                path.dot(2, 'white')
def move():
    """Move pacman and all ghosts."""
    writer.undo()
    writer.write(state['score'])
    clear()
    if valid(pacman + aim):
        pacman.move(aim)
    index = offset(pacman)
    if tiles[index] == 1:
        tiles[index] = 2
        state['score'] += 1
        x = (index % 20) * 20 - 200
        y = 180 - (index // 20) * 20
        square(x, y)
    up()
    goto(pacman.x + 10, pacman.y + 10)
    dot(20, 'yellow')
    for point, course in ghosts:
        if valid(point + course):
            point.move(course)
        else:
            options = [
                vector(5, 0),
                vector(-5, 0),
                vector(0, 5),
                vector(0, -5),
            ]
            plan = choice(options)
            course.x = plan.x
            course.y = plan.y
        up()
        goto(point.x + 10, point.y + 10)
        dot(20, 'red')
    update()
    for point, course in ghosts:
        if abs(pacman - point) < 20:
            return
    ontimer(move, 100)
def change(x, y):
    """Change pacman aim if valid."""
    if valid(pacman + vector(x, y)):
        aim.x = x
        aim.y = y
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
writer.goto(160, 160)
writer.color('white')
writer.write(state['score'])
listen()
onkey(lambda: change(5, 0), 'Right')
onkey(lambda: change(-5, 0), 'Left')
onkey(lambda: change(0, 5), 'Up')
onkey(lambda: change(0, -5), 'Down')
world()
move()
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/cb513acc18e24eb9a9948247023c5966.gif#pic_center


3.加农炮


👉游戏规则:点击屏幕发射炮弹。炮弹在它的路径上弹出蓝色气球。在气球穿过屏幕之前把它们全部弹出。


from random import randrange
from turtle import *
from freegames import vector
ball = vector(-200, -200)
speed = vector(0, 0)
targets = []
def tap(x, y):
    """Respond to screen tap."""
    if not inside(ball):
        ball.x = -199
        ball.y = -199
        speed.x = (x + 200) / 25
        speed.y = (y + 200) / 25
def inside(xy):
    """Return True if xy within screen."""
    return -200 < xy.x < 200 and -200 < xy.y < 200
def draw():
    """Draw ball and targets."""
    clear()
    for target in targets:
        goto(target.x, target.y)
        dot(20, 'blue')
    if inside(ball):
        goto(ball.x, ball.y)
        dot(6, 'red')
    update()
def move():
    """Move ball and targets."""
    if randrange(40) == 0:
        y = randrange(-150, 150)
        target = vector(200, y)
        targets.append(target)
    for target in targets:
        target.x -= 0.5
    if inside(ball):
        speed.y -= 0.35
        ball.move(speed)
    dupe = targets.copy()
    targets.clear()
    for target in dupe:
        if abs(target - ball) > 13:
            targets.append(target)
    draw()
    for target in targets:
        if not inside(target):
            return
    ontimer(move, 50)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/decb526db91c46e6b222ded8be4d2f75.gif#pic_center


4.四子棋


👉 游戏规则:单击行可放置光盘。第一个垂直、水平或对角连接四张光盘的玩家获胜。


from turtle import *
from freegames import line
turns = {'red': 'yellow', 'yellow': 'red'}
state = {'player': 'yellow', 'rows': [0] * 8}
def grid():
    """Draw Connect Four grid."""
    bgcolor('light blue')
    for x in range(-150, 200, 50):
        line(x, -200, x, 200)
    for x in range(-175, 200, 50):
        for y in range(-175, 200, 50):
            up()
            goto(x, y)
            dot(40, 'white')
    update()
def tap(x, y):
    """Draw red or yellow circle in tapped row."""
    player = state['player']
    rows = state['rows']
    row = int((x + 200) // 50)
    count = rows[row]
    x = ((x + 200) // 50) * 50 - 200 + 25
    y = count * 50 - 200 + 25
    up()
    goto(x, y)
    dot(40, player)
    update()
    rows[row] = count + 1
    state['player'] = turns[player]
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(tap)
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/e4e794a153434a4a846ddf9b0f29aea3.gif#pic_center


5. Fly Bird


👉 游戏规则:点击屏幕来拍打鸟的翅膀。飞过屏幕被黑色乌鸦碰到,游戏结束。


from random import *
from turtle import *
from freegames import vector
bird = vector(0, 0)
balls = []
def tap(x, y):
    """Move bird up in response to screen tap."""
    up = vector(0, 30)
    bird.move(up)
def inside(point):
    """Return True if point on screen."""
    return -200 < point.x < 200 and -200 < point.y < 200
def draw(alive):
    """Draw screen objects."""
    clear()
    goto(bird.x, bird.y)
    if alive:
        dot(10, 'green')
    else:
        dot(10, 'red')
    for ball in balls:
        goto(ball.x, ball.y)
        dot(20, 'black')
    update()
def move():
    """Update object positions."""
    bird.y -= 5
    for ball in balls:
        ball.x -= 3
    if randrange(10) == 0:
        y = randrange(-199, 199)
        ball = vector(199, y)
        balls.append(ball)
    while len(balls) > 0 and not inside(balls[0]):
        balls.pop(0)
    if not inside(bird):
        draw(False)
        return
    for ball in balls:
        if abs(ball - bird) < 15:
            draw(False)
            return
    draw(True)
    ontimer(move, 50)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/b0046011e33a4530aa42e6899bb16894.gif#pic_center

目录
相关文章
|
3月前
|
机器学习/深度学习 监控 算法
基于mediapipe深度学习的手势数字识别系统python源码
本内容涵盖手势识别算法的相关资料,包括:1. 算法运行效果预览(无水印完整程序);2. 软件版本与配置环境说明,提供Python运行环境安装步骤;3. 部分核心代码,完整版含中文注释及操作视频;4. 算法理论概述,详解Mediapipe框架在手势识别中的应用。Mediapipe采用模块化设计,包含Calculator Graph、Packet和Subgraph等核心组件,支持实时处理任务,广泛应用于虚拟现实、智能监控等领域。
|
10天前
|
小程序 PHP 图形学
热门小游戏源码(Python+PHP)下载-微信小程序游戏源码Unity发实战指南​
本文详解如何结合Python、PHP与Unity开发并部署小游戏至微信小程序。涵盖技术选型、Pygame实战、PHP后端对接、Unity转换适配及性能优化,提供从原型到发布的完整指南,助力开发者快速上手并发布游戏。
|
2月前
|
算法 数据可视化 数据挖掘
基于EM期望最大化算法的GMM参数估计与三维数据分类系统python源码
本内容展示了基于EM算法的高斯混合模型(GMM)聚类实现,包含完整Python代码、运行效果图及理论解析。程序使用三维数据进行演示,涵盖误差计算、模型参数更新、结果可视化等关键步骤,并附有详细注释与操作视频,适合学习EM算法与GMM模型的原理及应用。
|
2月前
|
API 数据安全/隐私保护 开发者
企业微信自动加好友软件,导入手机号批量添加微信好友,python版本源码分享
代码展示了企业微信官方API的合规使用方式,包括获取access_token、查询部门列表和创建用户等功能
|
3月前
|
人工智能 搜索推荐 数据可视化
用 Python 制作简单小游戏教程:手把手教你开发猜数字游戏
本教程详细讲解了用Python实现经典猜数字游戏的完整流程,涵盖从基础规则到高级功能的全方位开发。内容包括游戏逻辑设计、输入验证与错误处理、猜测次数统计、难度选择、彩色输出等核心功能,并提供完整代码示例。同时,介绍了开发环境搭建及调试方法,帮助初学者快速上手。最后还提出了图形界面、网络对战、成就系统等扩展方向,鼓励读者自主创新,打造个性化游戏版本。适合Python入门者实践与进阶学习。
331 1
|
2月前
|
机器人 API 数据安全/隐私保护
QQ机器人插件源码,自动回复聊天机器人,python源码分享
消息接收处理:通过Flask搭建HTTP服务接收go-cqhttp推送的QQ消息47 智能回复逻辑
|
5月前
|
前端开发 JavaScript 关系型数据库
基于python的租房网站-房屋出租租赁系统(python+django+vue)源码+运行
该项目是基于python/django/vue开发的房屋租赁系统/租房平台,作为本学期的课程作业作品。欢迎大家提出宝贵建议。
168 6
|
5月前
|
JavaScript 前端开发 关系型数据库
基于Python+Vue开发的体育场馆预约管理系统源码+运行
本项目为大学生课程设计作业,采用Python和Vue技术构建了一个体育场馆预约管理系统(实现前后端分离)。系统的主要目标在于帮助学生理解和掌握Python编程知识,同时培养其项目规划和开发能力。参与该项目的学习过程,学生能够在实际操作中锻炼技能,为未来的职业发展奠定良好的基础。
134 3
|
5月前
|
前端开发 JavaScript 关系型数据库
基于Python+Vue开发的房产销售管理系统源码+运行
基于Python+Vue开发的房产销售管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的房产销售管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
97 2
|
Linux C语言 开发者
源码安装Python学会有用还能装逼 | 解决各种坑
相信朋友们都看过这个零基础学习Python的开篇了
643 0
源码安装Python学会有用还能装逼 | 解决各种坑

推荐镜像

更多