C# snake game problem with body extension monogame - c#

So I have this problem where my sprites draw to close to the head of my snake and therefore only takes very long time to complete the map. I have tried to increase the speed and lower the frame rate but it is very laggy.
//Comments are in Swedish
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
SpriteFont xcord;
SpriteFont ycord;
//Map settings
int mapX;
int mapY;
//Movement Variabels
//Snake Movement
bool snakemoveup;
bool snakemovedown;
bool snakemoveright;
bool snakemoveleft;
int speedx;
int speedy;
int score;
int timer;
int i;
List<Rectangle> snakelength = new List<Rectangle>();
List<int> positiony = new List<int>() { 300, 300 };
bool snakemoveup2;
bool snakemovedown2;
bool snakemoveright2;
bool snakemoveleft2;
bool snakemoveupMemory;
bool snakemovedownMemory;
bool snakemoverightMemory;
bool snakemoveleftMemory;
//Sprite Variables
//Textures
Texture2D snakehead;
Texture2D gamemap;
Texture2D gamemapborder;
Texture2D Leader_Right;
Texture2D Leader_Left;
Texture2D Leader_Up;
Texture2D Leader_Down;
Texture2D Follower;
Texture2D Candy;
//Sprite Rectangles
Rectangle snakerec;
Rectangle followerrec;
Rectangle candyrec;
//Position Variables
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}enter code here
protected override void Initialize()
{
// TODO: Add your initialization logic here
//MapSize
mapX = 900 + 100;
mapY = 800 + 100;
_graphics.PreferredBackBufferWidth = mapX;
_graphics.PreferredBackBufferHeight = mapY;
_graphics.ApplyChanges();
//Movement
speedx = 0;
speedy = 0;
base.Initialize();
}
protected override void LoadContent()
{
//läger till en svans i listan
snakelength.Add(new Rectangle(snakerec.X, snakerec.Y, 50, 50));
//sänker fps:n (nämnaren = önskade fps:n)
IsFixedTimeStep = true;
TargetElapsedTime = System.TimeSpan.FromSeconds(1d / 60);
xcord = Content.Load<SpriteFont>("File");
ycord = Content.Load<SpriteFont>("File");
_spriteBatch = new SpriteBatch(GraphicsDevice);
Leader_Right = Content.Load<Texture2D>("Leader_Right");
Leader_Left = Content.Load<Texture2D>("Leader_Left");
Leader_Up = Content.Load<Texture2D>("Leader_Up");
Leader_Down = Content.Load<Texture2D>("Leader_Down");
Candy = Content.Load<Texture2D>("Candy");
Follower = Content.Load<Texture2D>("Follower");
gamemap = Content.Load<Texture2D>("Snake_map");
gamemapborder = Content.Load<Texture2D>("Snakemapborder");
snakerec = new Rectangle(500, 450, Leader_Right.Width, Leader_Right.Height);
candyrec = new Rectangle(200,150, Candy.Width, Candy.Height);
// TODO: use this.Content to load your game content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
//gameTime.ElapsedGameTime.Milliseconds
//sätt en if innan ditt ökande
snakerec.X += speedx;
snakerec.Y += speedy;
if (Keyboard.GetState().IsKeyDown(Keys.W) && snakemovedown == false)
{
snakemoveup2 = true;
snakemoveupMemory = true;
}
if (Keyboard.GetState().IsKeyDown(Keys.D) && snakemoveleft == false)
{
snakemoveright2 = true;
snakemoverightMemory = true;
}
if (Keyboard.GetState().IsKeyDown(Keys.A) && snakemoveright == false)
{
snakemoveleft2 = true;
snakemoveleftMemory = true;
}
if (Keyboard.GetState().IsKeyDown(Keys.S) && snakemoveup == false)
{
snakemovedown2 = true;
snakemovedownMemory = true;
}
if (snakerec.X % 50 == 0 && snakemoveupMemory == true)
{
speedy = -5;
speedx = 0;
snakemoveup = true;
snakemovedown = false;
snakemoveright = false;
snakemoveleft = false;
snakemoveupMemory = false;
}
if (snakerec.Y % 50 == 0 && snakemoveleftMemory == true)
{
speedy = 0;
speedx = -5;
snakemoveleft = true;
snakemovedown = false;
snakemoveright = false;
snakemoveup = false;
snakemoveleftMemory = false;
}
if (snakerec.X % 50 == 0 && snakemovedownMemory == true )
{
speedy = 5;
speedx = 0;
snakemovedown = true;
snakemoveup = false;
snakemoveright = false;
snakemoveleft = false;
snakemovedownMemory = false;
}
if (snakerec.Y % 50 == 0 && snakemoverightMemory == true)
{
speedy = 0;
speedx = 5;
snakemoveright = true;
snakemovedown = false;
snakemoveup = false;
snakemoveleft = false;
snakemoverightMemory = false;
}
if (Keyboard.GetState().IsKeyUp(Keys.W))
{
snakemoveup2 = false;
}
if (Keyboard.GetState().IsKeyUp(Keys.S))
{
snakemovedown2 = false;
}
if (Keyboard.GetState().IsKeyUp(Keys.A))
{
snakemoveleft2 = false;
}
if (Keyboard.GetState().IsKeyUp(Keys.D))
{
snakemoveright2 = false;
}
//Godis
Random randomx = new Random();
Random randomy = new Random();
List<int> godtalx = new List<int>() { 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900 };
List<int> godtaly = new List<int>() { 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800 };
if (snakerec.Intersects(candyrec))
{
candyrec.X = godtalx[randomx.Next(1, 18)];
candyrec.Y = godtaly[randomx.Next(1, 16)];
score++;
snakelength.Add(new Rectangle(snakerec.X, snakerec.Y, 50, 50));
}
//Follower
if (snakelength.Count != score)
{
for (int i = snakelength.Count - 1; i > 0; i--)
{
snakelength[i] = new Rectangle(snakelength[i - 1].X, snakelength[i - 1].Y, 50, 50);
}
}
snakelength[0] = new Rectangle(snakerec.X, snakerec.Y, 50, 50);
//Infite borders
//X
if (snakerec.X <= 50 || snakerec.X >= 900)
{
if (snakerec.X <= 0)
{
snakerec.X = 995;
}
if (snakerec.X >= 1000)
{
snakerec.X = 5;
}
}
//Y
if (snakerec.Y <= 50 || snakerec.Y >= 800)
{
if (snakerec.Y <= 0)
{
snakerec.Y = 895;
}
if (snakerec.Y >= 900)
{
snakerec.Y = 5;
}
}
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
_spriteBatch.Begin();
_spriteBatch.Draw(gamemap, new Vector2(0, 0), Color.White);
for (int i = 0; i < snakelength.Count; i++)
{
_spriteBatch.Draw(Follower, new Rectangle(snakelength[i].X, snakelength[i].Y, 50, 50), Color.White);
}
//Vilket håll huvudet kollar mot
if (true)
{
if (snakemoveup == true)
{
_spriteBatch.Draw(Leader_Up, snakerec, Color.White);
}
if (snakemoveright == true)
{
_spriteBatch.Draw(Leader_Right, snakerec, Color.White);
}
if (snakemoveleft == true)
{
_spriteBatch.Draw(Leader_Left, snakerec, Color.White);
}
if (snakemovedown == true)
{
_spriteBatch.Draw(Leader_Down, snakerec, Color.White);
}
}
_spriteBatch.Draw(Candy, candyrec, Color.White);
_spriteBatch.Draw(gamemapborder, new Vector2(0, 0), Color.White);
_spriteBatch.DrawString(xcord, (snakelength.Count).ToString(), new Vector2(0, 60), Color.Black);
_spriteBatch.DrawString(xcord, (snakerec.X).ToString(), new Vector2(0, 0), Color.Black);
_spriteBatch.DrawString(ycord, (snakerec.Y).ToString(), new Vector2(0, 30), Color.Black);
_spriteBatch.End();
}
}
}

