Pacman game - how to fix - c#

I am creating really simple pacman game as a homework. I am working in Visual Studio, in c#. The problem is, when I click run, only the winform shows with nothing on it. Can someone tell me what have I done wrong?
namespace pacman
{
public partial class Form1 : Form
{
Timer timer;
Pacman pacman;
static readonly int TIMER_INTERVAL = 250;
static readonly int WORLD_WIDTH = 15;
static readonly int WORLD_HEIGHT = 10;
Image foodImage;
bool[][] foodWorld;
public Form1()
{
InitializeComponent();
foodImage = Properties.Resources.orange_detoure;
DoubleBuffered = true;
newGame();
}
public void newGame()
{
pacman = new Pacman();
this.Width = Pacman.radius * 2 * (WORLD_WIDTH + 1);
this.Height = Pacman.radius * 2 * (WORLD_HEIGHT + 1);
foodWorld = new bool[WORLD_WIDTH][];
timer = new Timer();
timer.Interval = TIMER_INTERVAL;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
timer.Interval = TIMER_INTERVAL - 1;
if (TIMER_INTERVAL == 0)
{
timer.Stop();
}
pacman.Move(WORLD_WIDTH, WORLD_HEIGHT);
Invalidate();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (Keys.Up != 0)
{
pacman.ChangeDirection("UP");
}
if (Keys.Down != 0)
{
pacman.ChangeDirection("DOWN");
}
if (Keys.Left != 0)
{
pacman.ChangeDirection("LEFT");
}
if (Keys.Right != 0)
{
pacman.ChangeDirection("RIGHT");
}
Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.White);
for (int i = 0; i < foodWorld.Length; i++)
{
for (int j = 0; j < foodWorld[i].Length; j++)
{
if (foodWorld[i][j])
{
g.DrawImageUnscaled(foodImage, j * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Height) / 2, i * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Width) / 2);
}
}
}
pacman.Draw(g);
}
}
}
And here is the class Pacman:
namespace pacman
{
public class Pacman
{
public enum dir {UP, DOWN, RIGHT, LEFT};
public float x { get; set; }
public float y { get; set; }
public string direction { get; set; }
static public int radius = 20;
public double speed { get; set; }
public bool open { get; set; }
public Brush brush = new SolidBrush(Color.Yellow);
public Pacman() {
this.x = 7;
this.y = 5;
this.speed = 20;
this.direction = Convert.ToString(dir.RIGHT);
this.open = false;
}
public void ChangeDirection(string direct)
{
// vasiot kod ovde
for (int i = 0; i < 3; i++) {
if(direct == Convert.ToString(dir.RIGHT))
{
direction = "RIGHT";
}
if (direct == Convert.ToString(dir.LEFT))
{
direction = "LEFT";
}
if (direct == Convert.ToString(dir.UP))
{
direction = "UP";
}
if (direct == Convert.ToString(dir.DOWN))
{
direction = "DOWN";
}
}
}
public void Move(float width, float height)
{
if (direction == Convert.ToString(dir.RIGHT))
{
x = x + 1;
if (x > width) {
x = 1;
}
}
else if (direction == Convert.ToString(dir.LEFT))
{
x = x - 1;
if (x < 0) {
x = 14;
}
}
else if (direction == Convert.ToString(dir.UP))
{
y = y + 1;
if (y > height) {
y = 1;
}
}
else if (direction == Convert.ToString(dir.DOWN))
{
y = y - 1;
if (y < 0) {
y = 14;
}
}
}
public void Draw(Graphics g)
{
if (!open) {
g.FillEllipse(brush, 7, 5, 15, 15);
}
}
}
}
It should look like this http://prntscr.com/70e0jt.
I will be grateful if someone can tell me what should I fix so it finally works..

Add this to your constructor:
this.Paint += Form1_Paint;
What is happening is that you made a Paint handler, but never assigned the paint event to handle it (that I can see, its possible that the event was assigned in the other partial part of the class).
The other problem is that you did not fully define the "food world" variable, you initialized the first rank, but not the second. You need to fully initialize this and set the booleans inside of it.

Related

Reverse timer to increase life

