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

目录
相关文章
|
2月前
|
Python
用python进行视频剪辑源码
这篇文章提供了一个使用Python进行视频剪辑的源码示例,通过结合moviepy和pydub库来实现视频的区间切割和音频合并。
55 2
|
1月前
|
自然语言处理 Java 编译器
为什么要看 Python 源码?它的结构长什么样子?
为什么要看 Python 源码?它的结构长什么样子?
25 2
|
1月前
|
Python
源码解密 Python 的 Event
源码解密 Python 的 Event
33 1
|
1月前
|
数据采集 前端开发 Python
Python pygame 实现游戏 彩色 五子棋 详细注释 附源码 单机版
Python pygame 实现游戏 彩色 五子棋 详细注释 附源码 单机版
63 0
|
3月前
|
Ubuntu Linux 数据安全/隐私保护
使用Cython库包对python的py文件(源码)进行加密,把python的.py文件生成.so文件并调用
本文介绍了在Linux系统(Ubuntu 18.04)下将Python源代码(`.py文件`)加密为`.so文件`的方法。首先安装必要的工具如`python3-dev`、`gcc`和`Cython`。然后通过`setup.py`脚本使用Cython将`.py文件`转化为`.so文件`,从而实现源代码的加密保护。文中详细描述了从编写源代码到生成及调用`.so文件`的具体步骤。此方法相较于转化为`.pyc文件`提供了更高的安全性。
125 2
|
3月前
|
测试技术 Python
python自动化测试中装饰器@ddt与@data源码深入解析
综上所述,使用 `@ddt`和 `@data`可以大大简化写作测试用例的过程,让我们能专注于测试逻辑的本身,而无需编写重复的测试方法。通过讲解了 `@ddt`和 `@data`源码的关键部分,我们可以更深入地理解其背后的工作原理。
47 1
|
3月前
|
JSON 算法 API
京东以图搜图功能API接口调用算法源码python
京东图搜接口是一款强大工具,通过上传图片即可搜索京东平台上的商品。适合电商平台、比价应用及需商品识别服务的场景。使用前需了解接口功能并注册开发者账号获取Key和Secret;准备好图片的Base64编码和AppKey;生成安全签名后,利用HTTP客户端发送POST请求至接口URL;最后解析JSON响应数据以获取商品信息。
|
3月前
|
开发者 Python
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
深入解析Python `httpx`源码,探索现代HTTP客户端的秘密!
85 1
|
3月前
|
开发者 Python
深入解析Python `requests`库源码,揭开HTTP请求的神秘面纱!
深入解析Python `requests`库源码,揭开HTTP请求的神秘面纱!
172 1
|
3月前
|
算法 关系型数据库 程序员
程序员必备技能)基于Python的鼠标与键盘控制实战扩展与源码
这篇文章是关于如何使用Python的`pyautogui`库来控制鼠标和键盘进行各种操作,包括移动、点击、滚轮控制以及键盘的按键和快捷键输出,并介绍了如何结合图像处理和计算机视觉技术来扩展其应用。
下一篇
无影云桌面