Related

Monogame, why wont the block move even if there is an function for it?

I need some help, I have this labyrinth game where I need to push a block. If I intersect with the block the first one is supposed to move to the right and the second one is supposed to move to the left. The problem is that I can't get either of them to move when I intersect. Help would be appreciated.
Game1.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
namespace Labyrintspel
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
Texture2D pixelTexture;
Texture2D playerTexture;
List<Block> blocks = new List<Block>();
Player player;
Color backgroundColor = Color.CornflowerBlue;
Block door;
Block door2;
int i = 0;
int i2 = 0;
int speed1 = 1;
int speed2 = -1;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
_graphics.PreferredBackBufferWidth = 800;
_graphics.PreferredBackBufferHeight = 500;
_graphics.ApplyChanges();
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
base.Initialize();
blocks.Add(BlockFactory.CreateEatableBlock(70, 300));
blocks.Add(BlockFactory.CreateEatableBlock(190, 300));
blocks.Add(BlockFactory.CreateEatableBlock(490, 300));
blocks.Add(BlockFactory.CreateWall(0, 460, 800, 40));
blocks.Add(BlockFactory.CreateWall(0, 0, 800, 30));
blocks.Add(BlockFactory.CreateWall(0, 0, 40, 460));
blocks.Add(BlockFactory.CreateWall(760, 0, 40, 460));
blocks.Add(BlockFactory.CreateWall(640, 200, 40, 260));
blocks.Add(BlockFactory.CreateWall(140, 100, 700, 40));
blocks.Add(BlockFactory.CreateWall(540, 130, 40, 250));
blocks.Add(BlockFactory.CreateWall(440, 200, 40, 260));
blocks.Add(BlockFactory.CreateWall(340, 130, 40, 250));
blocks.Add(BlockFactory.CreateWall(240, 200, 40, 260));
blocks.Add(BlockFactory.CreateWall(140, 130, 40, 250));
blocks.Add(BlockFactory.RemovableWall(600, 0, 40, 100));
blocks.Add(BlockFactory.CreateWall(650, 375, 150, 200));
door = new Block(720, 40, 30, 50, Color.SaddleBrown);
blocks.Add(door);
door2 = new Block(700, 400, 30, 50, Color.SaddleBrown);
player = new Player(700, 300, playerTexture.Width, playerTexture.Height);
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
pixelTexture = Content.Load<Texture2D>("pixel");
playerTexture = Content.Load<Texture2D>("player");
}
protected override void Update(GameTime gameTime)
{
var keyState = Keyboard.GetState();
base.Update(gameTime);
player.StorePosition();
if (keyState.IsKeyDown(Keys.Left)) player.MoveLeft();
if (keyState.IsKeyDown(Keys.Right)) player.MoveRight();
if (keyState.IsKeyDown(Keys.Up)) player.MoveUp();
if (keyState.IsKeyDown(Keys.Down)) player.MoveDown();
if (player.GetRectangle().Intersects(door.Rectangle))
{
i = 0;
blocks.RemoveAll(block => block.IsVisible);
blocks.Add(BlockFactory.CreateWall(0, 460, 800, 40));
blocks.Add(BlockFactory.CreateWall(0, 0, 800, 30));
blocks.Add(BlockFactory.CreateWall(0, 0, 40, 460));
blocks.Add(BlockFactory.CreateWall(760, 0, 40, 460));
blocks.Add(BlockFactory.CreateWall(100, 100, 800, 40));
blocks.Add(BlockFactory.CreateWall(0, 200, 400, 40));
blocks.Add(BlockFactory.CreateWall(500, 200, 400, 40));
blocks.Add(BlockFactory.CreateWall(0, 300, 200, 40));
blocks.Add(BlockFactory.CreateWall(300, 300, 500, 40));
blocks.Add(BlockFactory.RemovableWall(600, 300, 40, 300));
blocks.Add(BlockFactory.CreateEatableBlock(700, 250));
blocks.Add(BlockFactory.CreateEatableBlock(190, 150));
blocks.Add(BlockFactory.CreateEatableBlock(500, 400));
blocks.Add(BlockFactory.CreatePushableBlock(50, 150));
blocks.Add(BlockFactory.CreatePushableBlock(50, 400));
blocks.Add(door2);
}
if (player.GetRectangle().Intersects(door2.Rectangle))
{
this.Exit();
}
backgroundColor = Color.CornflowerBlue;
foreach (var block in blocks)
{
if (player.GetRectangle().Intersects(block.Rectangle))
{
if (block.IsPushable && keyState.IsKeyDown(Keys.Space) && i2 == 0)
{
block.MoveRight();
i2++;
}
if (block.IsSolid) player.RestorePosition();
if (block.IsEatable)
{
block.IsVisible = false;
i++;
}
}
if (i == 3)
{
if (block.IsRemovable)
{
block.IsSolid = false;
block.IsVisible = false;
}
}
}
blocks.RemoveAll(block => !block.IsVisible);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(backgroundColor);
_spriteBatch.Begin();
blocks.ForEach(block => block.Draw(_spriteBatch, pixelTexture));
player.Draw(_spriteBatch, playerTexture);
_spriteBatch.End();
Window.Title = "Antal block: " + blocks.Count;
base.Draw(gameTime);
}
}
Block.cs
public class Block
{
public Rectangle Rectangle { get; set; }
public Color Color { get; set; }
public bool IsSolid { get; set; } = true;
public bool IsEatable { get; set; } = false;
public bool IsVisible { get; set; } = true;
public bool IsRemovable { get; set; } = false;
public bool IsPushable { get; set; } = false;
private Vector2 position;
private Rectangle rectangle;
public Block(int x, int y, int w, int h, Color color)
{
Color = color;
position.X = x;
position.Y = y;
Rectangle = new Rectangle(x, y, w, h);
}
public void Move(float dx, float dy)
{
position.X += dx;
position.Y += dy;
}
public Rectangle PushabelRectangle()
{
rectangle.X = (int)position.X;
rectangle.Y = (int)position.Y;
return rectangle;
}
internal void MoveLeft() => Move(-10, 0);
internal void MoveRight() => Move(100, 0);
public void Draw(SpriteBatch spriteBatch, Texture2D texture)
{
if (IsVisible)
{
spriteBatch.Draw(texture, Rectangle, Color);
}
}
}
blockfactory.cs
internal class BlockFactory
{
internal static Block CreateEatableBlock(int x, int y)
{
var block = new Block(x, y, 40, 40, Color.Yellow);
block.IsSolid = false;
block.IsEatable = true;
return block;
}
internal static Block CreatePushableBlock(int x, int y)
{
var block = new Block(x, y, 40, 40, Color.Orange);
block.IsPushable = true;
return block;
}
internal static Block CreateWall(int x, int y, int w, int h)
{
return new Block(x, y, w, h, Color.Black);
}
internal static Block RemovableWall(int x, int y, int w, int h)
{
var block = new Block(x, y, w, h, Color.Black);
block.IsSolid = true;
block.IsEatable = false;
block.IsVisible = true;
block.IsRemovable = true;
return block;
}
internal static Block CreatePushBlock(int x, int y, int w, int h)
{
return new Block(x, y, w, h, Color.Orange);
}
}
This code shows no error but nothing happens when I intersect and press spacebar.
Move() is changing the position variable, but the block is drawing from the Rectangle field, which is not changed to reflect the movement.
I would suggest the following correlation:
public Rectangle Rectangle { get{return rectangle; } set {rectangle = value;} })
public void Move(float dx, float dy)
{
position.X += dx;
position.Y += dy;
Rectangle = new Rectangle((int)position.X, (int)position.Y, Rectangle.Width, Rectangle.Height);
// you cannot set the X and Y of field structures directly.
}