I created a reverse timer for the system of lives. i.e., life should be added after 00:00 if the field is empty. I need the timer to work before all the hearts are full, i.e. when one heart is full, the timer turns on again, if all the hearts are in place, then it's just 00:00. I did this:
public int lives;
public int maxLives;
public Image[] Live;
public Sprite FullHearts;
public Sprite EmptyHearts;
//Timer
[SerializeField] private int minutes;
[SerializeField] private int seconds;
private int m, s;
[SerializeField]
private Text timerText;
private void updateTimer()
{
s--;
if (s < 0)
{
if (m == 0)
{
stopTimer();
return;
}
else {
m --;
s= 59;
}
}
writeTimer(m, s);
Invoke("updateTimer", 1f);
}
public void writeTimer(int m, int s) {
if (s < 10)
{
timerText.text = m.ToString() + ":0" + s.ToString();
}
else
{
timerText.text = m.ToString() + ":" + s.ToString();
}
}
public void stopTimer()
{
CancelInvoke();
}
public void StartTimer()
{
m = minutes;
s= seconds;
writeTimer(m, s);
Invoke("updateTimer", 1f);
}
public void setLives()
{
if (lives < maxLives)
{
StartTimer();
lives++;
Debug.Log("Life: " + lives);
}
if (lives > maxLives)
{
lives = maxLives;
}
for (int i = 0; i < Live.Length; i++)
{
if (i < Mathf.RoundToInt(lives))
{
Live[i].sprite = FullHearts;
}
else
{
Live[i].sprite = EmptyHearts;
}
if(i< maxLives)
{
Live[i].enabled = true;
}
else
{
Live[i].enabled = false;
}
}
}
public void TakeHit(int damage)
{
lives -= damage;
if (lives < 1)
{
lives = 0;
}
for (int i = 0; i < Live.Length; i++)
{
if (i < Mathf.RoundToInt(lives))
{
Live[i].sprite = FullHearts;
}
else
{
Live[i].sprite = EmptyHearts;
}
}
}
but for some reason it does not start, please tell me what the error is possible?

how can i have the high score in 1st in Tetris?

