六一用代码找回童心,花几分钟开发JAVA小游戏

个人介绍

光子郎.进行开发工作七年以上,目前涉及全栈领域并进行开发。会经常跟小伙伴分享前沿技术知识,java后台、web前端、移动端(Android,uniapp,小程序)相关的知识以及经验体会,不定期会有源码及框架的分享,如果你有相关的知识想要及时了解或者讨论,那么请关注光子郎.,点点文末小卡片,不定期会有免费的资源分享给大家,感谢支持~

人生格言

你要批评指点四周风景,首先你要爬上屋顶。

今天是六一,各位被选召的孩子们节日快乐。今天光子郎带大家用JAVA写几个简单的小游戏玩玩,用代码找回同心。废话少说,开整!

目录

猜数字游戏

贪吃蛇游戏

井字棋小游戏

石头、剪刀、布游戏


猜数字游戏

import java.util.Random;
import java.util.Scanner;

public class GuessNumberGame {

    public static void main(String[] args) {
        Random random = new Random();
        int targetNumber = random.nextInt(100) + 1;
        int guessCount = 0;

        System.out.println("欢迎来到猜数字游戏!");

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("请输入一个1到100之间的整数:");
            int guess = scanner.nextInt();
            guessCount++;

            if (guess == targetNumber) {
                System.out.println("恭喜你,猜对了!你总共猜了" + guessCount + "次。");
                break;
            } else if (guess < targetNumber) {
                System.out.println("猜的数字太小了,请再试一次。");
            } else {
                System.out.println("猜的数字太大了,请再试一次。");
            }
        }

        scanner.close();
    }
}

这个游戏的规则很简单,程序会随机生成一个1到100之间的整数,玩家需要通过输入数字来猜测这个数是多少。程序会根据玩家猜测的数字给出提示,直到玩家猜对为止。在游戏结束时,程序会告诉玩家猜测的次数。

贪吃蛇游戏

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SnakeGame extends JFrame implements ActionListener {
    private static final int SCALE = 10;
    private static final int WIDTH = 40;
    private static final int HEIGHT = 40;
    private static final int DELAY = 100;

    private Snake snake;
    private Timer timer;
    private boolean gameOver;

    public SnakeGame() {
        setTitle("贪吃蛇游戏");
        setSize(WIDTH * SCALE, HEIGHT * SCALE);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);

        snake = new Snake();
        timer = new Timer(DELAY, this);
        gameOver = false;

        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_UP && snake.getDirection() != Direction.DOWN)
                    snake.setDirection(Direction.UP);
                if (key == KeyEvent.VK_DOWN && snake.getDirection() != Direction.UP)
                    snake.setDirection(Direction.DOWN);
                if (key == KeyEvent.VK_LEFT && snake.getDirection() != Direction.RIGHT)
                    snake.setDirection(Direction.LEFT);
                if (key == KeyEvent.VK_RIGHT && snake.getDirection() != Direction.LEFT)
                    snake.setDirection(Direction.RIGHT);
            }
        });

        setVisible(true);
        startGame();
    }

    public void startGame() {
        timer.start();
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);

        if (!gameOver) {
            snake.move();
            snake.draw(g);
            if (snake.checkCollision()) {
                gameOver = true;
            }
        } else {
            gameOver(g);
        }
    }

    public void gameOver(Graphics g) {
        g.setColor(Color.RED);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString("Game Over", WIDTH * SCALE / 2 - 70, HEIGHT * SCALE / 2);
    }

    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    public static void main(String[] args) {
        new SnakeGame();
    }
}

import java.awt.*;
import java.util.*;

public class Snake {
    private ArrayList body;
    private Direction direction;
    private boolean grow;

    public Snake() {
        body = new ArrayList<>();
        body.add(new Point(20, 20));
        direction = Direction.RIGHT;
        grow = false;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public Direction getDirection() {
        return direction;
    }

    public void move() {
        Point head = body.get(0);
        Point newHead = new Point(head.x, head.y);
        switch (direction) {
            case UP:
                newHead.y--;
                break;
            case DOWN:
                newHead.y++;
                break;
            case LEFT:
                newHead.x--;
                break;
            case RIGHT:
                newHead.x++;
                break;
        }
        body.add(0, newHead);
        if (!grow) {
            body.remove(body.size() - 1);
        } else {
            grow = false;
        }
    }

    public void draw(Graphics g) {
        g.setColor(Color.GREEN);
        for (Point p : body) {
            g.fillRect(p.x * SnakeGame.SCALE, p.y * SnakeGame.SCALE, SnakeGame.SCALE, SnakeGame.SCALE);
        }
    }

    public boolean checkCollision() {
        Point head = body.get(0);
        for (int i = 1; i < body.size(); i++) {
            if (head.equals(body.get(i))) {
                return true;
            }
        }
        int x = head.x;
        int y = head.y;
        return x < 0 || x >= SnakeGame.WIDTH || y < 0 || y >= SnakeGame.HEIGHT;
    }
}

public enum Direction {
    UP, DOWN, LEFT, RIGHT
}

这个贪吃蛇游戏使用Java的图形界面库(Swing)来实现,玩家通过控制方向键来控制蛇的移动,目标是吃到食物并避免碰到自己的身体或边界。当蛇的头部与身体或边界发生碰撞时,游戏结束。(如果你有兴趣,还可以尝试增加一些功能,比如计分系统、难度级别等等)

井字棋小游戏

import java.util.Scanner;

public class TicTacToeGame {
    private char[][] board;
    private char currentPlayer;
    private boolean gameOver;

