java和python 编写贪吃蛇游戏

举报
赵KK日常技术记录 发表于 2023/07/01 00:02:24 2023/07/01
【摘要】 对于AI来说,编写贪吃蛇游戏需要调用的函数比较多,比如:初始化游戏界面、生成食物、蛇的移动、蛇的生长、判断游戏是否结束等等。Java代码:import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;public class SnakeGame extends JFrame { pri...

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

请在此添加图片描述

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代码:

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()
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。