How to fix onGUI method to a panel

I want to fix OnGUI method inside in a script to a panel. Especially what I want to do is, In free aspect, when I change the size of game screen, also my text which is writen with onGUI changes depending on size of the game screen.
public HumanBodyVisualizer bodyVisualizer;
public GameObject text;
Vector2 scrollPosition = Vector2.zero;
float scrollPosition_y = 30;
private void OnGUI()
{
//Debug.Log(text.transform.position.y);
int subPartsSpacing = 0;
float spacing = 30;
float x = 7 + spacing;
float y = text.transform.position.y;
HumanBodyPart mainBodyPart = bodyVisualizer.BodyData.Body.SubParts[0];
List<HumanBodyPart> nextPartsToRender = new List<HumanBodyPart>(new HumanBodyPart[] { mainBodyPart });
List<HumanBodyPart> allPartsToRender = new List<HumanBodyPart>(new HumanBodyPart[] { mainBodyPart });
scrollPosition = GUI.BeginScrollView(new Rect(7, 68, 236, 426), scrollPosition, new Rect(7, 68, 500, scrollPosition_y));
GUI.backgroundColor = Color.clear;
while (nextPartsToRender.Count > 0)
{
HumanBodyPart currentPart = nextPartsToRender[0];
nextPartsToRender.RemoveAt(0);
if(GUI.Button(new Rect(currentPart.DrawDepth * spacing + x + subPartsSpacing, y, 200, 20), currentPart.EnglishTitle))
{
HumanBodyVisualizer.ShowMode showModeFullBody = HumanBodyVisualizer.ShowMode.Invisible;
bodyVisualizer.ShowBody(showModeFullBody);
List<HumanBodyPart> AllSubPartsAndRoot = new List<HumanBodyPart>();
AllSubPartsAndRoot.Insert(0, currentPart);
allSubPartsOfClickButton(currentPart, AllSubPartsAndRoot, 1);
HumanBodyVisualizer.ShowMode showModeCurrentPart = HumanBodyVisualizer.ShowMode.LowTransparent;
//bodyVisualizer.ShowBodyPart(showModeCurrentPart, currentPart);
for (int i = 0; i < AllSubPartsAndRoot.Count; i++)
{
bodyVisualizer.ShowBodyPart(showModeCurrentPart,AllSubPartsAndRoot[i]);
}
/*
List<String> modelList = currentPart.ModelList;
for(int i = 0; i < modelList.Count; i++)
{
Debug.Log(modelList[i]);
}
*/
}
if (currentPart.SubParts.Count != 0)
{
if (GUI.Button(new Rect(x - spacing + currentPart.DrawDepth * spacing + subPartsSpacing, y, 20, 20), "+"))
{
if (!currentPart.IsExpanded)
{
currentPart.IsExpanded = true;
subPartsSpacing += 20;
}
else
currentPart.IsExpanded = false;
}
if (currentPart.IsExpanded)
{
nextPartsToRender.InsertRange(0, currentPart.SubParts);
allPartsToRender.InsertRange(allPartsToRender.Count - 1, currentPart.SubParts);
scrollPosition_y = allPartsToRender.Count * spacing ;
}
}
y += spacing;
}
// End the scroll view that we began above.
GUI.EndScrollView();
}
private void allSubPartsOfClickButton(HumanBodyPart root, List<HumanBodyPart> AllSubparts,int a)
{
AllSubparts.Insert(a, root);
a++;
for(int i = 0; i < root.SubParts.Count; i++)
{
allSubPartsOfClickButton(root.SubParts[i], AllSubparts, a);
}
}
When I run like that, even I change the size of game screen, OnGUI text(Buttons , labels and scrollview) stay constant on the screen.
I can not use Unity UI. I have to handle this problem with using onGUI.

