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

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

6.记忆:数字对拼图游戏(欢迎挑战!用时:2min)


👉游戏规则:单击方格用于显示数字。匹配两个数字,方格将显示从而显示图像。


from random import *
from turtle import *
from freegames import path
car = path('car.gif')
tiles = list(range(32)) * 2
state = {'mark': None}
hide = [True] * 64
def square(x, y):
    """Draw white square with black outline at (x, y)."""
    up()
    goto(x, y)
    down()
    color('black', 'white')
    begin_fill()
    for count in range(4):
        forward(50)
        left(90)
    end_fill()
def index(x, y):
    """Convert (x, y) coordinates to tiles index."""
    return int((x + 200) // 50 + ((y + 200) // 50) * 8)
def xy(count):
    """Convert tiles count to (x, y) coordinates."""
    return (count % 8) * 50 - 200, (count // 8) * 50 - 200
def tap(x, y):
    """Update mark and hidden tiles based on tap."""
    spot = index(x, y)
    mark = state['mark']
    if mark is None or mark == spot or tiles[mark] != tiles[spot]:
        state['mark'] = spot
    else:
        hide[spot] = False
        hide[mark] = False
        state['mark'] = None
def draw():
    """Draw image and tiles."""
    clear()
    goto(0, 0)
    shape(car)
    stamp()
    for count in range(64):
        if hide[count]:
            x, y = xy(count)
            square(x, y)
    mark = state['mark']
    if mark is not None and hide[mark]:
        x, y = xy(mark)
        up()
        goto(x + 2, y)
        color('black')
        write(tiles[mark], font=('Arial', 30, 'normal'))
    update()
    ontimer(draw, 100)
shuffle(tiles)
setup(420, 420, 370, 0)
addshape(car)
hideturtle()
tracer(False)
onscreenclick(tap)
draw()
done()


游戏演示:


image.png


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


7.乒乓球


👉游戏规则:用键盘上下移动划桨,谁先丢失球,谁输!(左ws上下,右ik上下)


from random import choice, random
from turtle import *
from freegames import vector
def value():
    """Randomly generate value between (-5, -3) or (3, 5)."""
    return (3 + random() * 2) * choice([1, -1])
ball = vector(0, 0)
aim = vector(value(), value())
state = {1: 0, 2: 0}
def move(player, change):
    """Move player position by change."""
    state[player] += change
def rectangle(x, y, width, height):
    """Draw rectangle at (x, y) with given width and height."""
    up()
    goto(x, y)
    down()
    begin_fill()
    for count in range(2):
        forward(width)
        left(90)
        forward(height)
        left(90)
    end_fill()
def draw():
    """Draw game and move pong ball."""
    clear()
    rectangle(-200, state[1], 10, 50)
    rectangle(190, state[2], 10, 50)
    ball.move(aim)
    x = ball.x
    y = ball.y
    up()
    goto(x, y)
    dot(10)
    update()
    if y < -200 or y > 200:
        aim.y = -aim.y
    if x < -185:
        low = state[1]
        high = state[1] + 50
        if low <= y <= high:
            aim.x = -aim.x
        else:
            return
    if x > 185:
        low = state[2]
        high = state[2] + 50
        if low <= y <= high:
            aim.x = -aim.x
        else:
            return
    ontimer(draw, 50)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
listen()
onkey(lambda: move(1, 20), 'w')
onkey(lambda: move(1, -20), 's')
onkey(lambda: move(2, 20), 'i')
onkey(lambda: move(2, -20), 'k')
draw()
done()


游戏演示:


image.png


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


8.上课划水必备-井字游戏(我敢说100%的人都玩过)


👉游戏规则:点击屏幕放置一个X或O。连续连接三个,就赢了!


from turtle import *
from freegames import line
def grid():
    """Draw tic-tac-toe grid."""
    line(-67, 200, -67, -200)
    line(67, 200, 67, -200)
    line(-200, -67, 200, -67)
    line(-200, 67, 200, 67)
def drawx(x, y):
    """Draw X player."""
    line(x, y, x + 133, y + 133)
    line(x, y + 133, x + 133, y)
def drawo(x, y):
    """Draw O player."""
    up()
    goto(x + 67, y + 5)
    down()
    circle(62)
def floor(value):
    """Round value down to grid with square size 133."""
    return ((value + 200) // 133) * 133 - 200
state = {'player': 0}
players = [drawx, drawo]
def tap(x, y):
    """Draw X or O in tapped square."""
    x = floor(x)
    y = floor(y)
    player = state['player']
    draw = players[player]
    draw(x, y)
    update()
    state['player'] = not player
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
update()
onscreenclick(tap)
done()


游戏演示:


image.png


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


9.将数字滑动到位的拼图游戏


👉 游戏规则:单击靠近空正方形的方格以交换位置。将所有数字从左到右按顺序排列。


from random import *
from turtle import *
from freegames import floor, vector
tiles = {}
neighbors = [
    vector(100, 0),
    vector(-100, 0),
    vector(0, 100),
    vector(0, -100),
]
def load():
    """Load tiles and scramble."""
    count = 1
    for y in range(-200, 200, 100):
        for x in range(-200, 200, 100):
            mark = vector(x, y)
            tiles[mark] = count
            count += 1
    tiles[mark] = None
    for count in range(1000):
        neighbor = choice(neighbors)
        spot = mark + neighbor
        if spot in tiles:
            number = tiles[spot]
            tiles[spot] = None
            tiles[mark] = number
            mark = spot
def square(mark, number):
    """Draw white square with black outline and number."""
    up()
    goto(mark.x, mark.y)
    down()
    color('black', 'white')
    begin_fill()
    for count in range(4):
        forward(99)
        left(90)
    end_fill()
    if number is None:
        return
    elif number < 10:
        forward(20)
    write(number, font=('Arial', 60, 'normal'))
def tap(x, y):
    """Swap tile and empty square."""
    x = floor(x, 100)
    y = floor(y, 100)
    mark = vector(x, y)
    for neighbor in neighbors:
        spot = mark + neighbor
        if spot in tiles and tiles[spot] is None:
            number = tiles[mark]
            tiles[spot] = number
            square(spot, number)
            tiles[mark] = None
            square(mark, None)
def draw():
    """Draw all tiles."""
    for mark in tiles:
        square(mark, tiles[mark])
    update()
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
load()
draw()
onscreenclick(tap)
done()


游戏演示:


image.png


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


10.迷宫


👉游戏规则:从一边移到另一边。轻触屏幕可跟踪从一侧到另一侧的路径。


from random import random
from turtle import *
from freegames import line
def draw():
    """Draw maze."""
    color('black')
    width(5)
    for x in range(-200, 200, 40):
        for y in range(-200, 200, 40):
            if random() > 0.5:
                line(x, y, x + 40, y + 40)
            else:
                line(x, y + 40, x + 40, y)
    update()
def tap(x, y):
    """Draw line and dot for screen tap."""
    if abs(x) > 198 or abs(y) > 198:
        up()
    else:
        down()
    width(2)
    color('red')
    goto(x, y)
    dot(4)
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
draw()
onscreenclick(tap)
done()


游戏演示:


image.png


https://ucc.alicdn.com/images/user-upload-01/e4a6c70be47240859343db571c21b5a0.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`库来控制鼠标和键盘进行各种操作,包括移动、点击、滚轮控制以及键盘的按键和快捷键输出,并介绍了如何结合图像处理和计算机视觉技术来扩展其应用。
下一篇
无影云桌面