Java猜测游戏无限循环

时间:2017-02-12 22:21:53

标签: java

我的代码存在问题,程序无法重新播放,但是 也不会结束。

在获胜或过多猜测之后,代码继续在内部while循环中循环。

这是我的代码:

/**
 * This program will prompt the user to guess a secret number
 * This number will is between 1 and N, where N is a postive number
 *
 * @author: Perry Chapman
*/

import java.util.Scanner;

public class SecretNumber2
{
    public static void main( String [] args )
    {
        int N;
        int randomNumber;    
        int guess;
        int tries, maxTries;

        boolean win = false;
        boolean playing = true;
        int playAgain = 1;
        tries = 0;

        while(playing == true)
        { 
            Scanner input = new Scanner( System.in );

            System.out.println( "This is a guessing game." );
            System.out.println( "What is the max number of tries: ");
            maxTries = input.nextInt();
            System.out.println( "Enter a value between 1 and 1000: " );
            N = input.nextInt();

            randomNumber = (int)(N * Math.random()) + 1;

            while (win == false)
            {
                System.out.println( "Enter your guess: " );                      
                guess = input.nextInt();
                tries++;

                if (guess == randomNumber) 
                {  
                    System.out.println( "Congratulations! The number of guesses it took you was " + tries );
                    win = true;
                    System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
                    playAgain = input.nextInt();

                    if(playAgain == 1) {
                        playing = true;
                    }

                    else if (playAgain == 2) {
                        playing = false;
                    }
                    tries = 0;
                }

                else if(guess < randomNumber)
                    System.out.println( "Too low, guess again." );

                else if(guess > randomNumber)                        
                    System.out.println( "Too high, guess again." );

                else if(tries == maxTries)
                {
                    System.out.println("You have exceeded the max number of tries. \nYou lose.");
                    System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
                    playAgain = input.nextInt();

                    if(playAgain == 1) {
                      playing = true;
                    }

                    else if(playAgain == 2) {
                      playing = false;
                    }

                    tries = 0;
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

Andrew是对的,为了循环条件需要为true。如果else语句需要按正确的顺序排列。这是一个修复,我希望它会有所帮助。

public static void main(String[] args) {
    int N;
    int randomNumber;
    int guess;
    int tries, maxTries;

    boolean lose;
    boolean playing = true;
    int playAgain;
    tries = 0;

    while (playing) {
        Scanner input = new Scanner(System.in);

        System.out.println("This is a guessing game.");
        System.out.println("What is the max number of tries: ");
        maxTries = input.nextInt();
        System.out.println("Enter a value between 1 and 1000: ");
        N = input.nextInt();

        randomNumber = (int) (N * Math.random()) + 1;
        lose = true;

        while (lose) {
            System.out.println("Enter your guess: ");
            guess = input.nextInt();
            tries++;

            if (guess == randomNumber) {
                System.out.println("Congratulations! The number of guesses it took you was " + tries);
                lose = false;
                System.out.println("Would you like to play again? \n (1)Yes or (2)No: ");
                playAgain = input.nextInt();

                if (playAgain == 1) {
                    playing = true;
                } else if (playAgain == 2) {
                    playing = false;
                }
                tries = 0;
            } else if (tries == maxTries) {
                System.out.println("You have exceeded the max number of tries. \nYou lose.");
                System.out.println("\nWould you like to play again?\n (1)Yes or (2)No: ");
                playAgain = input.nextInt();

                if (playAgain == 1) {
                    playing = true;
                } else if (playAgain == 2) {
                    playing = false;
                }
                lose = false;
                tries = 0;
            } else if (guess < randomNumber) {
                System.out.println("Too low, guess again.");
            } else if (guess > randomNumber) {
                System.out.println("Too high, guess again.");
            }
        }
    }
}

答案 1 :(得分:0)

我认为你有两个问题。

首先是在成功猜出你从未设定的号码后,胜利回到假。所以你不会再次进入内部while循环。

第二个是if / else if语句的排序,从来没有一个猜测可以到达最终的if的情况。在前三个ifs之一中,每种情况都将验证为真。

答案 2 :(得分:0)

     import pygame
     import random
     from os import path

     img_dir = path.join(path.dirname(__file__), 'img')
     snd_dir = path.join(path.dirname(__file__), 'sound')


     WIDTH = 800
     HEIGHT = 600
     FPS = 50

     WHITE=(255, 255, 255)
     BLACK=(0, 0, 0)
     RED=(255, 0, 0)
     GREEN=(0, 255, 0)
     BLUE=(0, 0, 255)
     YELLOW=(255, 255, 0)

     pygame.init()
     pygame.mixer.init()

     screen = pygame.display.set_mode((WIDTH, HEIGHT))
     pygame.display.set_caption("My Game")
     clock = pygame.time.Clock()

     font_name = pygame.font.match_font('arial')

     end = True
     def start_screen():
         draw_text(screen, "SPACE SHOOTING", 70, WIDTH/2, HEIGHT/4)
         draw_text(screen, "INSTRUCTIONS", 25, WIDTH/2, HEIGHT/2)
         draw_text(screen, "Press Left arrow key to move left", 20, WIDTH/2, HEIGHT*2/3.5)
     draw_text(screen, "Press Right arrow key to move right", 20, WIDTH/2, HEIGHT*2/3.3)
draw_text(screen, "Spacebar to shoot", 20, WIDTH/2, HEIGHT*2/3.1)
draw_text(screen, "Press a key to begin", 20, WIDTH/2, HEIGHT*3/4)
pygame.display.flip()
wait = True
while wait:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                wait = False




     def draw_text(surf, text, size, x, y):
          font = pygame.font.Font(font_name, size)
          text_surface = font.render(text, True, WHITE)
          text_rect = text_surface.get_rect()
          text_rect.midtop = (x, y)
          surf.blit(text_surface, text_rect)



   class Player(pygame.sprite.Sprite):
       def __init__(self):
          pygame.sprite.Sprite.__init__(self)
          self.image = pygame.transform.scale(player_img, (50, 38))
          self.image.set_colorkey(BLACK)
          self.rect = self.image.get_rect()
          self.radius = 20
          self.rect.centerx = WIDTH/2
          self.rect.bottom = HEIGHT - 10
          self.speedx = 0

     def update(self):
         self.speedx = 0
         keystate = pygame.key.get_pressed()
          if keystate[pygame.K_LEFT]:
             self.speedx = -5
          if keystate[pygame.K_RIGHT]:
             self.speedx = 5
             self.rect.x += self.speedx
          if self.rect.right > WIDTH:
             self.rect.right = WIDTH
          if self.rect.left < 0:
             self.rect.left = 0

def shoot(self):
    bullet = Bullets(self.rect.centerx, self.rect.top)
    all_sprites.add(bullet)
    bullets.add(bullet)

class Aliens(pygame.sprite.Sprite):
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = aliens_img
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.radius = int(self.rect.width*.85/2)
    self.rect.x = random.randrange(WIDTH - self.rect.width)
    self.rect.y = random.randrange(-100, -40)
    self.speedy = random.randrange(1, 8)

def update(self):
    self.rect.y += self.speedy
    if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or       self.rect.right > WIDTH + 20:
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 8)

class SuperAliens(pygame.sprite.Sprite):
  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = superaliens_img
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.radius = int(self.rect.width*.85/2)
    self.rect.x = random.randrange(WIDTH - self.rect.width)
    self.rect.y = random.randrange(-100, -40)
    self.speedy = random.randrange(1, 8)
    self.speedx = random.randrange(-3, 3)

def update(self):
    self.rect.x += self.speedx
    self.rect.y += self.speedy
    if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 8)

def shoot1(self):
    sbullet = SBullets(self.rect.centerx, self.rect.bottom)
    all_sprites.add(sbullet)
    bullets.add(sbullet)



class SBullets(pygame.sprite.Sprite):
  def __init__(self, x, y):
    pygame.sprite.Sprite.__init__(self)
    self.image = sbullet_img
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.rect.bottom = y
    self.rect.centerx = x
    self.speedy = +10

def update(self):
    self.rect.y += self.speedy
    if self.rect.top < 0:
        self.kill()

class Bullets(pygame.sprite.Sprite):
  def __init__(self, x, y):
    pygame.sprite.Sprite.__init__(self)
    self.image = bullet_img
    self.image.set_colorkey(BLACK)
    self.rect = self.image.get_rect()
    self.rect.bottom = y
    self.rect.centerx = x
    self.speedy = -10

def update(self):
    self.rect.y += self.speedy
    if self.rect.bottom < 0:
        self.kill()

 class Explode(pygame.sprite.Sprite):
  def __init__(self, center, size):
    pygame.sprite.Sprite.__init__(self)
    self.size = size
    self.image = explode[self.size][0]
    self.rect = self.image.get_rect()
    self.rect.center = center
    self.frame = 0
    self.last_update = pygame.time.get_ticks()
    self.frame_rate = 2

def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_update > self.frame_rate:
        self.last_update = now
        self.frame += 1
        if self.frame == len(explode[self.size]):
            self.kill()
        else:
            center = self.rect.center
            self.image = explode[self.size][self.frame]
            self.rect = self.image.get_rect()
            self.rect.center = center





 background = pygame.image.load(path.join(img_dir, "back.png")).convert()
  background_rect = background.get_rect()
  player_img = pygame.image.load(path.join(img_dir, "playerShip2_blue.png")).convert()
  superaliens_img = pygame.image.load(path.join(img_dir, "enemyBlack4.png")).convert()
  aliens_img = pygame.image.load(path.join(img_dir, "enemyBlack1.png")).convert()
  bullet_img = pygame.image.load(path.join(img_dir, "laserRed16.png")).convert()
  sbullet_img = pygame.image.load(path.join(img_dir, "laserRed11.png")).convert()
  explode = {}
  explode['super']=[]
  explode['small']=[]
 for i in range(9):
   filename = 'regularExplosion02.png'.format(1)
    img = pygame.image.load(path.join(img_dir, filename)).convert()
img.set_colorkey(BLACK)
img_super = pygame.transform.scale(img, (75, 75))
explode ['super'].append(img_super)
img_small = pygame.transform.scale(img, (32, 32))
explode ['small'].append(img_small)


#pygame.mixer.music.load(path.join(snd_dir, 'Orbital.mp3'))
#pygame.mixer.music.set_volume(0.4)


#pygame.mixer.music.play(loops=-1)
end_game = True
running = True
while running:
 if end_game:
    start_screen()
    end_game = False
    all_sprites = pygame.sprite.Group()
    aliens = pygame.sprite.Group()
    superaliens = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    sbullets = pygame.sprite.Group()
    player = Player()
    all_sprites.add(player)
    for i in range(5):
        m = Aliens()
        all_sprites.add(m)
        aliens.add(m)

    for j in range(1):
        n = SuperAliens()
        all_sprites.add(n)
        superaliens.add(n)

    score = 0
clock.tick(FPS)
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            player.shoot()

all_sprites.update()

hits = pygame.sprite.groupcollide(aliens, bullets, True, True)
for hit in hits:
    score += 1
    m = Aliens()
    expl = Explode(hit.rect.center, 'small')
    all_sprites.add(expl)
    all_sprites.add(m)
    aliens.add(m)

hits = pygame.sprite.groupcollide(superaliens, bullets, True, True)
for hitt in hits:
    score += 5
    n = SuperAliens()
    expl1 = Explode(hitt.rect.center, 'super')
    all_sprites.add(expl1)
    all_sprites.add(n)
    superaliens.add(n)

hits = pygame.sprite.spritecollide(player, aliens, True)
for hit in hits:
    expl = Explode(hit.rect.center, 'small')
    all_sprites.add(expl)
    if hits:
        end_game = True
hits = pygame.sprite.spritecollide(player, superaliens, True)
for hitt in hits:
    expl1 = Explode(hitt.rect.center, 'super')
    all_sprites.add(expl1)
    if hits:
        end_game = True

screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen,"SCORE" +str(score), 22, WIDTH/2, 10)
#after drwing everything flip the display
pygame.display.flip()

pygame.quit()

发现了这个问题,我想我会发布答案,万一其他人可能会偶然发现这个帖子!谢谢你的帮助!