Capturing screen not actually capturing right region

In C# I have written an application where you select a box to take a screen shot of and what happens is if you are above a 0 on the X axis it doesn't take a picture. I drew a small image to show what I mean:
Red = Image will actually not be of that section
Black = Ok
My code is as follows:
#region testing
private Point start = Point.Empty;
private Point end = Point.Empty;
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) != 0)
{
start.X = e.X;
start.Y = e.Y;
}
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
Point p1;
Point p2;
if (((e.Button & MouseButtons.Left) != 0) && (start != Point.Empty))
{
using (Graphics g = this.CreateGraphics())
{
p1 = PointToScreen(start);
if (end != Point.Empty)
{
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2),
Color.Black, FrameStyle.Dashed);
}
end.X = e.X;
end.Y = e.Y;
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2),
Color.Black, FrameStyle.Dashed);
}
}
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
Point p1;
Point p2;
if ((end != Point.Empty) && (start != Point.Empty))
{
using (Graphics g = this.CreateGraphics())
{
p1 = PointToScreen(start);
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2),
Color.Black, FrameStyle.Dashed);
int x1 = p1.X;
int y1 = p1.Y;
int x2 = p2.X;
int y2 = p2.Y;
int x = x2 - x1;
int y = y2 - y1;
string[] xsp;
int rx = 0;
string[] ysp;
int ry = 0;
if (x.ToString().Contains("-"))
{
xsp = x.ToString().Split('-');
rx = Convert.ToInt32(xsp[1]);
}
else
{
rx = x;
}
if (y.ToString().Contains("-"))
{
ysp = y.ToString().Split('-');
ry = Convert.ToInt32(ysp[1]);
}
else
{
ry = y;
}
using (Bitmap bmpScreenCapture = new Bitmap(rx, ry, g))
{
using (Graphics gra = Graphics.FromImage(bmpScreenCapture))
{
if(x.ToString().Contains("-"))
{
gra.CopyFromScreen(x2, y1, 0, 0, bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
else if(!x.ToString().Contains("-"))
{
gra.CopyFromScreen(x1, y1, 0, 0, bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
else if(y.ToString().Contains("-"))
{
gra.CopyFromScreen(x1, y2, 0, 0, bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
else if (!y.ToString().Contains("-"))
{
gra.CopyFromScreen(x1, y1, 0, 0, bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
else if (x.ToString().Contains("-") && y.ToString().Contains("-"))
{
gra.CopyFromScreen(x2, y2, 0, 0, bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
string filename = GenerateRandomString(20) + ".png";
bmpScreenCapture.Save(Path.GetTempPath() + "" + filename,
ImageFormat.Png);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints
(new Point(0), new Point(0)), Color.Black, FrameStyle.Dashed);
//Upload(Path.GetTempPath() + "" + filename, filename);
}
}
}
}
start = Point.Empty;
end = Point.Empty;
}
private Rectangle GetRectangleForPoints(Point beginPoint, Point endPoint)
{
int top = beginPoint.Y < endPoint.Y ? beginPoint.Y : endPoint.Y;
int bottom = beginPoint.Y > endPoint.Y ? beginPoint.Y : endPoint.Y;
int left = beginPoint.X < endPoint.X ? beginPoint.X : endPoint.X;
int right = beginPoint.X > endPoint.X ? beginPoint.X : endPoint.X;
rect = new Rectangle(left, top, (right - left), (bottom - top));
return rect;
}
#endregion
I have attempted to correct it and I have had no success. I mean the picture still shows up but it is not the right region of the screen.
I started to use a different selection method and that allowed for me to get the rectangles X and Y and Size. A lot better solution :)
Code:
#region testing
private Point start = Point.Empty;
private Point end = Point.Empty;
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) != 0)
{
start.X = e.X;
start.Y = e.Y;
}
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
//this.Invalidate();
Point p1;
Point p2;
if (((e.Button & MouseButtons.Left) != 0) && (start != Point.Empty))
{
using (Graphics g = this.CreateGraphics())
{
g.Clear(this.BackColor);
p1 = PointToScreen(start);
if (end != Point.Empty)
{
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2), Color.Black, FrameStyle.Dashed);
}
end.X = e.X;
end.Y = e.Y;
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2), Color.Black, FrameStyle.Dashed);
}
}
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
Point p1;
Point p2;
if ((end != Point.Empty) && (start != Point.Empty))
{
using (Graphics g = this.CreateGraphics())
{
p1 = PointToScreen(start);
p2 = PointToScreen(end);
ControlPaint.DrawReversibleFrame(GetRectangleForPoints(p1, p2), Color.Black, FrameStyle.Dashed);
int x1 = p1.X;
int y1 = p1.Y;
int x2 = p2.X;
int y2 = p2.Y;
int x = x2 - x1;
int y = y2 - y1;
string[] xsp;
int rx = 0;
string[] ysp;
int ry = 0;
if (x.ToString().Contains("-"))
{
xsp = x.ToString().Split('-');
rx = Convert.ToInt32(xsp[1]);
}
else
{
rx = x;
}
if (y.ToString().Contains("-"))
{
ysp = y.ToString().Split('-');
ry = Convert.ToInt32(ysp[1]);
}
else
{
ry = y;
}
using (Bitmap bmpScreenCapture = new Bitmap(rect.Width, rect.Height, g))
{
using (Graphics gra = Graphics.FromImage(bmpScreenCapture))
{
gra.CopyFromScreen(rect.X, rect.Y, 0, 0, bmpScreenCapture.Size, CopyPixelOperation.SourceCopy);
string filename = GenerateRandomString(20) + ".png";
bmpScreenCapture.Save(Path.GetTempPath() + "" + filename, ImageFormat.Png);
g.Clear(this.BackColor);
//Upload(Path.GetTempPath() + "" + filename, filename);
}
}
}
}
start = Point.Empty;
end = Point.Empty;
}
private Rectangle GetRectangleForPoints(Point beginPoint, Point endPoint)
{
int top = beginPoint.Y < endPoint.Y ? beginPoint.Y : endPoint.Y;
int bottom = beginPoint.Y > endPoint.Y ? beginPoint.Y : endPoint.Y;
int left = beginPoint.X < endPoint.X ? beginPoint.X : endPoint.X;
int right = beginPoint.X > endPoint.X ? beginPoint.X : endPoint.X;
rect = new Rectangle(left, top, (right - left), (bottom - top));
return rect;
}
#endregion

