【通义灵码实践】实现经典手机游戏推箱子

简介: 本文介绍了使用通义灵码辅助实现经典推箱子游戏的过程。首先,通过输入“用Python写一个推箱子游戏”,灵码生成了基本的终端版本代码,包括地图渲染、玩家移动和胜利检测等功能。然而,终端版本交互体验不佳。为了解决这一问题,再次输入“不要在终端上运行,希望可以在页面上运行”,灵码生成了基于Flask的后端代码和HTML前端代码,实现了网页版推箱子游戏。最终结果展示了游戏的完整实现,包括前后端交互和用户界面。总结中提到,该方法具有快速生成代码、代码质量高、易于扩展等优点,但也存在功能简单、样式和用户体验有限、错误处理不足等问题,适合快速原型开发和教学演示。

1.背景

用python实现经典小游戏,自己写代码费时费力,用通义灵码辅助实现,快速又准确。

2.灵码实践

2.1 第一版

输入:用python写一个推箱子游戏

灵码回答

  1. 规则说明

image.png

  1. 代码
def print_map(game_map):
    for row in game_map:
        print(''.join(row))
    print()

def move_player(game_map, player_pos, direction):
    x, y = player_pos
    dx, dy = direction

    new_x, new_y = x + dx, y + dy

    if game_map[new_x][new_y] == '#':
        return False  # 碰到墙壁,不能移动

    if game_map[new_x][new_y] in ('.', 'G'):
        game_map[x][y], game_map[new_x][new_y] = game_map[new_x][new_y], game_map[x][y]
        return True

    if game_map[new_x][new_y] == 'B':
        box_new_x, box_new_y = new_x + dx, new_y + dy
        if game_map[box_new_x][box_new_y] in ('.', 'G'):
            game_map[box_new_x][box_new_y] = 'B'
            game_map[new_x][new_y] = game_map[x][y]
            game_map[x][y] = '.'
            return True

    return False

def check_win(game_map):
    for row in game_map:
        if 'B' in row:
            return False
    return True

def main():
    game_map = [
        ['#', '#', '#', '#', '#', '#', '#'],
        ['#', '.', '.', '.', '.', '.', '#'],
        ['#', '.', 'B', '.', '.', '.', '#'],
        ['#', '.', '.', '.', 'G', '.', '#'],
        ['#', '.', '.', '.', '.', '.', '#'],
        ['#', '.', '.', '.', '.', 'P', '#'],
        ['#', '#', '#', '#', '#', '#', '#']
    ]

    player_pos = (5, 5)
    directions = {
        'w': (-1, 0),  # 上
        's': (1, 0),   # 下
        'a': (0, -1),  # 左
        'd': (0, 1)    # 右
    }

    while True:
        print_map(game_map)
        if check_win(game_map):
            print("恭喜你,通关了!")
            break

        move = input("请输入方向 (w/s/a/d): ").strip().lower()
        if move not in directions:
            print("无效的输入,请输入 w/s/a/d")
            continue

        if move_player(game_map, player_pos, directions[move]):
            for i, row in enumerate(game_map):
                if 'P' in row:
                    player_pos = (i, row.index('P'))
                    break

if __name__ == "__main__":
    main()
  1. 代码说明

image.png

  1. 最终结果

image.png

  1. 问题

只能在终端里实现,交互体验不好。

2.2 第二版

输入:不要在终端上运行,希望可以在页面上运行

灵码回答

  1. 实现说明

image.png

  1. 代码

后端代码

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# 初始游戏地图
game_map = [
    ['#', '#', '#', '#', '#', '#', '#'],
    ['#', '.', '.', '.', '.', '.', '#'],
    ['#', '.', 'B', '.', '.', '.', '#'],
    ['#', '.', '.', '.', 'G', '.', '#'],
    ['#', '.', '.', '.', '.', '.', '#'],
    ['#', '.', '.', '.', '.', 'P', '#'],
    ['#', '#', '#', '#', '#', '#', '#']
]

player_pos = (5, 5)
directions = {
    'w': (-1, 0),  # 上
    's': (1, 0),   # 下
    'a': (0, -1),  # 左
    'd': (0, 1)    # 右
}

