gpt4 book ai didi

java - Java 贪吃蛇游戏的类未编译

转载 作者:行者123 更新时间:2023-12-02 12:51:25 25 4
gpt4 key购买 nike

请找到我正在尝试创建的蛇游戏的一些源代码:

package Snake;

import java.awt.*;
import Snake.GameBoard.*;

public enum TileType {
SNAKE(Color.GREEN),
FRUIT(Color.RED),
EMPTY(null),

private Color tileColor;

private TileType(Color color) {
this.tileColor = color;
}

// @ return

public Color getColor() {
return tileColor;
}

private TileType[] tiles;

public void GameBoard() {
tiles = new TileType[MAP_SIZE * MAP_SIZE];
resetBoard();
}

// Reset all of the tiles to EMPTY.

public void resetBoard() {
for(int i = 0; i < tiles.length; i++) {
tiles[i] = TileType.EMPTY;
}
}

// @ param x The x coordinate of the tile.
// @ param y The y coordinate of the tile.
// @ return The type of tile.

public TileType getTile(int x, int y) {
return tiles[y * MAP_SIZE + x];
}

/**
* Draws the game board.
* @param g The graphics object to draw to.
*/
public void draw(Graphics2D g) {

//Set the color of the tile to the snake color.
g.setColor(TileType.SNAKE.getColor());

//Loop through all of the tiles.
for(int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {

//Calculate the x and y coordinates of the tile.
int x = i % MAP_SIZE;
int y = i / MAP_SIZE;

//If the tile is empty, so there is no need to render it.
if(tiles[i].equals(TileType.EMPTY)) {
continue;
}

//If the tile is fruit, we set the color to red before rendering it.
if(tiles[i].equals(TileType.FRUIT)) {
g.setColor(TileType.FRUIT.getColor());
g.fillOval(x * TILE_SIZE + 4, y * TILE_SIZE + 4, TILE_SIZE - 8, TILE_SIZE - 8);
g.setColor(TileType.SNAKE.getColor());
} else {
g.fillRect(x * TILE_SIZE + 1, y * TILE_SIZE + 1, TILE_SIZE - 2, TILE_SIZE - 2);
}
}
}
}

其中很多工作都很好。然而,当它显示“私有(private)颜色tileColor;”时,我收到“我收到“ token tileColor上的语法错误”,请删除 token ”,但是当我删除它时,它会在我的IDE上导致更多的红色(我是使用 Eclipse)。

此外,每当 MAP_SIZE 和 TILE_SIZE 出现时,它都会表示它们无法解析为变量,尽管它们存在于以下类中:

封装蛇;

public class GameBoard {
public static final int TILE_SIZE = 25;
public static final int MAP_SIZE = 20;
}

在同一个包内,因此编译器应该很容易找到。

最佳答案

这里需要一个分号:

SNAKE(Color.GREEN),
FRUIT(Color.RED),
EMPTY(null); <--

对于不仅仅包含常量定义的枚举,这是必需的。来自 docs

when there are fields and methods, the list of enum constants must end with a semicolon.

<小时/>

MAP_SIZETILE_SIZE 无法解析,因为它们存在于不同的类 GameBoard 中。这里有 2 个选项:

  • 使用限定名称,即 GameBoard.MAP_SIZEGameBoard.TILE_SIZE

  • 由于enum可以实现接口(interface):使GameBoard成为一个接口(interface)实现该接口(interface)。这些变量将成为成员变量。

关于java - Java 贪吃蛇游戏的类未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com