C# Object and class in XNA

I am creating a class with specific number of objects.When these objects are created and drawn on screen with that capacity again I reinitialize that class.The problem is that I want to reinitialize in such a way that if new objects are created then previous must be persist/drawn on the screen.I am not able to get the logic.
crShade = new CreateShade[Obj_num]; for (int i = incr_Obj; i < crShade.Length; i++) {
int r = rad.Next(0, 7); int x = 0; switch (r) {
case 0: x = 0; break; case 1: x = 120; break; case 2: x = 240; break; case 3: x = 360; break;
}
X_pos.Add(x); crShade[i] = new CreateShade(x, -60, clr[3]); _Shade.Add(crShade[i]);
}
--
public class CreateShade {
public int posX; public int posY; public Color color; Random r = new Random(); private int width = 120; private int height = 60; public static bool _Fall; public static bool check; public static List<int> y_pos = new List<int>(); int balance = 0; public CreateShade(int x, int y, Color color) {
int random = r.Next(0, 4); this.posY = y; this.posX = x; this.color = color;
}
public void draw(SpriteBatch batch) {
batch.Draw(Vimap_ScreenManager.blank, new Rectangle(posX, posY, width, height), color);
}
public void update() {
int counter = 0; if (posY != 740-balance) {
posY += 10; if (counter != y_pos.Count) {
if (new Rectangle(posX, posY, 120, 60).Intersects(new Rectangle(VimapGamePage.X_pos.ElementAt(counter), y_pos.ElementAt(counter), 120, 60))) {
balance = counter * 60;
}
else {
counter++;
}
}
//check = true;
}
else {
y_pos.Add(posY); _Fall = true; // VimapGamePage.End_Reach = true;
}
}
public void Move_X(Point p) {
if (p.X <= 240) {
if (p.X >= 0 && p.X <= 120) {
posX = 0;
}
else if (p.X > 120 && p.X <= 240) {
posX = 120;
}
}
else if (p.X > 240) {
if (p.X > 240 && p.X <= 360) {
posX = 240;
}
else if (p.X > 360 && p.X <= 480) {
posX = 360;
}
}
}
}