I got some problem with my Tetris game on highscore, here's the game script
/// The width of the Grid...
public static int gridWidth = 10;
/// The weight of the Grid...
public static int gridWeight = 20;
/// The grid...
public static Transform[,] grid = new Transform[gridWidth, gridWeight];
public static bool startingAtLevelZero;
public static int startingLevel;
public int scoreOneLine = 50;
public int scoreTwoLine = 100;
public int scoreThreeLine = 400;
public int scoreFourLine = 1500;
public int currentLevel = 0;
private int numLinesCleared = 0;
public static float fallSpeed = 1.0f;
public AudioClip clearedLineSound;
public Text hud_score;
public Text hud_level;
public Text hud_lines;
private int numberOfRowsThisTurn = 0;
private AudioSource audioSource;
public static int currentScore = 0;
private GameObject previewTetromino;
private GameObject nextTetromino;
private bool gameStarted = false;
private int startingHighScore;
private int startingHighScore2;
private int startingHighScore3;
private Vector2 previewTetrominoPosition = new Vector2(-6.5f, 16);
// Start is called before the first frame update
void Start()
{
currentScore = 0;
hud_score.text = "0";
currentLevel = startingLevel;
hud_level.text = currentLevel.ToString();
hud_lines.text = "0";
SpawnNextTetromino();
audioSource = GetComponent<AudioSource>();
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
}
void Update()
{
UpdateScore();
UpdateUI();
UpdateLevel();
UpdateSpeed();
}
void UpdateLevel()
{
if ((startingAtLevelZero == true) || (startingAtLevelZero == false && numLinesCleared / 10 > startingLevel))
currentLevel = numLinesCleared / 10;
Debug.Log("current Level : " + currentLevel);
}
void UpdateSpeed()
{
fallSpeed = 1.0f - ((float)currentLevel * 0.1f);
Debug.Log("current Fall Speed : " + fallSpeed);
}
public void UpdateUI()
{
hud_score.text = currentScore.ToString();
hud_level.text = currentLevel.ToString();
hud_lines.text = numLinesCleared.ToString();
}
public void UpdateScore()
{
if (numberOfRowsThisTurn > 0)
{
if (numberOfRowsThisTurn == 1)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 2)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 3)
{
ClearedThreeLine();
}
else if (numberOfRowsThisTurn == 4)
{
ClearedFourLine();
}
numberOfRowsThisTurn = 0;
PlayLineClearedSound();
}
}
public void ClearedOneLine()
{
currentScore += scoreOneLine + (currentLevel * 20);
numLinesCleared++;
}
public void ClearedTwoLine()
{
currentScore += scoreTwoLine + (currentLevel * 25);
numLinesCleared += 2;
}
public void ClearedThreeLine()
{
currentScore += scoreThreeLine + (currentLevel * 30);
numLinesCleared += 3;
}
public void ClearedFourLine()
{
currentScore += scoreFourLine + (currentLevel * 40);
numLinesCleared += 4;
}
public void PlayLineClearedSound()
{
audioSource.PlayOneShot(clearedLineSound);
}
public void UpdateHighScore()
{
if (currentScore > startingHighScore)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highScore2", startingHighScore);
PlayerPrefs.SetInt("highscore", currentScore);
}
else if (currentScore > startingHighScore2)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highscore2", currentScore);
}
else if (currentScore > startingHighScore3)
{
PlayerPrefs.SetInt("highscore3", currentScore);
}
}
public bool CheckIsAboveGrid(Tetromino tetromino)
{
for (int x = 0; x < gridWidth; ++x)
{
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y > gridWeight - 1)
{
return true;
}
}
}
return false;
}
public bool IsFullRowAt (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid [x, y] == null)
{
return false;
}
}
numberOfRowsThisTurn++;
return true;
}
public void DeleteMinoAt(int y)
{
for (int x = 0; x < gridWidth; ++x)
{
Destroy(grid[x, y].gameObject);
grid[x, y] = null;
}
}
public void MoveRowDown (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
grid[x,y -1] = grid[x, y];
grid[x, y] = null;
grid[x, y -1].position += new Vector3(0, -1, 0);
}
}
}
public void MoveAllRowsDown (int y)
{
for (int i = y; i < gridWeight; ++i)
{
MoveRowDown(i);
}
}
public void DeleteRow()
{
for (int y = 0; y < gridWeight; ++y)
{
if (IsFullRowAt(y))
{
DeleteMinoAt(y);
MoveAllRowsDown(y + 1);
--y;
}
}
}
public void UpdateGrid (Tetromino tetromino)
{
for (int y = 0; y < gridWeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
if (grid[x,y].parent == tetromino.transform)
{
grid[x, y] = null;
}
}
}
}
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y < gridWeight)
{
grid[(int)pos.x, (int)pos.y] = mino;
}
}
}
public Transform GetTransformAtGridPosition (Vector2 pos)
{
if (pos.y > gridWeight -1)
{
return null;
}
else
{
return grid[(int)pos.x, (int)pos.y];
}
}
public void SpawnNextTetromino()
{
if (!gameStarted)
{
gameStarted = true;
nextTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), new Vector2(5.0f, 20.0f), Quaternion.identity);
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
else
{
previewTetromino.transform.localPosition = new Vector2(5.0f, 20.0f);
nextTetromino = previewTetromino;
nextTetromino.GetComponent<Tetromino>().enabled = true;
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
}
public bool CheckIsInsideGrid (Vector2 pos)
{
return ((int)pos.x >= 0 && (int)pos.x < gridWidth && (int)pos.y >= 0);
}
public Vector2 Round (Vector2 pos)
{
return new Vector2(Mathf.Round(pos.x), Mathf.Round(pos.y));
}
string GetRandomTetromino()
{
int randomTetromino = Random.Range(1, 8);
string randomTetrominoName = "Prefabs/Tetromino_T";
switch (randomTetromino)
{
case 1:
randomTetrominoName = "Prefabs/Tetromino_T";
break;
case 2:
randomTetrominoName = "Prefabs/Tetromino_Long";
break;
case 3:
randomTetrominoName = "Prefabs/Tetromino_Square";
break;
case 4:
randomTetrominoName = "Prefabs/Tetromino_J";
break;
case 5:
randomTetrominoName = "Prefabs/Tetromino_L";
break;
case 6:
randomTetrominoName = "Prefabs/Tetromino_S";
break;
case 7:
randomTetrominoName = "Prefabs/Tetromino_Z";
break;
}
return randomTetrominoName;
}
public void GameOver()
{
UpdateHighScore();
Application.LoadLevel("GameOver");
}
and here's the game menu script
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
highScoreText2.text = PlayerPrefs.GetInt("highscore2").ToString();
highScoreText3.text = PlayerPrefs.GetInt("highScore3").ToString();
}
public void PlayGame()
{
if (Game.startingLevel == 0)
Game.startingAtLevelZero = true;
else
Game.startingAtLevelZero = false;
Application.LoadLevel("tetris");
}
public void ChangedValue (float value)
{
Game.startingLevel = (int)value;
levelText.text = value.ToString();
}
public void LaunchGameMenu()
{
Application.LoadLevel("tetris menu");
}
When I got 1120 score in the Tetris game, it shows up in 2nd score instead of 3rd or 1st ,when I got 720 score, it doesn't show up in 3rd score, when I score 1300 It shows up in 2nd and 1120 in 3rd, but not in 1st, can somehow help me what is wrong?
It appears you have various typographical errors while typing the keys when accessing the player's PlayerPrefs. PlayerPrefs is case-sensitive.
↓↓↓
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
...
↓↓↓
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
Consider the use of the nameof() command. The nameof() command allows you to treat a variable in-code as a string. This is SUPER helpful if you ever re-name the variable for example, the string will be renamed along with it. It also has the added bonus of giving you compilation errors if they are misspelled.
Example:
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt(nameof(highScoreText)).ToString();
highScoreText2.text = PlayerPrefs.GetInt(nameof(highScoreText2)).ToString();
highScoreText3.text = PlayerPrefs.GetInt(nameof(highScoreText3)).ToString();
}

