I am developing a game in C# .But it has some infinite loop that prevents form from being loaded. I have tried many solutions available on internet, But that doesn't seems to work.
My problem is :"How to load the form before execution of while loop."?
My Program.cs Source
namespace SumSwamp
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var window = new Form1();
window.Show();
}
}
}
Form1.cs :
namespace SumSwamp
{
public partial class Form1 : Form
{
public static int DieLargeNum = 0;
public static int DieSmallNum = 0;
public static int DieOperator = 0;
public static int DieTotal = 0;
public static int TotalSpaces = 42;
public static int CompSum = 0;
public static int PlayerSum = 0;
public static Boolean PlayersRoll = true;
public static Boolean WaitForRoll = true;
public static int Turn = 0;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(this.Form1_Load);
while(Turn == 0) //INFINITE LOOP
{
if (WaitForRoll==false)
{
DieTotal=DieLargeNum;
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
if (DieTotal>DieLargeNum)
{
Turn = 1;
labelStatus.Text = "Player 1's Turn";
WaitForRoll=true;
}
else
{
Turn = 2;
labelStatus.Text = "Player 2's Turn";
WaitForRoll = false;
}
}
}
while ((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces))//INFINITE LOOP
{
while (Turn == 1)
{
if (WaitForRoll == false)
{
if (DieOperator == 1)
{
DieTotal = DieLargeNum + DieSmallNum;
}
else
{
if (DieLargeNum > DieSmallNum)
{
DieTotal = DieLargeNum - DieSmallNum;
}
else
{
DieTotal = DieSmallNum - DieLargeNum;
}
}
PlayerSum = PlayerSum + DieTotal;
Turn = 2;
PlayersRoll = false;
labelStatus.Text = "Player 2's Turn";
}
}
while (Turn == 2)
{
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
Random rnd2 = new Random();
DieSmallNum = rnd2.Next(1, 7);
Random rnd3 = new Random();
DieOperator = rnd3.Next(1, 3);
labelDieLargeNum.Text = DieLargeNum.ToString();
labelDieSmallNum.Text = DieSmallNum.ToString();
if (DieOperator == 1)
{
labelDieOperator.Text = "+";
}
else
{
labelDieOperator.Text = "-";
}
if (DieOperator == 1)
{
DieTotal = DieLargeNum + DieSmallNum;
}
else
{
if (DieLargeNum > DieSmallNum)
{
DieTotal = DieLargeNum - DieSmallNum;
}
else
{
DieTotal = DieSmallNum - DieLargeNum;
}
}
CompSum = CompSum + DieTotal;
Turn = 1;
PlayersRoll = true;
labelStatus.Text = "Player 1's Turn";
}
}
if (CompSum>=TotalSpaces)
{
labelResult.Text = "CPU Player has won!";
}
else
{
labelResult.Text = "You win!";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonRoll_Click(object sender, EventArgs e)
{
if (PlayersRoll == true)
{
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
Random rnd2 = new Random();
DieSmallNum = rnd2.Next(1, 7);
Random rnd3 = new Random();
DieOperator = rnd3.Next(1, 3);
WaitForRoll = false;
labelDieLargeNum.Text = DieLargeNum.ToString();
labelDieSmallNum.Text = DieSmallNum.ToString();
if(DieOperator == 1)
{
labelDieOperator.Text = "+";
}
else
{
labelDieOperator.Text = "-";
}
}
}
}
}
If you put your infinite loop in the Form.Enter() event, the form will be loaded first and then run your loop. But the UI will be unresponsive if you're really in an infinite loop.
Usually UI games are driven by user interaction with controls. So, instead of an infinite loop where you have "WaitForRoll", you just have a button that says "Roll", and when they click it you run your code for that particular event (of rolling the dice).
If you do have to run a loop while the user isn't interacting with controls, it should be done in a separate thread, like a BackgroundWorker or Task.
Related
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 am currently working on my thesis project, this is an application that writes tablature by ASIO drivers. In short, write what you play. I'm new in all regards Naudio and I'm having poblemas to transform sound into FFT. I am capturing the sound with a device called "GuitarLink" which runs through ASIO4ALL.
So I need to compare frequencies for the chord in real time.
Currently, the program gives me two values, X and Y.
(I am using "SampleAggregator" Class and AsioOut)
MAIN
private SampleAggregator sampleAggregator = new(fftLength);
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Tick += new EventHandler(SoClose);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
dispatcherTimer.Start();
}
void SoClose(object sender, EventArgs e)
{
try
{
if (PBass)
{
sampleAggregator.PerformFFT = true;
sampleAggregator.FftCalculated += new EventHandler<FftEventArgs>(FftCalculated);
AsioOut asioOut = new();
BufferedWaveProvider wavprov = new(new WaveFormat(48000, 1));
asioOut.AudioAvailable += new EventHandler<AsioAudioAvailableEventArgs>(asio_DataAvailable);
asioOut.InitRecordAndPlayback(wavprov, 1, 25);
asioOut.Play();
I1E.Text = frecuencia.ToString();
}
}
catch
{
MessageBox.Show("Error de bajo presupuesto", "Obviamente algo anda mal");
}
}
private void FftCalculated(object sender, FftEventArgs e)
{
for (int i = 0; i < e.Result.Length; ++i)
{
A = e.Result[i].X;
B = e.Result[i].Y;
frecuencia = B;
Debug.WriteLine($"FFT: X={e.Result[i].X} Y={e.Result[i].Y}");
}
}
void asio_DataAvailable(object sender, AsioAudioAvailableEventArgs e)
{
byte[] buf = new byte[e.SamplesPerBuffer * 4];
for (int i = 0; i < e.InputBuffers.Length; i++)
{
Marshal.Copy(e.InputBuffers[i], buf, 0, e.SamplesPerBuffer * 4);
Marshal.Copy(buf, 0, e.OutputBuffers[i], e.SamplesPerBuffer * 4);
}
for (int i = 0; i < buf.Length; i = i + 4)
{
float sample = Convert.ToSingle(buf[i] + buf[i + 1] + buf[i + 2] + buf[i + 3]);
sampleAggregator.Add(sample);
}
e.WrittenToOutputBuffers = true;
}
SampleAggregator class
public class SampleAggregator
{
// FFT
public event EventHandler<FftEventArgs> FftCalculated;
public bool PerformFFT { get; set; }
// This Complex is NAudio's own!
private Complex[] fftBuffer;
private FftEventArgs fftArgs;
private int fftPos;
private int fftLength;
private int m;
public SampleAggregator(int fftLength)
{
if (!IsPowerOfTwo(fftLength))
throw new ArgumentException("FFT Length must be a power of two");
this.m = (int)Math.Log(fftLength, 2.0);
this.fftLength = fftLength;
this.fftBuffer = new Complex[fftLength];
this.fftArgs = new FftEventArgs(fftBuffer);
}
public void Add(float value)
{
if (PerformFFT && FftCalculated != null)
{
fftBuffer[fftPos].X = (float)(value * FastFourierTransform.HammingWindow(fftPos, fftLength));
fftBuffer[fftPos].Y = 0; // This is always zero with audio.
fftPos++;
if (fftPos >= fftLength)
{
fftPos = 0;
FastFourierTransform.FFT(true, m, fftBuffer);
FftCalculated(this, fftArgs);
}
}
}
static bool IsPowerOfTwo(int x) => (x & (x - 1)) == 0;
}
public class FftEventArgs : EventArgs
{
public Complex[] Result { get; private set; }
public string resultado = "";
[DebuggerStepThrough]
public FftEventArgs(Complex[] result) => Result = result;
void FftCalculated(object sender, FftEventArgs e)
{
}
}
Well the problem is that when I play a note, the values that are delivered are not affected.
Im using WinForms. In my Form i have a picturebox and a next button. I use this picturebox to display tiff images and i use the next button to navigate to the next page. The tiff documents are multipage images. The document I'm trying to view has a horizontal images and a vertical images like the example below. If its horizontal i want to size it (1100, 800), but if its vertical i want to size it (800, 1100). How do i do this? currently this is what i have but its not a good solution.
System.Drawing.Image img = System.Drawing.Image.FromFile(path_lbl.Text);
if (img.Height > img.Width)
{
pictureBox1.Width = 800;
pictureBox1.Height = 1300;
}
else
{
pictureBox1.Width = 1300;
pictureBox1.Height = 800;
}
I currently use this approach but this doesn't work because if the first image is vertical the if-statement will always execute the first condition pictureBox1.size(1300 , 800); With this method, if the next image is horizontal the condition will not ever re-size it horizontally.
Example Tiff image
http://www.filedropper.com/verticalandhorizontal
Quick Test Code
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace Demo
{
class TestForm : Form
{
public TestForm()
{
var panel = new Panel { Dock = DockStyle.Top, BorderStyle = BorderStyle.FixedSingle };
openButton = new Button { Text = "Open", Top = 8, Left = 16 };
prevButton = new Button { Text = "Prev", Top = 8, Left = 16 + openButton.Right };
nextButton = new Button { Text = "Next", Top = 8, Left = 16 + prevButton.Right };
path_lbl = new Label { Text = "", Top = 12, Left = 16 + nextButton.Right };
panel.Height = 16 + openButton.Height;
panel.Controls.AddRange(new Control[] { openButton, prevButton, nextButton, path_lbl });
pageViewer = new PictureBox { Dock = DockStyle.Fill, SizeMode = PictureBoxSizeMode.Zoom };
ClientSize = new Size(850, 1100 + panel.Height);
Controls.AddRange(new Control[] { panel, pageViewer });
openButton.Click += OnOpenButtonClick;
prevButton.Click += OnPrevButtonClick;
nextButton.Click += OnNextButtonClick;
Disposed += OnFormDisposed;
UpdatePageInfo();
}
private Button openButton;
private Button prevButton;
private Button nextButton;
private PictureBox pageViewer;
private PageBuffer pageData;
private int currentPage;
private Size pageSize;
public string path;
private Label path_lbl;
private void OnOpenButtonClick(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog())
{
if (dialog.ShowDialog(this) == DialogResult.OK)
Open(dialog.FileName);
path = dialog.FileName;
}
}
private void OnPrevButtonClick(object sender, EventArgs e)
{
SelectPage(currentPage - 1);
}
private void OnNextButtonClick(object sender, EventArgs e)
{
//var data = PageBuffer.Open(path,Size= new Size(850,1150));
SelectPage(currentPage + 1);
//Debug.WriteLine("Current Size: 1300, 800");
}
private void OnFormDisposed(object sender, EventArgs e)
{
if (pageData != null)
pageData.Dispose();
}
private void Open(string path)
{
var data = PageBuffer.Open(path, new Size(1500, 1500));
pageViewer.Image = null;
if (pageData != null)
pageData.Dispose();
pageData = data;
SelectPage(0);
}
private void SelectPage(int index)
{
pageViewer.Image = pageData.GetPage(index);
currentPage = index;
UpdatePageInfo();
}
private void UpdatePageInfo()
{
prevButton.Enabled = pageData != null && currentPage > 0;
nextButton.Enabled = pageData != null && currentPage < pageData.PageCount - 1;
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());
}
}
class PageBuffer : IDisposable
{
public const int DefaultCacheSize = 12; //This is how much images it will have in memory
public static PageBuffer Open(string path, Size maxSize, int cacheSize = DefaultCacheSize)
{
return new PageBuffer(File.OpenRead(path), maxSize, cacheSize);
}
private PageBuffer(Stream stream, Size maxSize, int cacheSize)
{
this.stream = stream;
source = Image.FromStream(stream);
pageCount = source.GetFrameCount(FrameDimension.Page);
if (pageCount < 2) return;
pageCache = new Image[Math.Min(pageCount, Math.Max(cacheSize, 5))];
pageSize = source.Size;
if (!maxSize.IsEmpty)
{
float scale = Math.Min((float)maxSize.Width / pageSize.Width, (float)maxSize.Height / pageSize.Height);
pageSize = new Size((int)(pageSize.Width * scale), (int)(pageSize.Height * scale));
}
var worker = new Thread(LoadPages) { IsBackground = true };
worker.Start();
}
private void LoadPages()
{
while (true)
{
lock (syncLock)
{
if (disposed) return;
int index = Array.FindIndex(pageCache, 0, pageCacheSize, p => p == null);
if (index < 0)
Monitor.Wait(syncLock);
else
pageCache[index] = LoadPage(pageCacheStart + index);
}
}
}
private Image LoadPage(int index)
{
source.SelectActiveFrame(FrameDimension.Page, index);
return new Bitmap(source, pageSize);
}
private Stream stream;
private Image source;
private int pageCount;
private Image[] pageCache;
private int pageCacheStart, pageCacheSize;
private object syncLock = new object();
private bool disposed;
private Size pageSize;
public Image Source { get { return source; } }
public int PageCount { get { return pageCount; } }
public Image GetPage(int index)
{
if (disposed) throw new ObjectDisposedException(GetType().Name);
if (PageCount < 2) return Source;
lock (syncLock)
{
AdjustPageCache(index);
int cacheIndex = index - pageCacheStart;
var image = pageCache[cacheIndex];
if (image == null)
image = pageCache[cacheIndex] = LoadPage(index);
return image;
}
}
private void AdjustPageCache(int pageIndex)
{
int start, end;
if ((start = pageIndex - pageCache.Length / 2) <= 0)
end = (start = 0) + pageCache.Length;
else if ((end = start + pageCache.Length) >= PageCount)
start = (end = PageCount) - pageCache.Length;
if (start < pageCacheStart)
{
int shift = pageCacheStart - start;
if (shift >= pageCacheSize)
ClearPageCache(0, pageCacheSize);
else
{
ClearPageCache(pageCacheSize - shift, pageCacheSize);
for (int j = pageCacheSize - 1, i = j - shift; i >= 0; j--, i--)
Exchange(ref pageCache[i], ref pageCache[j]);
}
}
else if (start > pageCacheStart)
{
int shift = start - pageCacheStart;
if (shift >= pageCacheSize)
ClearPageCache(0, pageCacheSize);
else
{
ClearPageCache(0, shift);
for (int j = 0, i = shift; i < pageCacheSize; j++, i++)
Exchange(ref pageCache[i], ref pageCache[j]);
}
}
if (pageCacheStart != start || pageCacheStart + pageCacheSize != end)
{
pageCacheStart = start;
pageCacheSize = end - start;
Monitor.Pulse(syncLock);
}
}
void ClearPageCache(int start, int end)
{
for (int i = start; i < end; i++)
Dispose(ref pageCache[i]);
}
static void Dispose<T>(ref T target) where T : class, IDisposable
{
var value = target;
if (value != null) value.Dispose();
target = null;
}
static void Exchange<T>(ref T a, ref T b) { var c = a; a = b; b = c; }
public void Dispose()
{
if (disposed) return;
lock (syncLock)
{
disposed = true;
if (pageCache != null)
{
ClearPageCache(0, pageCacheSize);
pageCache = null;
}
Dispose(ref source);
Dispose(ref stream);
if (pageCount > 2)
Monitor.Pulse(syncLock);
}
}
}
}
My friend's GameElements.cs seems to have become corrupted in some way. We're both studying in the same class, and he sent me his project and I can't open the file either. I can't troubleshoot his solution, as he is using XNA and I'm using MonoGame.
Sadly, he does not have any back-ups (this way he'll learn the hard way though) and neither one of us are familiar with neither Visual Studio nor programming at all, as we're just a couple months into the course.
The file is still 12kb, even though I can only select/copy blank spaces. I have no idea if it's possible to restore the code from it, there is obviously data in the file.
This is a link to download the whole solution, though the corrupt file in question is "GameElements.cs". We both would appreciate it greatly if someone was able to recover the code! http://www.filedropper.com/xnabus
Please see below for the code from GameElements.cs. Hope this helps :). You could use any .Net Disassembler to do this. I used ILSpy and decompiled your code from XNA bus.exe file.
Note that, sometimes there could be minor issues with names of classes or methods. So, please go through the code once completely to ensure this.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
namespace XNA_bus
{
internal static class GameElements
{
public enum State
{
Menu,
Levels,
Level1,
Level2,
Level3,
Run,
Highscore,
Quit
}
private static Meny meny;
private static Levels levels;
private static Player player;
private static List<Fiender> Fiende;
private static List<GuldMynt> guldMynt;
private static List<Powerup> SuperSkepp;
private static List<Powerup> PenetratingBullets;
private static Texture2D guldMyntSprite;
private static Texture2D SuperskeppSprite;
private static Texture2D PenetratingbulletsSprite;
private static Utskrifter printText;
private static Bakgrund bakgrund;
private static Boss1 boss1;
private static int boss1Liv = 3;
private static int playerLiv = 1;
public static GameElements.State currentState;
public static void Initialize()
{
GameElements.guldMynt = new List<GuldMynt>();
GameElements.SuperSkepp = new List<Powerup>();
GameElements.PenetratingBullets = new List<Powerup>();
}
public static void LoadContent(ContentManager content, GameWindow window)
{
GameElements.player = new Player(content.Load<Texture2D>("Images/player/Player"), 0f, 200f, 2.5f, 4.5f, content.Load<Texture2D>("Images/player/bullet"));
GameElements.bakgrund = new Bakgrund(content.Load<Texture2D>("Images/bakgrund"), window);
GameElements.boss1 = new Boss1(content.Load<Texture2D>("Images/Enemies/Boss1"), 700f, 360f);
GameElements.meny = new Meny(0);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Start"), 1, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Highscore"), 6, window);
GameElements.meny.AddItem(content.Load<Texture2D>("Images/Meny/Avsluta"), 7, window);
GameElements.levels = new Levels(1);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 1"), 2, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 2"), 3, window);
GameElements.levels.AddItem(content.Load<Texture2D>("Images/Meny/Level 3"), 4, window);
GameElements.Fiende = new List<Fiender>();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
GameElements.printText = new Utskrifter(content.Load<SpriteFont>("Font1"));
GameElements.guldMyntSprite = content.Load<Texture2D>("Images/Powerups/SpelMynt");
GameElements.SuperskeppSprite = content.Load<Texture2D>("Images/Powerups/PowerUp");
GameElements.PenetratingbulletsSprite = content.Load<Texture2D>("Images/Powerups/PowerUp2");
}
public static GameElements.State MenyUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.meny.Update(gameTime);
}
public static void MenyDraw(SpriteBatch spriteBatch)
{
GameElements.bakgrund.Draw(spriteBatch);
GameElements.meny.Draw(spriteBatch);
}
public static GameElements.State RunUpdate(ContentManager content, GameWindow window, GameTime gameTime)
{
GameElements.bakgrund.Update(window);
GameElements.player.Update(window, gameTime);
foreach (Fiender f in GameElements.Fiende.ToList<Fiender>())
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (f.CheckCollision(b))
{
f.Liv = false;
GameElements.player.poäng++;
if (!GameElements.player.PenetratingBullets)
{
GameElements.player.AntSkott.Remove(b);
}
else if (GameElements.player.PenetratingBullets)
{
if (gameTime.get_TotalGameTime().TotalSeconds > GameElements.player.PenetratingBulletsTime + 2.0)
{
GameElements.player.PenetratingBullets = false;
}
}
}
}
if (f.Liv)
{
if (f.CheckCollision(GameElements.player))
{
GameElements.playerLiv--;
GameElements.player.Liv = false;
}
f.Update(window);
}
else
{
GameElements.Fiende.Remove(f);
}
if (!f.FKoll)
{
GameElements.Fiende.Remove(f);
GameElements.playerLiv--;
}
}
if (GameElements.boss1.Liv)
{
foreach (Bullet b in GameElements.player.AntSkott.ToList<Bullet>())
{
if (GameElements.boss1.CheckCollision(b))
{
GameElements.player.AntSkott.Remove(b);
GameElements.boss1Liv--;
}
}
GameElements.boss1.Update(window);
}
if (GameElements.boss1Liv == 0)
{
GameElements.boss1.Liv = false;
}
GameElements.State result;
if (!GameElements.boss1.Liv)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
Random random = new Random();
int newMynt = random.Next(1, 200);
if (newMynt == 1)
{
int rndX = random.Next(0, window.get_ClientBounds().Width - GameElements.guldMyntSprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - GameElements.guldMyntSprite.get_Height());
GameElements.guldMynt.Add(new GuldMynt(GameElements.guldMyntSprite, (float)rndX, (float)rndY));
}
foreach (GuldMynt gc in GameElements.guldMynt.ToList<GuldMynt>())
{
if (gc.Liv)
{
gc.Update(gameTime);
if (gc.CheckCollision(GameElements.player))
{
GameElements.guldMynt.Remove(gc);
GameElements.player.Poäng++;
}
}
else
{
GameElements.guldMynt.Remove(gc);
}
}
Random rnd = new Random();
int newPowerup = rnd.Next(1, 300);
if (newPowerup == 1)
{
int rndX = rnd.Next(0, window.get_ClientBounds().Width - GameElements.SuperskeppSprite.get_Width());
int rndY = rnd.Next(0, window.get_ClientBounds().Height - GameElements.SuperskeppSprite.get_Height());
GameElements.SuperSkepp.Add(new Powerup(GameElements.SuperskeppSprite, (float)rndX, (float)rndY));
}
foreach (Powerup Power in GameElements.SuperSkepp.ToList<Powerup>())
{
if (Power.Liv)
{
Power.Update(gameTime);
if (Power.CheckCollision(GameElements.player))
{
GameElements.SuperSkepp.Remove(Power);
GameElements.player.SuperSkepp = true;
GameElements.player.SuperSkeppTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.SuperSkepp.Remove(Power);
}
}
Random rnd2 = new Random();
int NewPowerup = rnd2.Next(1, 300);
if (NewPowerup == 1)
{
int rndX = rnd2.Next(0, window.get_ClientBounds().Width - GameElements.PenetratingbulletsSprite.get_Width());
int rndY = rnd2.Next(0, window.get_ClientBounds().Height - GameElements.PenetratingbulletsSprite.get_Height());
GameElements.PenetratingBullets.Add(new Powerup(GameElements.PenetratingbulletsSprite, (float)rndX, (float)rndY));
}
foreach (Powerup P in GameElements.PenetratingBullets.ToList<Powerup>())
{
if (P.Liv)
{
P.Update(gameTime);
if (P.CheckCollision(GameElements.player))
{
GameElements.PenetratingBullets.Remove(P);
GameElements.player.PenetratingBullets = true;
GameElements.player.PenetratingBulletsTime = gameTime.get_TotalGameTime().TotalSeconds;
}
}
else
{
GameElements.PenetratingBullets.Remove(P);
}
}
if (!GameElements.player.Liv || GameElements.playerLiv == 0)
{
GameElements.Reset(window, content);
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Run;
}
}
return result;
}
public static void RunDraw(SpriteBatch spriteBatch)
{
GameElements.boss1.Draw(spriteBatch);
GameElements.bakgrund.Draw(spriteBatch);
GameElements.player.Draw(spriteBatch);
foreach (Fiender f in GameElements.Fiende)
{
f.Draw(spriteBatch);
}
foreach (GuldMynt gc in GameElements.guldMynt)
{
gc.Draw(spriteBatch);
}
foreach (Powerup Power in GameElements.SuperSkepp)
{
Power.Draw(spriteBatch);
}
foreach (Powerup p in GameElements.PenetratingBullets)
{
p.Draw(spriteBatch);
}
GameElements.printText.Print("Points:" + GameElements.player.poäng, spriteBatch, 0, 0);
GameElements.printText.Print("Boss Liv:" + GameElements.boss1Liv, spriteBatch, 680, 0);
GameElements.printText.Print("Liv:" + GameElements.playerLiv, spriteBatch, 0, 20);
}
public static GameElements.State HighScoreUpdate()
{
GameElements.State result;
if (Keyboard.GetState().IsKeyDown(27))
{
result = GameElements.State.Menu;
}
else
{
result = GameElements.State.Highscore;
}
return result;
}
public static void HighScoreDraw(SpriteBatch spriteBatch)
{
}
private static void Reset(GameWindow window, ContentManager content)
{
GameElements.boss1Liv = 3;
GameElements.playerLiv = 1;
GameElements.boss1.Liv = true;
GameElements.player.Reset(0f, 200f, 2.5f, 4.5f);
GameElements.Fiende.Clear();
Random random = new Random();
Texture2D tmpsprite = content.Load<Texture2D>("Images/Enemies/Predator");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp);
}
tmpsprite = content.Load<Texture2D>("Images/Enemies/mina");
for (int i = 0; i < 5; i++)
{
int rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
int rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
GameElements.Fiende.Add(temp2);
}
}
public static GameElements.State LevelsUpdate(GameTime gameTime)
{
return (GameElements.State)GameElements.levels.Update(gameTime);
}
public static void LevelsDraw(SpriteBatch spritebatch)
{
GameElements.bakgrund.Draw(spritebatch);
GameElements.levels.Draw(spritebatch);
}
}
}
I´m currently trying to add parallel downloads to my application but I don´t know how to handle the DownloadProgressChangedEvent to display the progress in multiple progressbars.
I´m using a datagridview with predefined rows for each file the user is able to download and each row has a cell with a progressbar in it.
The problem now is, that I don´t know how to update each progressbar individually, because right now, all selected progressbars are showing the same percentage and they´re just jumping between the progress of download1 & download2.
Here´s the code im using:
To start the downloads:
private void download_button_Click(object sender, EventArgs e)
{
start = DateTime.Now;
download_button.Enabled = false;
Rows = dataGridView1.Rows.Count;
Checked = 0;
CheckedCount = 0;
//count the selected rows
for (i = 0; i < Rows; i++)
{
Checked = Convert.ToInt32(dataGridView1.Rows[i].Cells["checkboxcol"].FormattedValue);
CheckedCount += Checked;
richTextBox3.Text = CheckedCount.ToString();
}
for (int z = 1; z < CheckedCount; z++)
{
_MultipleWebClients = new WebClient();
_MultipleWebClients.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
_MultipleWebClients.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
_MultipleWebClients.DownloadFileAsync(new Uri(_downloadUrlList[z].ToString()), #"F:\test" + z + ".mp4");
}
}
(I´m also unable to download more than two files simultaneously - the third download won´t start until the first two are finished)
DownloadProgressChangedEvent:
private void _DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
for (int c = 0; c < CheckedCount; c++)
{
dataGridView1.Rows[_downloadRowNrList[c]].Cells[3].Value = e.ProgressPercentage;
}
float size = ((e.TotalBytesToReceive / 1024) / 1024);
label1.Text = size.ToString();
double dn = (double)e.BytesReceived / 1024.0 / (DateTime.Now - start).TotalSeconds;
label2.Text = (dn.ToString("n") + " KB/s) " + e.ProgressPercentage);
}
The problem probably is, that all progressbars are using the same DownloadProgressChangedEvent, but I´m not sure how to create multiple of these events without knowing the needed number...
So i hope that someone is able to help me with this,
thanks in advance!
What you want to do is use the other DownloadFileAsync method:
http://msdn.microsoft.com/en-us/library/ms144197.aspx
The third parameter is a userToken which gets passed as part of the DownloadProgressChangedEventArgs (it's in the UserState property).
So, when you make the DownloadFileAsync call, pass in a unique token (an integer, or something else) that you can then associate with the progressBar that needs updating.
//(Snip)
//in download_button_Click, pass the row you are updating to the event.
for (int z = 1; z < CheckedCount; z++)
{
_MultipleWebClients = new WebClient();
_MultipleWebClients.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
_MultipleWebClients.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
_MultipleWebClients.DownloadFileAsync(new Uri(_downloadUrlList[z].ToString()), #"F:\test" + z + ".mp4", dataGridView1.Rows[z]);
}
}
private void _DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
var rowToUpdate = (DataGridViewRow)e.UserState;
RowToUpdate["ProgressBar"].Value = e.ProgressPercentage;
RowToUpdate["TextProgress"].Value = e.ProgressPercentage;
RowToUpdate["BytesToRecive"].Value = ((e.TotalBytesToReceive / 1024) / 1024).ToString();
double dn = (double)e.BytesReceived / 1024.0 / (DateTime.Now - start).TotalSeconds;
RowToUpdate["Speed"].Value = (dn.ToString("n") + " KB/s) " + e.ProgressPercentage);
}
Sounds like you need a progress bar for multi-parted progress:
public partial class ProgressBarEx : ProgressBar
{
private readonly Dictionary<Guid, double> _partsProgress =
new Dictionary<Guid, double>();
private readonly Dictionary<Guid, double> _partsSizes =
new Dictionary<Guid, double>();
private double _value;
private double _maximum;
public ProgressBarEx()
{
this.InitializeComponent();
}
public int Parts
{
get { return this._partsSizes.Count; }
}
public new int Minimum { get; private set; }
public new double Maximum
{
get { return this._maximum; }
private set
{
this._maximum = value;
base.Maximum = (int)value;
}
}
public new double Value
{
get { return this._value; }
private set
{
this._value = value;
base.Value = (int)value;
}
}
[Obsolete("Not useable in ProgressBarEx.")]
public new int Step
{
get { return 0; }
}
public Guid AddPart(double size)
{
if (size <= 0)
{
throw new ArgumentException("size");
}
var partId = Guid.NewGuid();
this.Maximum += size;
this._partsSizes.Add(partId, size);
this._partsProgress.Add(partId, 0);
return partId;
}
public bool RemovePart(Guid partId)
{
double size;
if (!this._partsSizes.TryGetValue(partId, out size))
{
return false;
}
this.Maximum -= size;
this._partsSizes.Remove(partId);
this.Value -= this._partsProgress[partId];
this._partsProgress.Remove(partId);
return true;
}
public bool ContainsPart(Guid partId)
{
return this._partsSizes.ContainsKey(partId);
}
public double GetProgress(Guid partId)
{
return this._partsProgress[partId];
}
public void SetProgress(Guid partId, double progress)
{
if (progress < 0 || this._partsSizes[partId] < progress)
{
throw new ArgumentOutOfRangeException("progress");
}
this.Value += progress - this._partsProgress[partId];
this._partsProgress[partId] = progress;
}
public void AddProgress(Guid partId, double progress)
{
this.SetProgress(partId, progress + this._partsProgress[partId]);
}
[Obsolete("Not useable in ProgressBarEx.")]
public new void PerformStep()
{
}
}
Example usage:
public Form1()
{
InitializeComponent();
var pbe = new ProgressBarEx {Location = new Point(100, 100)};
this.Controls.Add(pbe);
for (var i = 0; i < 4; i++)
{
var size = i * 10 + 30;
var partId = pbe.AddPart(size);
var pb = new ProgressBar
{
Maximum = size,
Location = new Point(100, i * 30 + 130)
};
this.Controls.Add(pb);
var timer = new Timer {Interval = 1000 + i * 100};
timer.Tick += (sender, args) =>
{
pb.Value += 5;
pbe.AddProgress(partId, 5);
if (pb.Value == pb.Maximum)
{
timer.Stop();
}
};
timer.Start();
}
}