def move_player(map_data, player_pos, direction):
    x, y = player_pos
    dx, dy = direction

    new_x, new_y = x + dx, y + dy

    if map_data[new_x][new_y] == '#':
        return False  # 碰到墙壁,不能移动

    if map_data[new_x][new_y] in ('.', 'G'):
        map_data[x][y], map_data[new_x][new_y] = map_data[new_x][new_y], map_data[x][y]
        return True

    if map_data[new_x][new_y] == 'B':
        box_new_x, box_new_y = new_x + dx, new_y + dy
        if map_data[box_new_x][box_new_y] in ('.', 'G'):
            map_data[box_new_x][box_new_y] = 'B'
            map_data[new_x][new_y] = map_data[x][y]
            map_data[x][y] = '.'
            return True

    return False

def check_win(map_data):
    for row in map_data:
        if 'B' in row:
            return False
    return True

@app.route('/')
def index():
    return render_template('index.html', game_map=game_map)

@app.route('/move', methods=['POST'])
def move():
    global player_pos
    direction = request.form.get('direction')
    if direction in directions:
        if move_player(game_map, player_pos, directions[direction]):
            for i, row in enumerate(game_map):
                if 'P' in row:
                    player_pos = (i, row.index('P'))
                    break
            if check_win(game_map):
                return jsonify({'status': 'win'})
    return jsonify({'status': 'ok', 'game_map': game_map})