I need to create Bullets in XNA, C# but an error in the Bullets class tells me that "texture" doesnt have a value

public class Bullet
{
public Rectangle boundingBox;
public Texture2D texture;
public Vector2 origin;
public Vector2 position;
public bool isVisible;
public float speed;
public Bullet (Texture2D newTexture)
{
speed = 10;
texture = newTexture;
isVisible = false;
}
public void Draw(SpriteBatch spritebatch)
{
spritebatch.Draw(texture, position, Color.White);
}
}
public class ClasePersonaje : Microsoft.Xna.Framework.Game
{
public Texture2D PersonajePrincipalClase { get; set; }
public int Filas { get; set; }
public int Columnas { get; set; }
public int marcoMax { get; set; }
public int marcoMin { get; set; }
public int marcoActual { get; set; }
private int marcosTotales;
private double contadorFrames;
public static int posPersonajePrincipalX = 30;
public static int posPersonajePrincipalY = 30;
public Texture2D bulletTexture;
public float bulletDelay;
public List<Bullet> bulletList;
public ClasePersonaje(Texture2D texturaPersonajePrincipal, int filas, int columnas)
{
PersonajePrincipalClase = texturaPersonajePrincipal;
Filas = filas;
Columnas = columnas;
marcoActual = marcoMin;
marcosTotales = filas * columnas;
bulletList = new List<Bullet>();
bulletDelay = 20;
}
public void Draw(SpriteBatch spriteBatch, Vector2 location, float size)
{
int ancho = PersonajePrincipalClase.Width / Columnas;
int altura = PersonajePrincipalClase.Height / Filas;
int fila = (int)((float)marcoActual / (float)Columnas);
int columna = marcoActual % Columnas;
Rectangle rectanguloOrigen = new Rectangle(ancho * columna, altura * fila, ancho, altura);
Rectangle rectanguloDestino = new Rectangle((int)location.X, (int)location.Y, (int)(ancho * size), (int)(altura * size));
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);
spriteBatch.Draw(PersonajePrincipalClase, rectanguloDestino, rectanguloOrigen, Color.White);
spriteBatch.End();
foreach (Bullet b in bulletList)
{
b.Draw(spriteBatch);
}
}
public void Update()
{
if (Game1.disparo)
{
Shoot();
}
UpdateBullets();
if (contadorFrames >= 100)
{
if (marcoActual < marcoMin || marcoMax <= marcoActual)
{
marcoActual = marcoMin;
}
else
{
marcoActual++;
}
if (Game1.derPersonaje)
{
if (Game1.derDisparo)
{
marcoMin = 0;
marcoMax = 3;
}
else if (Game1.izqDisparo)
{
marcoMin = 4;
marcoMax = 7;
}
else if (Game1.arDisparo)
{
marcoMin = 8;
marcoMax = 11;
}
else if (Game1.abDisparo)
{
marcoMin = 12;
marcoMax = 15;
}
if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
{
marcoMin = 0;
marcoMax = 3;
}
posPersonajePrincipalX += 10;
}
else if (Game1.izqPersonaje)
{
if (Game1.derDisparo)
{
marcoMin = 0;
marcoMax = 3;
}
else if (Game1.izqDisparo)
{
marcoMin = 4;
marcoMax = 7;
}
else if (Game1.arDisparo)
{
marcoMin = 8;
marcoMax = 11;
}
else if (Game1.abDisparo)
{
marcoMin = 12;
marcoMax = 15;
}
if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
{
marcoMin = 4;
marcoMax = 7;
}
posPersonajePrincipalX -= 10;
}
else if (Game1.arPersonaje)
{
if (Game1.derDisparo)
{
marcoMin = 0;
marcoMax = 3;
}
else if (Game1.izqDisparo)
{
marcoMin = 4;
marcoMax = 7;
}
else if (Game1.arDisparo)
{
marcoMin = 8;
marcoMax = 11;
}
else if (Game1.abDisparo)
{
marcoMin = 12;
marcoMax = 15;
}
if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
{
marcoMin = 8;
marcoMax = 11;
}
posPersonajePrincipalY -= 10;
}
else if (Game1.abPersonaje)
{
if (Game1.derDisparo)
{
marcoMin = 0;
marcoMax = 3;
}
else if (Game1.izqDisparo)
{
marcoMin = 4;
marcoMax = 7;
}
else if (Game1.arDisparo)
{
marcoMin = 8;
marcoMax = 11;
}
else if (Game1.abDisparo)
{
marcoMin = 12;
marcoMax = 15;
}
if (!Game1.arDisparo && !Game1.abDisparo && !Game1.derDisparo && !Game1.izqDisparo)
{
marcoMin = 12;
marcoMax = 15;
}
posPersonajePrincipalY += 10;
}
if (!Game1.abPersonaje && !Game1.arPersonaje && !Game1.derPersonaje && !Game1.izqPersonaje)
{
marcoActual = 12;
}
contadorFrames = 0;
}
else
{
contadorFrames += Game1.ElapsedTime;
}
}
public void Shoot()
{
if (bulletDelay >= 0)
{
bulletDelay--;
}
if (bulletDelay <= 0)
{
Bullet b = new Bullet(bulletTexture);
b.position = new Vector2(posPersonajePrincipalX, posPersonajePrincipalY);
b.isVisible = true;
if (bulletList.Count() < 20)
{
bulletList.Add(b);
}
}
if (bulletDelay == 0)
{
bulletDelay = 20;
}
}
public void UpdateBullets()
{
foreach (Bullet b in bulletList)
{
b.position.Y -= 10;
if(b.position.Y <= 0)
{
b.isVisible = false;
}
}
for (int i = 0; i < bulletList.Count(); i++)
{
if(!bulletList[i].isVisible)
{
bulletList.RemoveAt(i);
i--;
}
}
}
}
The error is in the texture inside the Draw Method of the Bullet Class (it says that it is null). I've been trying to solve this for 5 days and I still couldn't find a solution. And i know it's not that difficult but I'm new to programming and XNA (I started this in March)

