java用二维数组写的关灯小游戏

来源:互联网 发布:手机更换ip地址软件 编辑:程序博客网 时间:2024/06/08 11:14
import java.util.Scanner;public class CloseLight {public static void main(String[] args) {int[][] map = new int[5][5];Scanner sca = new Scanner(System.in);int row, col;int sum;boolean result = true;/*----------生成开的灯----------*/map[2][2] = 1;map[2][1] = 1;map[2][3] = 1;map[1][2] = 1;map[3][2] = 1;/*----------遍历-----------*/for (int i = 0; i < map.length; i++) {for (int j = 0; j < map[i].length; j++) {System.out.print(map[i][j] + " ");}System.out.println();}/*------循环-----*/do {/*----------输入并更改----------*/System.out.println("请输入行数1-5:");row = sca.nextInt()-1;if (row < 0 || row > 4) {System.out.println("输入行超出范围,请重新输入:");continue;}System.out.println("请输入列数1-5:");col = sca.nextInt()-1;if (col < 0 || col > 4) {System.out.println("输入列超出范围,请重新输入:");continue;}if (map[row][col] == 0) {map[row][col] = 1;} else {map[row][col] = 0;}/*------------更改上方-------------*/if (row != 0) {if (map[row - 1][col] == 0) {map[row - 1][col] = 1;} else {map[row - 1][col] = 0;}}/*---------更改下方-------------*/if (row != map.length-1) {if (map[row + 1][col] == 0) {map[row + 1 ][col] = 1;} else {map[row + 1][col] = 0;}}/*---------更改左方-------------*/if (col !=0) {if (map[row ][col-1] == 0) {map[row  ][col-1] = 1;} else {map[row ][col-1] = 0;}}/*---------更改右方-------------*/if (col != map.length-1) {if (map[row ][col+1] == 0) {map[row  ][col+1] = 1;} else {map[row][col+1] = 0;}}/*-----遍历输出---------*/sum = 0;for (int i = 0; i < map.length; i++) {for (int j = 0; j < map[i].length; j++) {System.out.print(map[i][j] + " ");sum += map[i][j];}System.out.println();}/*--------------判断--------------------*/if (sum == 0) {result = false;}} while (result);System.out.println("果然是天才!");}}


原创粉丝点击