diff --git a/src/com/msb/DirEnum.java b/src/com/msb/DirEnum.java index a6131de..f9e8c23 100644 --- a/src/com/msb/DirEnum.java +++ b/src/com/msb/DirEnum.java @@ -7,5 +7,12 @@ package com.msb; * @Version: 1.0 */ public enum DirEnum { - LEFT, RIGHT, UP, DOWN + LEFT, RIGHT, UP, DOWN; + + public static DirEnum valueOf(int ordinal) { + if (ordinal < 0 || ordinal >= values().length) { + throw new IndexOutOfBoundsException("Invalid ordinal"); + } + return values()[ordinal]; + } } diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java index 242f6a0..269bffa 100644 --- a/src/com/msb/Tank.java +++ b/src/com/msb/Tank.java @@ -38,10 +38,6 @@ public class Tank { return; } - /* Color color = g.getColor(); - g.setColor(Color.YELLOW); - g.fillRect(x, y, 50, 50); - g.setColor(color);*/ switch (dir) { case UP: g.drawImage(ResourcesMgr.tankU, x, y, null); break; case DOWN: g.drawImage(ResourcesMgr.tankD, x, y, null); break; diff --git a/src/com/msb/TankDemo.java b/src/com/msb/TankDemo.java index 85f5672..4bbdb11 100644 --- a/src/com/msb/TankDemo.java +++ b/src/com/msb/TankDemo.java @@ -1,5 +1,7 @@ package com.msb; +import java.util.Random; + /** * @Author bingor * @Date 2022-09-29 11:02 @@ -10,10 +12,11 @@ public class TankDemo { public static void main(String[] args) throws InterruptedException { TankFrame tankFrame = new TankFrame(); + Random random = new Random(); //创建5个敌方坦克 for (int i=0; i<5; i++) { - tankFrame.tanks.add(new Tank(100 + i*80, 100, DirEnum.DOWN, GroupEnum.BAD, tankFrame)); + tankFrame.tanks.add(new Tank(100 + i*80, 100, DirEnum.valueOf(random.nextInt(3)), GroupEnum.BAD, tankFrame)); } //现实当中,虽然可以过按键来改变方块的坐标并且重新刷新画板来实现移动,但是敌方的坦克应该是自动在跑 diff --git a/src/com/msb/test/CommonTest.java b/src/com/msb/test/CommonTest.java index 3e1aa76..8906c23 100644 --- a/src/com/msb/test/CommonTest.java +++ b/src/com/msb/test/CommonTest.java @@ -1,5 +1,6 @@ package com.msb.test; +import com.msb.DirEnum; import org.junit.Assert; import org.junit.Test; @@ -7,6 +8,7 @@ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; +import java.util.Random; /** * @Author bingor @@ -24,4 +26,13 @@ public class CommonTest { Assert.assertNotNull(image); } + @Test + public void testEnum() { + Random random = new Random(); + System.out.println(DirEnum.valueOf(random.nextInt(3))); + System.out.println(DirEnum.valueOf(random.nextInt(3))); + System.out.println(DirEnum.valueOf(random.nextInt(3))); + System.out.println(DirEnum.valueOf(random.nextInt(3))); + } + }