Firecracker Kind of Animation in Windows 8 Metro

I am trying to make an animation in which a rocket like thing will go up the screen and blast into various parts and follow its path down and fade just like actual firecracker. I have tried to make it using an update loop and a draw loop and then rendering the images on a bitmap. But there is a lot of lag there in the animation. I want to implement this thing at the end of my game and when a user taps the screen the rocket will go to that place and then explode. The code which I have tried is here...
public class Plotter : UserControl, IDisposable
{
Random _rand = new Random((int)DateTime.Now.Ticks);
WriteableBitmap _particleBmp;
EventBlob[] _data;
private int NUMPBLOBS = 25;
private const int CANWIDTH = 1366;
private const int CANHEIGHT = 768;
double _lastx, _lasty;
public Plotter()
{
}
public async Task PlotterMethod(Point current)
{
_lastx = current.X;
_lasty = current.Y;
await Setup();
}
private async Task Setup()
{
_particleBmp = await Util.LoadBitmap("tspark.png");
CompositionTarget.Rendering += CompositionTarget_Rendering;
_data = new EventBlob[NUMPBLOBS];
int ang = 0;
for (int i = 0; i < NUMPBLOBS; i++)
{
EventBlob eb = new EventBlob();
eb.img = _particleBmp;
eb.SourceRect = new Rect(0, 0, 30, 30);
eb.Position.X = _rand.Next((int)_lastx - 10, (int)_lastx + 10);
eb.Position.Y = _rand.Next((int)_lasty - 10, (int)_lasty + 10);
eb.VX = 5;
eb.VY = 5;
eb.angle = ang;
ang += 36 / 5;
eb.Opacity = 1;
eb.BlendMode = WriteableBitmapExtensions.BlendMode.Additive;
eb.FadeRate = _rand.NextDouble() * 0.005 + 0.002;
Color c = new Color();
c.A = (byte)0;
c.R = (byte)_rand.Next(0, 255);
c.G = (byte)_rand.Next(0, 255);
c.B = (byte)_rand.Next(0, 255);
eb.Color = c;
_data[i] = eb;
}
}
int counterupdate = 0;
void CompositionTarget_Rendering(object sender, object e)
{
if (counterupdate % 2 == 0)
{
Update();
DrawBitmap();
}
counterupdate++;
}
int count = 0;
bool opacitycheck = true;
private void Update()
{
bool isallclear = true;
for (int i = 0; i < _data.Length; i++)
{
var p = _data[i];
if (i < 51)
{
p.VX = 2 * Math.Cos(p.angle);
p.VY = 2 * Math.Sin(p.angle);
}
p.Position.X += p.VX;
p.Position.Y += p.VY;
if (opacitycheck)
{
if (p.Color.A + 30 < 255)
p.Color.A += 30;
else
{
opacitycheck = false;
p.Color.A = 255;
}
}
else
{
if (p.Color.A - 30 > 0)
p.Color.A -= 30;
else
{
p.Color.A = 0;
}
}
if (p.Color.A != 0)
{
isallclear = false;
}
}
count++;
if (isallclear)
{
_data = new EventBlob[0];
CompositionTarget.Rendering -= CompositionTarget_Rendering;
NUMPBLOBS = 0;
opacitycheck = true;
Completed(this, null);
}
}
private void DrawBitmap()
{
using (TargetBmp.GetBitmapContext())
{
TargetBmp.Clear();
for (int i = 0; i < _data.Length; i++)
{
var b = _data[i];
this.TargetBmp.Blit(b.Position, b.img, b.SourceRect, b.Color, b.BlendMode);
}
TargetBmp.Invalidate();
}
}
public WriteableBitmap TargetBmp { get; set; }
public Image Imagemain { get; set; }
public event EventHandler<object> Completed;
public void Dispose()
{
}
}
public class EventBlob
{
public double Opacity { get; set; }
public double FadeRate { get; set; }
public Color Color;
public Rect SourceRect { get; set; }
public WriteableBitmap img { get; set; }
public Point Position;
public double VX { get; set; }
public double VY { get; set; }
public WriteableBitmapExtensions.BlendMode BlendMode;
public double angle { get; set; }
}
and in my main page i have called it like this...
async void MainPage_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (LayoutRoot.Children.Count < 6)
{
Plotter asd = new Plotter();
await asd.PlotterMethod(e.GetCurrentPoint(LayoutRoot).Position);
WriteableBitmap _wb = new WriteableBitmap(1366, 786);
asd.TargetBmp = _wb;
Image image = new Image();
image.Height = 786;
image.Width = 1366;
image.Stretch = Stretch.Fill;
image.Source = _wb;
asd.Imagemain = image;
asd.Completed += asd_Completed;
LayoutRoot.Children.Add(image);
}
}
void asd_Completed(object sender, object e)
{
var obj = (Plotter)sender;
LayoutRoot.Children.Remove(obj.Imagemain);
obj.Dispose();
}
but there is too much of lag if I create 4 of these objects the fps goes down to 10.
Please suggest a better way or a way to optimize this code. Thanks.
Try implementing the parallel feature of C# , For Reference check
http://www.parallelcsharp.com/
I hope this will solve your Problem

