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

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("果然是天才!");

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值