C# Maze solver Graphic

i got a problem with my maze solver when i run the solver it gives a error at the graphic variable
private bool solveMaze(int xPos, int yPos, bool[,] alreadySearched)
{
bool correctPath = false;
bool shouldCheck = true;
Bitmap map = (Bitmap)Mazebox.Image;
Graphics gfx = null;
gfx = Graphics.FromImage(map);
Brush b = new SolidBrush(Color.CornflowerBlue);
//out of index check
if (xPos >= XTILES || xPos < 0 || yPos >= YTILES || yPos < 0)
shouldCheck = false;
if (map.GetPixel(xPos , yPos) == Color.Green)
{
correctPath = true;
}
//Search the Tile
if (shouldCheck)
{
//mark tile as searched
alreadySearched[xPos, yPos] = true;
//Check right tile
correctPath = correctPath || solveMaze(xPos + 1, yPos, alreadySearched);
//Check down tile
correctPath = correctPath || solveMaze(xPos, yPos + 1, alreadySearched);
//check left tile
correctPath = correctPath || solveMaze(xPos - 1, yPos, alreadySearched);
//check up tile
correctPath = correctPath || solveMaze(xPos, yPos - 1, alreadySearched);
}
//make correct path gray
if (correctPath)
{
gfx.FillRectangle(b, xPos, yPos, 10, 10);
Mazebox.Image = map;
}
return correctPath;
}
i think the problem is that he opens it alot and then it crash(infinity)
Can anyone help me with this problem?
you are never using your alreadySearched field.
you can do this by inserting
shouldCheck = shouldCheck && !alreadySearched[xPos, yPos];

Categories

Resources