if __name__ == '__main__':
    app.run(debug=True)

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>推箱子游戏</title>
    <style>
        .map {
            display: grid;
            grid-template-columns: repeat(7, 50px);
            grid-gap: 2px;
        }
        .cell {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        .wall { background-color: black; color: white; }
        .empty { background-color: lightgray; }
        .goal { background-color: yellow; }
        .box { background-color: brown; color: white; }
        .player { background-color: blue; color: white; }
        .box-goal { background-color: green; color: white; }
    </style>
</head>
<body>
    <div id="game-map" class="map"></div>
    <div>
        <button onclick="move('w')"></button>
        <button onclick="move('a')"></button>
        <button onclick="move('s')"></button>
        <button onclick="move('d')"></button>
    </div>
    <script>
        function updateMap(mapData) {
            const mapContainer = document.getElementById('game-map');
            mapContainer.innerHTML = '';
            mapData.forEach(row => {
                row.forEach(cell => {
                    const cellElement = document.createElement('div');
                    cellElement.classList.add('cell');
                    if (cell === '#') cellElement.classList.add('wall');
                    else if (cell === '.') cellElement.classList.add('empty');
                    else if (cell === 'G') cellElement.classList.add('goal');
                    else if (cell === 'B') cellElement.classList.add('box');
                    else if (cell === 'P') cellElement.classList.add('player');
                    else if (cell === 'BG') cellElement.classList.add('box-goal');
                    cellElement.textContent = cell;
                    mapContainer.appendChild(cellElement);
                });
            });
        }

        function move(direction) {
            fetch('/move', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `direction=${direction}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'win') {
                    alert('恭喜你,通关了!');
                } else {
                    updateMap(data.game_map);
                }
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            updateMap({{ game_map | tojson }});
        });
    </script>
</body>
</html>
  1. 代码说明

image.png

  1. 最终结果

image.png

3.总结

3.1 优点

  1. 快速生成代码
  • 通义灵码能够快速生成基本的推箱子游戏代码,节省了从零开始编写的时间。
  • 提供了完整的前后端代码,包括Flask后端和HTML前端,使得开发者可以快速搭建一个可运行的Web应用。
  1. 代码质量较高
  • 生成的代码结构清晰,逻辑明确,符合Python和Flask的最佳实践。
  • 前端代码使用了现代的HTML和JavaScript,布局合理,样式简洁。
  1. 易于扩展
  • 生成的代码模块化程度较高,便于后续的扩展和维护。
  • 可以轻松添加更多的游戏关卡、更复杂的逻辑或改进用户界面。
  1. 文档和注释
  • 生成的代码包含了详细的注释,帮助开发者理解每一部分的功能。
  • 提供了详细的说明文档,指导开发者如何运行和调试代码。
  1. 交互性强
  • 通过AJAX请求实现了前后端的交互,使得游戏体验更加流畅。
  • 用户可以通过简单的按钮操作控制游戏角色,操作简单直观。

3.2 缺点

  1. 功能相对简单
  • 生成的推箱子游戏功能较为基础,没有复杂的游戏机制和高级特性。
  • 缺乏一些常见的游戏元素,如计分系统、时间限制、多关卡等。
  1. 样式和用户体验
  • 生成的前端样式较为简单,可能不够吸引人。
  • 用户界面的交互效果有限,缺乏动画和音效等增强用户体验的元素。
  1. 错误处理
  • 生成的代码在错误处理方面较为简单,可能需要开发者进一步完善。
  • 例如,网络请求失败时的处理、输入验证等。
  1. 性能优化
  • 生成的代码在性能优化方面做得不够,特别是在处理大规模数据或高并发请求时。
  • 需要开发者根据实际需求进行性能调优。
  1. 安全性
  • 生成的代码在安全性方面考虑较少,可能存在一些安全漏洞。
  • 例如,CSRF攻击、XSS攻击等,需要开发者进行安全加固。


通义灵码生成的推箱子游戏代码具有快速生成、代码质量高、易于扩展等优点,适合快速原型开发和教学演示。然而,对于需要更高复杂度、更好用户体验和更高安全性的商业项目,还需要开发者进行进一步的开发和优化。

目录
相关文章
|
5月前
|
存储 机器学习/深度学习 人工智能
大模型微调技术:LoRA原理与实践
本文深入解析大语言模型微调中的关键技术——低秩自适应(LoRA)。通过分析全参数微调的计算瓶颈,详细阐述LoRA的数学原理、实现机制和优势特点。文章包含完整的PyTorch实现代码、性能对比实验以及实际应用场景,为开发者提供高效微调大模型的实践指南。
2752 2
|
5月前
|
存储 人工智能 NoSQL
AI大模型应用实践 八:如何通过RAG数据库实现大模型的私有化定制与优化
RAG技术通过融合外部知识库与大模型,实现知识动态更新与私有化定制,解决大模型知识固化、幻觉及数据安全难题。本文详解RAG原理、数据库选型(向量库、图库、知识图谱、混合架构)及应用场景,助力企业高效构建安全、可解释的智能系统。
|
6月前
|
人工智能 自然语言处理 搜索推荐
携多项成果亮相云栖大会,探索大模型在云通信中的创新应用与全球实践
2025云栖大会云通信分论坛聚焦大模型与云通信融合,阿里云发布智能联络中心2.0与Chat App AI助理,携手伙伴推动通信智能化升级。
583 1
|
6月前
|
机器学习/深度学习 数据采集 人工智能
通义实验室Mobile-Agent-v3开源,全平台SOTA的GUI智能体,支持手机电脑等多平台交互
近日,通义实验室MobileAgent团队正式开源全新图形界面交互基础模型 GUI-Owl,并同步推出支持多智能体协同的自动化框架 Mobile-Agent-v3。该模型基于Qwen2.5-VL打造,在手机端与电脑端共8个GUI任务榜单中全面刷新开源模型性能纪录,达成全平台SOTA。
2095 2
|
5月前
|
机器学习/深度学习 缓存 自然语言处理
【万字长文】大模型训练推理和性能优化算法总结和实践
我们是阿里云公共云 AI 汽车行业大模型技术团队,致力于通过专业的全栈 AI 技术推动 AI 的落地应用。
2483 39
【万字长文】大模型训练推理和性能优化算法总结和实践
|
7月前
|
人工智能 安全 Serverless
进阶版|企业级 AI Agent 的构建实践
我们将构建 AI 应用扩展到了运行时和可观测,并尝试将 Agent、LLM、MCP 服务这几者之间如何有机协作尽量清晰化,未来还会扩展到Memory、LiteMQ 等更完整的技术栈,旨在帮助大家厘清完整的企业级 AI 应用构建的最佳实践。
2252 134
|
5月前
|
人工智能 安全 开发工具
C3仓库AI代码门禁通用实践:基于Qwen3-Coder+RAG的代码评审
本文介绍基于Qwen3-Coder、RAG与Iflow在C3级代码仓库落地LLM代码评审的实践,实现AI辅助人工评审。通过CI流水线自动触发,结合私域知识库与生产代码同仓管理,已成功拦截数十次高危缺陷,显著提升评审效率与质量,具备向各类代码门禁平台复用推广的价值。(239字)
1104 24
|
5月前
|
监控 安全 数据安全/隐私保护
55_大模型部署:从云端到边缘的全场景实践
随着大型语言模型(LLM)技术的飞速发展,从实验室走向产业化应用已成为必然趋势。2025年,大模型部署不再局限于传统的云端集中式架构,而是向云端-边缘协同的分布式部署模式演进。这种转变不仅解决了纯云端部署在延迟、隐私和成本方面的痛点,还为大模型在各行业的广泛应用开辟了新的可能性。本文将深入剖析大模型部署的核心技术、架构设计、工程实践及最新进展,为企业和开发者提供从云端到边缘的全场景部署指南。