【发布时间】:2018-08-29 21:54:51
【问题描述】:
出于学习目的,我想在 c# 的空间入侵者上制作一个控制台克隆。我被困在如何制作成排的入侵者的问题上。例如,必须有 4 行有 6 个入侵者。我设法将一个入侵者作为一个结构列表,在其中放置 x 和 y 坐标以及角色。 我的问题是:我怎样才能用 6 个这种类型的入侵者制作 4 行,以便它们可以打印在控制台上,每个具有不同的坐标。 这是我的入侵者的一个例子:
using System;
using System.Collections.Generic;
using System.Threading;
namespace SpaceInvader
{
public struct Position
{
public int Row { get; set; }
public int Col { get; set; }
public char Symbol { get; set; }
public Position(int row, int col, char symbol)
{
this.Row = row;
this.Col = col;
this.Symbol = symbol;
}
}
class Program
{
static public int maxRows = 50;
static public int maxCols = 180;
public static List<Position> invader = new List<Position>();
public static List<List<Position>> invaders = new List<List<Position>>();
public static int moveX = 0;
public static int moveY =0;
static void Main()
{
ScreenSettings();
InitializeInvaders();
DrawInvaders();
while (true)
{
moveX++;
InitializeInvaders(moveY,moveX);
DrawInvaders();
Console.Clear();
Thread.Sleep(300);
}
}
private static void ScreenSettings()
{
Console.CursorVisible = false;
Console.BufferHeight = Console.WindowHeight = maxRows;
Console.BufferWidth = Console.WindowWidth = maxCols;
}
private static void DrawInvaders()
{
foreach (List<Position> invader in invaders)
{
DrawInvader(invader);
}
}
private static void InitializeInvaders(int moveY = 0, int moveX = 0)
{
for (int row = 0 ; row < 16; row += 4)
{
for (int col = 0 ; col < 99 ; col += 9)
{
InitializeInvader(row+moveY, col+moveX);
}
}
invaders.Add(invader);
}
private static void DrawInvader(List<Position> invader)
{
;
foreach (Position part in invader)
{
Console.SetCursorPosition(part.Col, part.Row);
Console.Write((char)part.Symbol);
}
}
public static List<Position> InitializeInvader(int row, int col)
{
int startrow = 5;//start position row
int startcol = 40;// start position col
invader.Add(new Position(startrow + row, startcol + col, '/'));
invader.Add(new Position(startrow + row, startcol + 1 + col, '{'));
invader.Add(new Position(startrow + row, startcol + 2 + col, 'O'));
invader.Add(new Position(startrow + row, startcol + 3 + col, '}'));
invader.Add(new Position(startrow + row, startcol + 4 + col, '\\'));
invader.Add(new Position(startrow + 1 + row, startcol + col, '\\'));
invader.Add(new Position(startrow + 1 + row, startcol + 1 + col, '~'));
invader.Add(new Position(startrow + 1 + row, startcol + 2 + col, '$'));
invader.Add(new Position(startrow + 1 + row, startcol + 3 + col, '~'));
invader.Add(new Position(startrow + 1 + row, startcol + 4 + col, '/'));
return invader;
}
}
【问题讨论】:
-
首先创建一个
Invader类,不要在每个位置硬编码每个字符。 -
非常感谢您的建议!好吧,我不是按课做的,但我做了一个职位列表。我不知道如何在课堂上做到这一点。现在我将它打印在屏幕上,并将外星人的行移到左边,但我找不到如何从控制台清理旧的。你有什么想法吗?