    public TicTacToeGame() {
        board = new char[3][3];
        currentPlayer = 'X';
        gameOver = false;
        initializeBoard();
    }

    public void playGame() {
        System.out.println("欢迎来到井字棋游戏!");

        while (!gameOver) {
            printBoard();
            int[] move = getPlayerMove();
            makeMove(move[0], move[1]);
            if (checkWin()) {
                printBoard();
                System.out.println("玩家 " + currentPlayer + " 赢了!");
                gameOver = true;
            } else if (checkDraw()) {
                printBoard();
                System.out.println("平局!");
                gameOver = true;
            } else {
                switchPlayer();
            }
        }
    }

    private void initializeBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                board[i][j] = '-';
            }
        }
    }

    private void printBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }

    private int[] getPlayerMove() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("玩家 " + currentPlayer + ",请输入您的下一步坐标(行 列):");
        int row = scanner.nextInt();
        int col = scanner.nextInt();
        return new int[]{row, col};
    }

    private void makeMove(int row, int col) {
        if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-') {
            board[row][col] = currentPlayer;
        } else {
            System.out.println("无效的移动!请重新输入。");
            int[] move = getPlayerMove();
            makeMove(move[0], move[1]);
        }
    }

    private boolean checkWin() {
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
                return true;
            }
            if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
                return true;
            }
        }
        if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) {
            return true;
        }
        if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
            return true;
        }
        return false;
    }

    private boolean checkDraw() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == '-') {
                    return false;
                }
            }
        }
        return true;
    }

    private void switchPlayer() {
        if (currentPlayer == 'X') {
            currentPlayer = 'O';
        } else {
            currentPlayer = 'X';
        }
    }

    public static void main(String[] args) {
        TicTacToeGame game = new TicTacToeGame();
        game.playGame();
    }
}

经典的井字棋游戏,两位玩家轮流下棋,首先连成一条线的玩家获胜,如果棋盘填满且没有玩家获胜,则为平局。

石头、剪刀、布游戏

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissorsGame {
    public static void main(String[] args) {
        String[] choices = { "石头", "剪刀", "布" };
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        System.out.println("欢迎来到石头、剪刀、布游戏!");

        while (true) {
            System.out.print("请输入你的选择(石头、剪刀、布)或输入 q 退出游戏:");
            String playerChoice = scanner.nextLine();

            if (playerChoice.equalsIgnoreCase("q")) {
                break;
            }

            int randomIndex = random.nextInt(choices.length);
            String computerChoice = choices[randomIndex];

            System.out.println("你的选择:" + playerChoice);
            System.out.println("电脑的选择:" + computerChoice);

            String result = determineWinner(playerChoice, computerChoice);
            System.out.println(result);
            System.out.println();
        }

        System.out.println("游戏结束。谢谢你的参与!");
    }

    public static String determineWinner(String playerChoice, String computerChoice) {
        if (playerChoice.equalsIgnoreCase(computerChoice)) {
            return "平局!";
        } else if (
                (playerChoice.equalsIgnoreCase("石头") && computerChoice.equalsIgnoreCase("剪刀")) ||
                (playerChoice.equalsIgnoreCase("剪刀") && computerChoice.equalsIgnoreCase("布")) ||
                (playerChoice.equalsIgnoreCase("布") && computerChoice.equalsIgnoreCase("石头"))
        ) {
            return "你赢了!";
        } else {
            return "电脑赢了!";
        }
    }
}

这个石头、剪刀、布游戏需要输入自己的选择(石头、剪刀、布),然后与电脑进行对战,决定胜负。游戏会根据规则判断出胜负,并展示结果。可以输入 "q" 退出游戏。

希望这几款小游戏能够让大家找回当初敲代码的初心,虽然是谋生手段但是也不妨碍我们乐在其中这个六一希望大家能够开心敲代码用代码找回童心~ 

这次的分享就到这里,不要忘记关注光子郎,也点点文末小卡片,一定会有你喜欢的资源分享以及干货整理,我们下期再见啦,拜拜~

你可能感兴趣的:(Java,java,开发语言,小游戏)