前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java和python 编写贪吃蛇游戏

java和python 编写贪吃蛇游戏

原创
作者头像
疯狂的KK
修改2023-03-18 13:45:26
4860
修改2023-03-18 13:45:26
举报
文章被收录于专栏:Java项目实战

对于AI来说,编写贪吃蛇游戏需要调用的函数比较多,比如:初始化游戏界面、生成食物、蛇的移动、蛇的生长、判断游戏是否结束等等。

Java代码:

代码语言:java
复制
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class SnakeGame extends JFrame {
    private final int WIDTH = 300;
    private final int HEIGHT = 300;
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 29;
    private final int DELAY = 140;
    private int x[] = new int[ALL_DOTS];
    private int y[] = new int[ALL_DOTS];
    private int dots;
    private int apple_x;
    private int apple_y;
    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean upDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;
    private Timer timer;
    private Image ball;
    private Image apple;
    private Image head;

    public SnakeGame() {
        initGame();
        addKeyListener(new TAdapter());
        setBackground(Color.black);
        setFocusable(true);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        loadImages();
        timer = new Timer(DELAY, new GameCycle());
        timer.start();
    }

    private void initGame() {
        dots = 3;
        for (int i = 0; i < dots; i++) {
            x[i] = 50 - i * DOT_SIZE;
            y[i] = 50;
        }
        locateApple();
    }

    private void loadImages() {
        ImageIcon iid = new ImageIcon(getClass().getResource("dot.png"));
        ball = iid.getImage();
        ImageIcon iia = new ImageIcon(getClass().getResource("apple.png"));
        apple = iia.getImage();
        ImageIcon iih = new ImageIcon(getClass().getResource("head.png"));
        head = iih.getImage();
    }

    private void locateApple() {
        int r = (int) (Math.random() * RAND_POS);
        apple_x = r * DOT_SIZE;
        r = (int) (Math.random() * RAND_POS);
        apple_y = r * DOT_SIZE;
    }

    private void checkApple() {
        if ((x[0] == apple_x) && (y[0] == apple_y)) {
            dots++;
            locateApple();
        }
    }

    private void move() {
        for (int i = dots; i > 0; i--) {
            x[i] = x[(i - 1)];
            y[i] = y[(i - 1)];
        }
        if (leftDirection) {
            x[0] -= DOT_SIZE;
        }
        if (rightDirection) {
            x[0] += DOT_SIZE;
        }
        if (upDirection) {
            y[0] -= DOT_SIZE;
        }
        if (downDirection) {
            y[0] += DOT_SIZE;
        }
    }

    private void checkCollision() {
        for (int i = dots; i > 0; i--) {
            if ((i > 4) && (x[0] == x[i]) && (y[0] == y[i])) {
                inGame = false;
            }
        }
        if (y[0] >= HEIGHT) {
            inGame = false;
        }
        if (y[0] < 0) {
            inGame = false;
        }
        if (x[0] >= WIDTH) {
            inGame = false;
        }
        if (x[0] < 0) {
            inGame = false;
        }
        if (!inGame) {
            timer.stop();
        }
    }

    private class TAdapter extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }
            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }
            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }

    private class GameCycle implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (inGame) {
                checkApple();
                checkCollision();
                move();
            }
            repaint();
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        if (inGame) {
            g.drawImage(apple, apple_x, apple_y, this);
            for (int i = 0; i < dots; i++) {
                if (i == 0) {
                    g.drawImage(head, x[i], y[i], this);
                } else {
                    g.drawImage(ball, x[i], y[i], this);
                }
            }
            Toolkit.getDefaultToolkit().sync();
        } else {
            gameOver(g);
        }
    }

    private void gameOver(Graphics g) {
        String msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);
        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2);
    }

    public static void main(String[] args) {
        JFrame frame = new SnakeGame();
        frame.setTitle("Snake");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Python代码:

代码语言:python
代码运行次数:0
复制
import pygame
import random

pygame.init()

# 画布大小
width, height = 300, 300

# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# 设置蛇的初始位置
snake_pos = [[100, 50], [90, 50], [80, 50]]
snake_size = 10

# 设置食物的位置
food_pos = [random.randrange(1, width / 10) * 10, random.randrange(1, height / 10) * 10]

# 初始化方向
direction = "RIGHT"
change_to = direction

# 设置游戏速度
speed = 15

# 游戏结束标志
game_over = False


def draw_snake(snake_pos):
    for pos in snake_pos:
        pygame.draw.rect(screen, white, pygame.Rect(pos[0], pos[1], snake_size, snake_size))


def draw_food(food_pos):
    pygame.draw.rect(screen, red, pygame.Rect(food_pos[0], food_pos[1], snake_size, snake_size))


def move_snake(direction, snake_pos):
    if direction == "RIGHT":
        new_head = [snake_pos[0][0] + snake_size, snake_pos[0][1]]
    elif direction == "LEFT":
        new_head = [snake_pos[0][0] - snake_size, snake_pos[0][1]]
    elif direction == "UP":
        new_head = [snake_pos[0][0], snake_pos[0][1] - snake_size]
    elif direction == "DOWN":
        new_head = [snake_pos[0][0], snake_pos[0][1] + snake_size]
    snake_pos.insert(0, new_head)
    return snake_pos


def check_collision(snake_pos):
    if snake_pos[0][0] >= width or snake_pos[0][0] < 0:
        return True
    elif snake_pos[0][1] >= height or snake_pos[0][1] < 0:
        return True
    for pos in snake_pos[1:]:
        if pos == snake_pos[0]:
            return True
    return False


# 游戏主循环
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                change_to = "RIGHT"
            elif event.key == pygame.K_LEFT:
                change_to = "LEFT"
            elif event.key == pygame.K_UP:
                change_to = "UP"
            elif event.key == pygame.K_DOWN:
                change_to = "DOWN"

    if change_to == "RIGHT" and direction != "LEFT":
        direction = "RIGHT"
    elif change_to == "LEFT" and direction != "RIGHT":
        direction = "LEFT"
    elif change_to == "UP" and direction != "DOWN":
        direction = "UP"
    elif change_to == "DOWN" and direction != "UP":
        direction = "DOWN"

    snake_pos = move_snake(direction, snake_pos)

    if snake_pos[0] == food_pos:
        food_pos = [random.randrange(1, width / 10) * 10, random.randrange(1, height / 10) * 10]
    else:
        snake_pos.pop()

    screen.fill(black)
    draw_snake(snake_pos)
    draw_food(food_pos)

    if check_collision(snake_pos):
        game_over = True

    pygame.display.update()

    # 控制游戏速度
    pygame.time.Clock().tick(speed)

pygame.quit()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档