以下是一个使用 Python 编写的迷宫游戏,利用 JavaScript 来辅助实现。

Python 代码:

import tkinter as tk

class MazeGame:
    def __init__(self, maze):
        self.maze = maze
        self.rows = len(maze)
        self.cols = len(maze[0])
        self.player_pos = (0, 0)  # 初始玩家位置
        self.goal_pos = (self.rows-1, self.cols-1)  # 目标位置
        
        self.window = tk.Tk()
        self.canvas = tk.Canvas(self.window, width=self.cols*50, height=self.rows*50)
        self.canvas.pack()
        
        self.draw_maze()
        self.draw_player()
        
        self.window.bind('<Up>', self.move_up)
        self.window.bind('<Down>', self.move_down)
        self.window.bind('<Left>', self.move_left)
        self.window.bind('<Right>', self.move_right)
        
    def draw_maze(self):
        for row in range(self.rows):
            for col in range(self.cols):
                x1 = col * 50
                y1 = row * 50
                x2 = x1 + 50
                y2 = y1 + 50
                
                if self.maze[row][col] == 1:  # 墙壁
                    self.canvas.create_rectangle(x1, y1, x2, y2, fill='black')
        
    def draw_player(self):
        x1 = self.player_pos[1] * 50
        y1 = self.player_pos[0] * 50
        x2 = x1 + 50
        y2 = y1 + 50
        
        self.canvas.create_oval(x1, y1, x2, y2, fill='red')
        
    def move_up(self, event):
        new_pos = (self.player_pos[0]-1, self.player_pos[1])
        if self.is_valid_move(new_pos):
            self.update_player_pos(new_pos)
        
    def move_down(self, event):
        new_pos = (self.player_pos[0]+1, self.player_pos[1])
        if self.is_valid_move(new_pos):
            self.update_player_pos(new_pos)
        
    def move_left(self, event):
        new_pos = (self.player_pos[0], self.player_pos[1]-1)
        if self.is_valid_move(new_pos):
            self.update_player_pos(new_pos)
        
    def move_right(self, event):
        new_pos = (self.player_pos[0], self.player_pos[1]+1)
        if self.is_valid_move(new_pos):
            self.update_player_pos(new_pos)
        
    def is_valid_move(self, pos):
        if pos[0] < 0 or pos[0] >= self.rows or pos[1] < 0 or pos[1] >= self.cols:
            return False
        if self.maze[pos[0]][pos[1]] == 1:  # 遇到墙壁
            return False
        return True
        
    def update_player_pos(self, new_pos):
        self.canvas.create_rectangle(self.player_pos[1]*50, self.player_pos[0]*50, (self.player_pos[1]+1)*50, (self.player_pos[0]+1)*50, fill='white')
        self.player_pos = new_pos
        self.draw_player()
        
        if self.player_pos == self.goal_pos:
            self.canvas.create_text(self.cols*25, self.rows*25, text='You Win!', fill='green', font=('Arial', 20), justify='center')
            self.window.unbind('<Up>')
            self.window.unbind('<Down>')
            self.window.unbind('<Left>')
            self.window.unbind('<Right>')
        
    def play(self):
        self.window.mainloop()

maze = [
    [0, 1, 0, 0, 0, 0],
    [0, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0],
    [1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0]
]

game = MazeGame(maze)
game.play()

JavaScript 代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Maze Game</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id='mazeCanvas' width='300' height='300'></canvas>
    <script>
        var maze = [
            [0, 1, 0, 0, 0, 0],
            [0, 1, 1, 1, 1, 0],
            [0, 0, 0, 0, 0, 0],
            [1, 1, 1, 1, 1, 0],
            [0, 0, 0, 0, 0, 0],
            [0, 1, 1, 1, 1, 0],
            [0, 0, 0, 0, 0, 0]
        ];
        
        var canvas = document.getElementById('mazeCanvas');
        var ctx = canvas.getContext('2d');
        
        var rows = maze.length;
        var cols = maze[0].length;
        var playerPos = { x: 0, y: 0 };  // 初始玩家位置
        var goalPos = { x: cols-1, y: rows-1 };  // 目标位置
        
        drawMaze();
        drawPlayer();
        
        document.addEventListener('keydown', function(event) {
            switch(event.key) {
                case 'ArrowUp':
                    moveUp();
                    break;
                case 'ArrowDown':
                    moveDown();
                    break;
                case 'ArrowLeft':
                    moveLeft();
                    break;
                case 'ArrowRight':
                    moveRight();
                    break;
            }
        });
        
        function drawMaze() {
            for (var row = 0; row < rows; row++) {
                for (var col = 0; col < cols; col++) {
                    var x = col * 50;
                    var y = row * 50;
                    var cellSize = 50;
                    
                    if (maze[row][col] === 1) {  // 墙壁
                        ctx.fillStyle = 'black';
                        ctx.fillRect(x, y, cellSize, cellSize);
                    }
                }
            }
        }
        
        function drawPlayer() {
            var x = playerPos.x * 50;
            var y = playerPos.y * 50;
            var cellSize = 50;
            
            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.arc(x+cellSize/2, y+cellSize/2, cellSize/2, 0, 2*Math.PI);
            ctx.fill();
        }
        
        function moveUp() {
            var newPos = { x: playerPos.x, y: playerPos.y-1 };
            if (isValidMove(newPos)) {
                updatePlayerPos(newPos);
            }
        }
        
        function moveDown() {
            var newPos = { x: playerPos.x, y: playerPos.y+1 };
            if (isValidMove(newPos)) {
                updatePlayerPos(newPos);
            }
        }
        
        function moveLeft() {
            var newPos = { x: playerPos.x-1, y: playerPos.y };
            if (isValidMove(newPos)) {
                updatePlayerPos(newPos);
            }
        }
        
        function moveRight() {
            var newPos = { x: playerPos.x+1, y: playerPos.y };
            if (isValidMove(newPos)) {
                updatePlayerPos(newPos);
            }
        }
        
        function isValidMove(pos) {
            if (pos.x < 0 || pos.x >= cols || pos.y < 0 || pos.y >= rows) {
                return false;
            }
            if (maze[pos.y][pos.x] === 1) {  // 遇到墙壁
                return false;
            }
            return true;
        }
        
        function updatePlayerPos(newPos) {
            ctx.clearRect(playerPos.x*50, playerPos.y*50, 50, 50);
            playerPos = newPos;
            drawPlayer();
            
            if (playerPos.x === goalPos.x && playerPos.y === goalPos.y) {
                ctx.font = '20px Arial';
                ctx.fillStyle = 'green';
                ctx.fillText('You Win!', (cols-1)*25, (rows-1)*25);
                document.removeEventListener('keydown', function(event) {});
            }
        }
    </script>
</body>
</html>

上述代码分别是使用 Python 和 JavaScript 编写的迷宫游戏。Python 使用 Tkinter 库创建一个图形化的迷宫游戏界面,通过键盘事件监听玩家的移动操作。JavaScript 使用 Canvas 绘制迷宫和玩家,通过键盘事件监听玩家的移动操作。两者的实现原理类似,只是使用了不同的界面库。

Python 迷宫游戏:使用 Tkinter 和 JavaScript 辅助实现

原文地址: https://www.cveoy.top/t/topic/p6I8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录