Source not available keeps on popping up
I have been searching google for quite some time now and most of the solutions I saw were changing Visual Studio's Settings, tried them but still it doesn't solve the issue
I have the following code
[DllImport("BS2dll.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool FiRE(int ptr, int l);
in another form
public void createButton2()
{
int x = 0, y = 0;
butt2 = new Button[100];
for (int i = 0; i < 100; i++)
{
butt2[i] = new Button();
int names = i;
butt2[i].Name = "2" + names.ToString();
butt2[i].Location = new Point(520 + (x * 31), 70 + (y * 21));
butt2[i].Visible = true;
butt2[i].Size = new Size(32, 22);
butt2[i].BackColor = Color.CornflowerBlue;
this.Controls.Add(butt2[i]);
butt2[i].Click += new EventHandler(butt2_2_Click);
x++;
if (x == 10)
{
x = 0; y++;
}
}
}
event handler
private void butt2_2_Click(object sender, EventArgs e)
{
bool hit;
int loc;
Button pushedBtn = sender as Button;
if (pushedBtn != null)
{
pushedBtn.BackColor = Color.Blue;
pushedBtn.Enabled = false;
loc = int.Parse(pushedBtn.Name);
if (loc > 29)
loc -= 200;
else
loc -= 20;
hit = UnsafeMethodCall.FiRE(objPtr, loc);
if (hit == true)
{
// MessageBox.Show("HIT");
pushedBtn.BackColor = Color.Red;
}
else
{
//MessageBox.Show("MISS");
pushedBtn.BackColor = Color.Black;
}
}
}//error appears around here
even if I comment hit = UnsafeMethodCall.FiRE(objPtr, loc); it still persists
my dll if it helps
void __stdcall FiRE(int *ptr, int l)
{
Battleship *dll = (Battleship *) ptr;
dll->FIRE(l);
}
bool Battleship::FIRE( int l) //check if hit or miss
{
for(int i= 0; i<17; i++)
{
if (board[i]==l)
{
hit = true;
break;
}
else
hit = false;
break;
}
return hit;
}
My Settings
Settings
so I think my problem is at the event handling part, since even if I remove the call to the dll, error still persists
as you may have noticed, it is a battleship game
when I hit a ship for the first time, it returns true, next attempts would just return false
You should check and make sure all of your source files are being looked at, especially for external libraries that you imported. Go to the solution and right the properties. In the window the pops up [below] go to the Debug Source Files.
Related
I am working on a game. For this game i create around 200 images in a box 20x10.
My problem is that pressing 1 button creates them a lot of times which garbages the Memory, which i want to avoid. So i created a little if/else function which is supposed to check wether the images were created or not. In case they weren't, code creates them, but if they were, the code should delete them, and i have no idea how to delete code generated images or how to interract with them at all.
public void GameStart(bool load = false)
{
Random rnd = new Random();
Pause.IsEnabled = true;
Save.IsEnabled = true;
Shuffle.IsEnabled = true;
byte datasave = 0;
int[,] TileID = new int[20,10];
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 10; j++)
{
if(TileID[i,j] != 0)
{
datasave = 1;
}
TileID[i, j] = rnd.Next(1,9);
CreateImage(i, j, TileID[i,j], datasave);
}
}
}
public void CreateImage(int a, int b, int TileID, byte datainfo)
{
if(datainfo != 0)
{
Image image = new Image();
image.Width = 40;
image.Height = 40;
image.Name = $"Tile{a}{b}";
image.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
image.VerticalAlignment = System.Windows.VerticalAlignment.Center;
image.Margin = new Thickness(-1000 + 80 * a, -200 + 80 * b, 0, 0);
string way = #"C:\Users\ignat\Desktop\Игра\Images\";
image.Source = new BitmapImage(new Uri(way + $"icon{TileID}.jpg", UriKind.Absolute));
Grid.Children.Add(image);
}
else
{
CreateImage(a, b, TileID, datainfo);
}
I'm creating a procedurally generated platformer in the C# console, out of interest. However, I found that the program runs slower than I would expect unless I hold any button, then it returns to the expected amount entered as timeLapse.
Currently the only button with a functionality is the space bar, which makes you jump. I tested the code as well without the code on line // THIS CODE, and that removes the problem. Does anyone have an explanation or an article about this? Couldn't find a lot myself.
PlatformGenerator code could be added, although I don't think it would be necessary.
Program code:
namespace TestProject.Procedural_Generation
{
public class PlatformManager
{
#region Variables
// Game settings
private static char[,] screen;
private static int screenWidth = 96;
private static int screenHeight = 20;
// Platform generation settings
private static int minGeneration = 4;
private static int maxGeneration = 18;
private static PlatformGenerator pg;
private static List<Platform> platforms = new List<Platform>();
// Physics variables
private static int oldX = 0;
private static int currentX = 0;
private static int currentY = 8;
private static string toSkip = "";
private static Player player;
// Timer variables
private static float timeLapse = 100;
private static float jumpTime = 200;
private static Timer graphicUpdater;
private static Timer physicUpdater;
private static Timer jumpTimer;
private static bool isJumping = false;
private static long score = 0;
#endregion
public PlatformManager()
{
screen = new char[screenHeight, screenWidth];
pg = new PlatformGenerator(minGeneration, maxGeneration);
player = new Player();
// Physics
physicUpdater = new Timer(timeLapse);
physicUpdater.Elapsed += ExecutePhysics;
physicUpdater.AutoReset = true;
physicUpdater.Enabled = true;
jumpTimer = new Timer(jumpTime);
jumpTimer.Elapsed += Land;
jumpTimer.Enabled = true;
// Graphics
graphicUpdater = new Timer(timeLapse);
graphicUpdater.Elapsed += ExecuteGraphics;
graphicUpdater.AutoReset = true;
graphicUpdater.Enabled = true;
while (true)
{
score++;
}
}
private void Land(object source, EventArgs e)
{
isJumping = false;
}
#region Graphics
private void ExecuteGraphics(object source, ElapsedEventArgs e)
{
Console.Clear();
Console.Write(Display());
}
// Makes sure everything is printed correctly
public string Display()
{
string result = "";
for (int y = 0; y < screenHeight; y++)
{
for (int x = 0; x < screenWidth; x++)
{
if (y == player.y && x == player.x)
{
result += "O";
}
else if (screen[y, x] == '=')
{
result += "=";
}
else
{
result += " ";
}
}
result += "\n";
}
return result;
}
#endregion
#region Physics
// Controls platform generation and movement
private void ExecutePhysics(object source, ElapsedEventArgs e)
{
Platformer();
if (player.y == screenHeight - 1)
{
graphicUpdater.Stop();
physicUpdater.Stop();
Console.WriteLine();
Console.WriteLine("Game over! Score: " + Math.Floor(Math.Sqrt(score)));
}
else if (isJumping)
{
player.y -= 1;
}
else if (Console.ReadKey(true).Key == ConsoleKey.Spacebar && screen[player.y + 1, player.x] == '=') // THIS CODE
{
isJumping = true;
jumpTimer.Start();
player.y -= 1;
}
else if (screen[player.y + 1, player.x] != '=' && !isJumping)
{
player.y += 1;
}
}
// Generate a new platform
public void Platformer()
{
Platform newPlatform = pg.Generate(currentX, currentY);
currentY = newPlatform.y;
if (currentX + newPlatform.size + newPlatform.xDif > screenWidth)
{
MoveScreen(newPlatform.size + newPlatform.xDif);
currentX -= newPlatform.size + newPlatform.xDif;
oldX -= newPlatform.size + newPlatform.xDif;
}
while (currentX < oldX + newPlatform.size + newPlatform.xDif)
{
screen[currentY, currentX] = '=';
currentX += 1;
}
oldX = currentX;
}
// Update all rows so the newly added ones fit.
public void MoveScreen(int amount)
{
for (int y = 0; y < screenHeight; y++)
{
for (int x = amount; x < screenWidth; x++)
{
screen[y, x - amount] = screen[y, x];
}
}
for (int y = 0; y < screenHeight; y++)
{
for (int x = screenWidth - amount; x < screenWidth; x++)
{
screen[y, x] = '\0';
}
}
}
#endregion
}
}
Not sure If I understand correclty, but the
Console.ReadKey(true).Key == ConsoleKey.Spacebar
waits for a keypress to happen, so the code will not be processed until a key is actually pressed, if you remove that the programm will obviously move "faster" because it does not wait for a keypress to happen
This is my code so far,im trying to make a c# connect four game but i cant seem to get the win checker to work! I'd like for my game to be able to check for four in a row, horizontally, vertically and diagonally and show a message telling you the winner. I have checked and everything else works as it should.
namespace ConnectFour
{
public partial class Form1 : Form
{
Button[] gameButtons = new Button[42]; //array of buttons for markers(red and blue)
bool blue = true; //blue is set to true if the next marker is to be a blue
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Connect 4";
this.BackColor = Color.BlanchedAlmond;
this.Width = 500;
this.Height = 500;
for (int i = 0; i < gameButtons.Length; i++)
{
int index = i;
this.gameButtons[i] = new Button();
int x = 50 + (i % 7) * 50;
int y = 50 + (i / 7) * 50;
this.gameButtons[i].Location = new System.Drawing.Point(x, y);
this.gameButtons[i].Name = "btn" + (index + 1);
this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
this.gameButtons[i].TabIndex = i;
//this.gameButtons[i].Text = Convert.ToString(index);
this.gameButtons[i].UseVisualStyleBackColor = true;
this.gameButtons[i].Visible = true;
gameButtons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
this.Controls.Add(gameButtons[i]);
}
}
private void buttonHasBeenPressed(object sender, int i)
{
if (((Button)sender).BackColor == Color.BlanchedAlmond)
{
if (blue == true)
{
((Button)sender).BackColor = Color.Red;
}
else
{
((Button)sender).BackColor = Color.Blue;
}
blue = !blue;
}
}
private void fourInARow(int a, int b, int c,int d)
{
if (gameButtons[a].BackColor == gameButtons[b].BackColor && gameButtons[a].BackColor == gameButtons[c].BackColor && gameButtons[a].BackColor==gameButtons[d].BackColor)
{
if (gameButtons[a].BackColor == Color.Blue)
{
MessageBox.Show("the winner is player 1");
}
else
{
MessageBox.Show("the winner is player 2");
}
}
}
}
Why do you use Index?
int index = I;
will stay at "0" - because its an initializer and only called once in for-loop.
But it makes no sense for me at all to have an index var.
I had been experimenting on writing a code to generate images inside a FlowLayoutPanel.
This is what i had done so far, when i click on a button for the first time (by using a checkboxes - read in number of images to open), it will generate the images, when i click on the button on second try, it will not update the flowlayoutpanel.
Even though i tried to remove the controls inside the FlowLayoutPanel, it still doesn't show the second try of the images.
This is the code snippet of the method:
FlowLayoutPanel fwPanel = null;
private void btnOpenFile_Click(object sender, EventArgs e)
{
//if there is content inside the flowpanel, dump it
if (fwPanel != null)
{
listOfFile.Clear();
}
//create a new FLP
fwPanel = new FlowLayoutPanel();
int panelWidth = width * 4 + 50;
int panelHeight = height * 4 + 50;
fwPanel.Size = new Size(panelWidth, panelHeight);
fwPanel.Location = new Point(0, 0);
this.Controls.Add(fwPanel);
//each checked item would be stored into an arraylist
foreach(object itemChecked in clbFile.CheckedItems)
{
listOfFile.Add((clbFile.Items.IndexOf(itemChecked)+1).ToString());
}
int noOfCheckedFile = listOfFile.Count;
PictureBox[] listOfPicture = new PictureBox[noOfCheckedFile];
int positionX = 0, positionY = 0;
int maxPaddingX = (width * MATRIX_SIZE) - 1;
int maxPaddingY = (height * MATRIX_SIZE) - 1;
//dynamically create images.
for (int i = 0; i < noOfCheckedFile; i++)
{
listOfPicture[i] = new PictureBox();
listOfPicture[i].Image = resizeImage((Image)show_picture(Convert.ToInt32(listOfFile[i])), new Size(width, height));
listOfPicture[i].Size = new Size(width, height);
if (positionX > maxPaddingX)
{
positionX = 0;
positionY += height;
}
if (positionY > maxPaddingY)
{
positionY = 0;
}
listOfPicture[i].Location = new Point(positionX,positionY);
listOfPicture[i].Visible = true;
fwPanel.Controls.Add(listOfPicture[i]);
positionX += width;
}
}
show_picture is a method that takes in and integer and returns a bitmap image.
listOfFile is to trace which file to return.
listOfPicture is to store each images.
i tried replacing this lines
//if there is content inside the flowpanel, dump it
if (fwPanel != null)
{
listOfFile.Clear();
}
i have added this line into it, when i do a second click, everything just gone missing, but this is not what i want, because it does not re-populating the FlowLayoutPanel.
if (fwPanel != null)
{
fwPanel.SuspendLayout();
if (fwPanel.Controls.Count > 0)
{
for (int i = (fwPanel.Controls.Count - 1); i >= 0; i--)
{
Control c = fwPanel.Controls[i];
c.Dispose();
}
GC.Collect();
}
fwPanel.ResumeLayout();
listOfFile.Clear();
}
I also tried this, but on second click, nothing will happen.
if (fwPanel != null)
{
List<Control> listControls = fwPanel.Controls.Cast<Control>().ToList();
foreach (Control control in listControls)
{
fwPanel.Controls.Remove(control);
control.Dispose();
}
listOfFile.Clear();
}
I wonder if i miss out anything, can someone enlighten me on what did i miss out ? Or guide me for the best practice of doing this.
as Suggested, i shifted the creation outside (credit to Sinatr for spotting it)
FlowLayoutPanel fwPanel = new FlowLayoutPanel();
private void createFLP()
{
int panelWidth = width * 4 + 50;
int panelHeight = height * 4 + 50;
fwPanel.Size = new Size(panelWidth, panelHeight);
fwPanel.Location = new Point(0, 0);
this.Controls.Add(fwPanel);
}
that solves the nothing happen part. Followed by using this to remove controls
if (fwPanel != null)
{
List<Control> listControls = fwPanel.Controls.Cast<Control>().ToList();
foreach (Control control in listControls)
{
fwPanel.Controls.Remove(control);
control.Dispose();
}
listOfFile.Clear();
}
and everything works like a charm, hope that this answer will be able to help others who are facing the same problem too.
I am trying add a page when horizontal or the x position is greater than a counter in order to keep a right side margin. When I run the code I end up in an infinate loop of hundreds of pages all displaying the same first page graphics. Thinking it might have to do with my lack of understanding HasMorePages. I could use some help. Thanks.
public static class PrintWave
{
public static void PrintPreWave()
{
PrintDocument pd = new PrintDocument();
if (WaveTools.MySettings == null)
{
pd.DefaultPageSettings.Landscape = true;
}
else
{
pd.DefaultPageSettings = WaveTools.MySettings;
}
pd.OriginAtMargins = true;
pd.PrintPage += new PrintPageEventHandler(OnPrintPage);
PrintDialog dlg = new PrintDialog();
PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
printPreviewDlg.Document = pd;
Form p = (Form)printPreviewDlg;
p.WindowState = FormWindowState.Maximized;
printPreviewDlg.ShowDialog();
}
private static void OnPrintPage(object sender, PrintPageEventArgs e)
{
string MyTag = string.Empty;
MyTag = WaveActions.ActiveId;
Wave MyWave = WaveHolder.FindWave(MyTag);
int MyCount = 0;
int xOffset = e.MarginBounds.Location.X;
int yOffset = e.MarginBounds.Location.Y;
if (MyWave != null)
{
Graphics g = e.Graphics;
g.SetClip(e.PageBounds);
Pen MyPen = new Pen(WaveTools.WaveColor, WaveTools.PenWidth);
float dx = (float)e.PageBounds.Width / MyWave.NumSamples;
float dy = (float)e.PageBounds.Height / 255;
if (MyWave.Normal == false)
{
g.ScaleTransform(dx, dy);
}
for (int i = 0; i < MyWave.NumSamples - 1; i++)
{
g.DrawLine(MyPen, i, MyWave.Data[i], i + 1, MyWave.Data[i + 1]);
MyCount = MyCount + 1;
if (MyCount > e.MarginBounds.Width)
{
e.HasMorePages = true;
MyCount = 0;
return;
}
else
{
e.HasMorePages = false;
return;
}
}
}
}
}
}
for (int i = 0; i < MyWave.NumSamples - 1; i++)
That's the core problem statement, you start at 0 every time PrintPage gets called. You need to resume where you left off on the previous page. Make the i variable a field of your class instead of a local variable. Implement the BeginPrint event to set it to zero.
The else clause inside the loop need to be deleted.