Java小程序游戏

问题描述:

我已经开始制作一个像applet游戏一样的java applet。这是我想要做的:Java小程序游戏

建立一个10x10板,随机挑选'船'所在的10个坐标。用户通过点击棋盘来猜测运送位置,将白色钉子放置为“未命中”,将红色钉子放置为“命中”。 只要用户点击最后一个'发送',程序就会写出一条包含所花费和退出次数的获奖消息。

我已经制作了10x10板,并将reg钉的随机位置存储在ArrayList中。现在,它允许输出隐藏红点的坐标,供我测试,并在它们被击中时放置它们。如果它没有击中,它可以让我放一个白点。我会如何计算它需要的命中次数,最后如果全部填满了或者找到了所有10艘船只,请输出游戏结束数量和命中数量?任何帮助表示感谢,并感谢你。这里是我的代码段:

Boolean isHit = false; 

while(unWon && totalClicks <= 100) { 
isHit = false; // reset isHit 
Coordinate currentClick = board.getClick(); // Get the current click 

//Check the ship coordinates to see whether it is hit 
for(Coordinate c: ships) { 
    if(c.getRow() == currentClick.getRow() && c.getCol() == currentClick.getCol()) { 
    board.putPeg("red", currentClick.getRow(), currentClick.getCol()); 
    isHit = true; 
    break;   
    } 
} 

// If it didn't hit, mark it with a white peg 
if (!isHit) { 
    board.putPeg("white", currentClick.getRow(), currentClick.getCol()); 
    } 
    } 
} 
} 
+1

请不要恶意破坏哟你的内容。一旦它被发布到网站上,它就被授权给该网站并且“属于社区”。 – TylerH

你在这段代码中有两个独立的环比ships因为某些原因:

for(Coordinate c: ships){ 

for (int i = 0; i < ships.size(); i++) { 

摆脱外一个。它没有做任何有用的事情,并且与之相关的if语句使得所有代码都在“内部”,如果currentClick不在ships中的位置上,则该循环会被跳过。

+0

那么在编辑之后,这段代码会是什么样子呢? if语句需要改变什么? –

好像你只需要清理的一点点,使事情变得更容易,以通过排序:

// This will be used to track whether any of the ship coordinates is a match for currentClick 
Boolean isHit = false; 

// It looks like you can combine these two conditions, but if that changes, just put `totalClicks <= 100` in its own `if` statement 
while(unWon && totalClicks <= 100) { 
    // reset isHit 
    isHit = false; 
    // Get the current click 
    Coordinate currentClick = board.getClick(); 
    // Check the ship coordinates to see whether we hit 
    for(Coordinate c: ships) { 
    if(c.getRow() == currentClick.getRow() && c.getCol() == currentClick.getCol()) { 
     board.putPeg("red", currentClick.getRow(), currentClick.getCol()); 
     isHit = true; 
     break;   
    } 
    } 
    // If we didn't hit, mark it with white 
    if (!isHit) { 
    board.putPeg("white", currentClick.getRow(), currentClick.getCol()); 
    } 
} 

为了提高清晰度,你可以把红色复到它自己的功能:

Boolean isHit(Coordinate currentClick, ArrayList<Coordinate> ships) { 
    for(Coordinate c: ships) { 
    if(c.getRow() == currentClick.getRow() && c.getCol() == currentClick.getCol()) { 
    return = true; 
    } 
    return false; 
} 

然后你就可以摆脱isHit布尔和重写你而:

while(unWon && totalClicks <= 100) { 
    Coordinate currentClick = board.getClick(); 
    if (isHit(currentClick, ships)) { 
    board.putPeg("red", currentClick.getRow(), currentClick.getCol()); 
    } else { 
    board.putPeg("white", currentClick.getRow(), currentClick.getCol()); 
    } 
} 
+0

第一部分的工作,但你的意思是提高清晰度。我不太明白你在第二和第三部分做了什么。感谢您的帮助,因为它现在允许我点击白点。 –

+0

第二部分将测试分为当前点击是否为自己的功能,它允许您简单地将while循环作为第三部分。 – adamdc78

+0

好吧。谢谢你的帮助! @ adamdc78 –