Drawing a line from a dot to dot (Point to Point) on Form MouseDown

I've been working days on a program that draws a grid of dots, and I had to start all over again several times because of a bad approach / to complicated. I've come to a point now where I have to draw a line from a clicked dot (point) to a second clicked dot (point) on the form.
Seriously I've been spending hours even days of my time searching for the right approach.
As for now I only managed to get a line drawn from a point on the form to another point on the form on random clicks...
Could someone please help get the code done, its just frustrating me how I don't have any progress after all attempts of drawing a grid of dots..
So what I want to do is "draw a line from a clicked dot (point) to a second clicked dot (point) on the form".
See below of my code:
Form1.cs:
public partial class Form1 : Form
{
private GridDrawing drawing;
private Point point1;
private Point point2;
List<Point> p1List = new List<Point>(); //Temp
List<Point> p2List = new List<Point>(); //Temp
//True if point1 must be updated
//False if point2 must be updated
private bool firstPoint = true;
private int sizeOfDot;
private int rows;
private int columns;
public Form1()
{
InitializeComponent();
sizeOfDot = 10; //The size of the dot
rows = 6; //The amount of rows for the matrix
columns = 8; //The amount of columns for the matrix
}
private void Form_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.White, ClientRectangle); //Fill the form in white
drawing = new GridDrawing(this, rows, columns); //Control, Rows, Columns
foreach (var piece in drawing.Pieces) //Draws all the dots
{
e.Graphics.FillEllipse(Brushes.Black, (piece.Dot.X - sizeOfDot / 2),
(piece.Dot.Y - sizeOfDot / 2), sizeOfDot, sizeOfDot); //Draws the dot
}
using (var pen = new Pen(Color.Black, 2))
{
for (int i = 0; i < p1List.Count; i++)
{
e.Graphics.DrawLine(pen, p1List[i], p2List[i]);
}
}
}
private void startToolStripMenuItem_Click(object sender, EventArgs e)
{}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (firstPoint) //Update point1 or point2
{
//Point 1
point1.X = e.X;
point1.Y = e.Y;
}
else
{
//Point 2
point2.X = e.X;
point2.Y = e.Y;
p1List.Add(point1);
p2List.Add(point2);
}
firstPoint = !firstPoint; //Change the bool value
Invalidate(); //Redraw
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
Invalidate();
}
}
GridDrawing.cs:
public class GridDrawing
{
private int columns;
private int rows;
private List<GridPiece> pieces;
private Point dot;
//private Point point1; //point1 to start drawing line from
//private Point point2; //point2 to end drawing line from
/// <summary>
/// Constructs a grid
/// </summary>
/// <param name="ctrl"></param>
/// <param name="rows"></param>
/// <param name="columns"></param>
/// <param name="sizeOfDot"></param>
public GridDrawing(Control ctrl, int rows, int columns)
{
this.rows = rows; // The amount of rows in the matrix.
this.columns = columns; // The amount of columns in the matrix.
this.pieces = new List<GridPiece>(); // Initializes the List GridPieces
int xOffset = (int)ctrl.ClientRectangle.Width / (columns + 1); // FP offset for X
int yOffset = (int)ctrl.ClientRectangle.Height / (rows + 1); // FP offset for Y
//Generate the dots
for (int i = 0; i < rows; i++) //Matrix with 6 rows
{
for (int j = 0; j < columns; j++) //Matrix with 8 columns
{
dot = new Point((j + 1) * xOffset, (i + 1) * yOffset); // Center of the dot
GridPiece p = new GridPiece(dot); // Creates a piece
pieces.Add(p); // Puts the piece that has to be drawn in the List<GridPiece>pieces
}
}
}
public List<GridPiece> Pieces //Property List<GridPiece>pieces
{
get { return this.pieces; }
}
public Point Dot //Property Point dot
{
get { return this.dot; }
}
}
GridPiece.cs:
public class GridPiece
{
private Point dot;
/// <summary>
/// Constructor of GriedPiece
/// </summary>
/// <param name="bmpPic"></param>
/// <param name="position"></param>
public GridPiece(Point dot)
{
this.dot = dot;
}
public Point Dot
{
get { return dot; }
}
}
Here's an example how I'm trying to make it look like
Could someone please help me?
Here is how to do this. add following code
public class Line
{
public float X1 { get; set; }
public float X2 { get; set; }
public float Y1 { get; set; }
public float Y2 { get; set; }
}
public sealed class Grid : Panel
{
readonly DotDrawing drawing = new DotDrawing();
private List<Line> Markers { get; set; }
public Grid()
{
this.DoubleBuffered = true;
Markers = new List<Line>();
}
protected override void OnPaint(PaintEventArgs e)
{
foreach (Line line in Markers)
{
using (Pen pen = new Pen(Brushes.Black))
{
pen.Width = 2;
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.DrawLine(pen, line.X1, line.Y1, line.X2, line.Y2);
}
}drawing.Render(e.Graphics);
base.OnPaint(e);
}
private Dot lastDot;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
var x = this.drawing.GetDotFromPoint(e.Location);
if (x != null)
{
lastDot = x;
}
else
{
lastDot = null;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
var x = this.drawing.GetDotFromPoint(e.Location);
if (x != null)
{
Line line = new Line();
line.X1 = lastDot.Center.X;
line.Y1 = lastDot.Center.Y;
line.X2 = x.Center.X;
line.Y2 = x.Center.Y;
this.Markers.Add(line);
Invalidate();
}
}
}
public class Dot
{
public PointF Location { get; set; }
public int Radius { get; set; }
public PointF Center
{
get
{
return new PointF(this.Bounds.Left + (float)this.Radius,
this.Bounds.Top + (float)this.Radius);
}
}
public RectangleF Bounds
{
get
{
return new RectangleF(Location, new SizeF(2 * Radius, 2 * Radius));
}
}
public Dot()
{
Radius = 5;
}
}
public class DotDrawing
{
private List<Dot> Dots { get; set; }
public int RowCount { get; set; }
public int ColumnCount { get; set; }
public int ColumnSpacing { get; set; }
public int RowSpacing { get; set; }
public int DotRadius { get; set; }
public DotDrawing()
{
Dots = new List<Dot>();
DotRadius = 10;
ColumnCount = 15;
RowCount = 25;
this.RowSpacing = 30;
this.ColumnSpacing = 30;
}
public void Render(Graphics g)
{
this.Dots.Clear();
float x = 0;
float y = 0;
for (int i = 0; i < RowCount; i++)
{
for (int j = 0; j < ColumnCount; j++)
{
{
Dot dot = new Dot();
dot.Location = new PointF(x, y);
using (SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml("#009aff")))
{
g.FillEllipse(brush, dot.Location.X, dot.Location.Y, DotRadius, DotRadius);
}
x += (DotRadius + ColumnSpacing);
Dots.Add(dot);
}
}
x = 0;
y += (DotRadius + this.RowSpacing);
}
}
public Dot GetDotFromPoint(PointF point)
{
for (int i = 0; i < this.Dots.Count; i++)
{
RectangleF rect = this.Dots[i].Bounds;
rect.Inflate(new SizeF(3, 3));
Region region = new Region(rect);
if (region.IsVisible(point))
{
return this.Dots[i];
}
}
return null;
}
}
Drag the Grid from the tool box.
Mouse Click on any of the dots without releasing it point to another grid you'll see the effect.

Categories

Resources