private void RegButton_Click(object sender, EventArgs e) { regMessageTextBox.Text = ""; loginMessageTextBox.Text = ""; string username = usernameRegTextBox.Text; string password = passwordRegTextBox.Text; if (string.IsNullOrWhiteSpace(usernameRegTextBox.Text) || string.IsNullOrWhiteSpace(passwordRegTextBox.Text)) { regMessageTextBox.Text = "Fältet för användarnamn eller lösenord är tomt."; } else { Player play = controller.FindPlayer(username, password); if (play != null) { regMessageTextBox.Text = "Användarnamn är upptaget."; } else { controller.AddPlayer(username, password); controller.UpdateNewPlayerHighscore(username, 1, 1); Plays pl = controller.FindPlayerInTblPlays(username); Plays plays = controller.FindPlayerPoints(pl); currentPlayerPoints = plays.points; currentPlayerUsername = username; this.Hide(); new View.LoggedInForm(username, currentPlayerPoints).Show(); } } }
public void Load(string file) { if (File.Exists(file)) { XDocument doc = XDocument.Load(file); XElement elemPresentation = doc.Element("Presentation"); Plays.Clear(); if (elemPresentation != null) { Name = elemPresentation.Attribute("Name").Value; XElement elemFiles = elemPresentation.Element("Files"); if (elemFiles != null) { foreach (XElement elem in elemFiles.Elements("File")) { PresentationPlay play = new PresentationPlay(); play.ReadXML(elem); Plays.Add(play); } } } } }
public async Task <IActionResult> Edit(int id, [Bind("InstrumentID,MusicianID")] Plays plays) { if (id != plays.InstrumentID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(plays); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PlaysExists(plays.InstrumentID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["InstrumentID"] = new SelectList(_context.Instruments, "InstrumentID", "Name", plays.InstrumentID); ViewData["MusicianID"] = new SelectList(_context.Musicians, "MusicianID", "FirstName", plays.MusicianID); return(View(plays)); }
public bool PlayDrawCard(Player player) { if (!CanDraw(player)) { return(false); } var cardDrew = DrawCard(); AddCardToHand(player, cardDrew); Plays.Add(new Play() { CardNumber = cardDrew, PlayedLocationNumber = -1, Draw = true, PlayerHand = player.Hand, PlayerNumber = player.PlayerNumber, TurnNumber = TurnNumber }); CheckForAllDeadCards(); NextTurn(); return(true); }
private void UpdatePlays(string[] selectedInstruments, Musician musicianToUpdate) { if (selectedInstruments == null) { musicianToUpdate.Plays = new List <Plays>(); return; } var selectedInstrumentsHS = new HashSet <string>(selectedInstruments); var playsHS = new HashSet <int>(musicianToUpdate.Plays.Select(i => i.InstrumentID)); foreach (var ins in _context.Instruments) { if (selectedInstrumentsHS.Contains(ins.ID.ToString())) { if (!playsHS.Contains(ins.ID)) { musicianToUpdate.Plays.Add(new Plays { MusicianID = musicianToUpdate.ID, InstrumentID = ins.ID }); } } else { if (playsHS.Contains(ins.ID)) { Plays playsToRemove = musicianToUpdate.Plays.SingleOrDefault(i => i.InstrumentID == ins.ID); _context.Remove(playsToRemove); } } } }
private void LoginButton_Click(object sender, EventArgs e) { regMessageTextBox.Text = ""; loginMessageTextBox.Text = ""; string username = usernameTextBox.Text; string password = passwordLoginTextBox.Text; if (string.IsNullOrWhiteSpace(usernameTextBox.Text) || string.IsNullOrWhiteSpace(passwordLoginTextBox.Text)) { loginMessageTextBox.Text = "Fältet för användarnamn eller lösenord är tomt."; } else { currentUser = controller.FindPlayer(username, password); if (currentUser == null) { loginMessageTextBox.Text = "Användare kan inte hittas."; } else { currentUser = controller.FindPlayer(username, password); currentPlayerUsername = currentUser.Username; Plays pl = controller.FindPlayerInTblPlays(username); Plays plays = controller.FindPlayerPoints(pl); currentPlayerPoints = plays.points; this.Hide(); new View.LoggedInForm(currentPlayerUsername, currentPlayerPoints).Show(); } } }
public void AddPlay(Play play) { if (Plays == null) { Plays = new List <Play>(); } Plays.Add(play); }
internal string PrintStatement(Invoice invoice, Plays plays) { decimal totalAmount = 0; decimal volumeCredits = 0; var result = new StringBuilder(); result.AppendLine($"Statement for {invoice.Customer}"); foreach (var perf in invoice.Performances) { var play = plays[perf.PlayId]; decimal thisAmount = 0; switch (play.Type) { case "tragedy": { thisAmount = 40000; if (perf.Audience > 30) { thisAmount += 1000 * (perf.Audience - 30); } break; } case "comedy": { thisAmount = 30000; if (perf.Audience > 20) { thisAmount += 10000 + 500 * (perf.Audience - 20); } thisAmount += 300 * perf.Audience; break; } default: { throw new Exception($"Unknown type: {play.Type}"); } } // add volume credits volumeCredits += Math.Max(perf.Audience - 30, 0); // add extra credit for every ten comedy attendees if ("comedy" == play.Type) { volumeCredits += Math.Floor(perf.Audience / 5m); } // print line for this order result.AppendLine($" {play.Name}: {thisAmount / 100:C} ({perf.Audience} seats)"); totalAmount += thisAmount; } result.AppendLine($"Amount owed is {totalAmount / 100:C}"); result.AppendLine($"You earned {volumeCredits} credits"); return(result.ToString()); }
private void backToStartButton_Click(object sender, EventArgs e) { Plays pl = controller.FindPlayerInTblPlays(tempUsername); Plays plays = controller.FindPlayerPoints(pl); highscore = plays.points; this.Hide(); new LoggedInForm(tempUsername, highscore).Show(); }
private void QuitGameButton_Click(object sender, EventArgs e) { this.Hide(); Plays pl = controller.FindPlayerInTblPlays(currentPlayerUsername); Plays plays = controller.FindPlayerPoints(pl); highschore = plays.points; new LoggedInForm(currentPlayerUsername, highschore).Show(); }
public void UpdatePlayerHighscore(int points, Plays currentPlayer) { using (SqlConnection connection = Connector.GetConnection()) { string query = string.Format("UPDATE Plays SET points = @add WHERE USERNAME = '******'", currentPlayer.Username); SqlCommand cmd = new SqlCommand(query, connection); cmd.Parameters.AddWithValue("@add", points); cmd.ExecuteNonQuery(); } }
private void btnDelete_Click(object sender, RoutedEventArgs e) { if (dgEvents.SelectedIndex == -1) { return; } var selectedPlay = dgEvents.SelectedItem as PlayByPlayEntry; Plays.Remove(selectedPlay); }
public Presentation(string name, List <PresentationPlay> pPlays) { Name = name; Plays.Clear(); foreach (PresentationPlay pPlay in pPlays) { Plays.Add(pPlay); } }
public async Task <IActionResult> Create([Bind("InstrumentID,MusicianID")] Plays plays) { if (ModelState.IsValid) { _context.Add(plays); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["InstrumentID"] = new SelectList(_context.Instruments, "InstrumentID", "Name", plays.InstrumentID); ViewData["MusicianID"] = new SelectList(_context.Musicians, "MusicianID", "FirstName", plays.MusicianID); return(View(plays)); }
public static List <Plays> GetPlays() { DataTable dt = WebSetDAL.BaseProvider.GetPlays(); List <Plays> list = new List <Plays>(); foreach (DataRow dr in dt.Rows) { Plays model = new Plays(); model.FillData(dr); list.Add(model); } return(list); }
public Plays GetPlay(IEnumerable <Card> hand, Card dealerShowing, Plays possiblePlays) { BlackJackScore score = new BlackJackScore(hand); BlackJackScore dealerScore = new BlackJackScore(dealerShowing); int index = GetGeneNumber(score, dealerScore); Plays willingPlays = (Plays)((byte)possiblePlays & Genes[index] & USABLE_GENES_MASK); if (willingPlays.HasFlag(Plays.Hit)) { return(Plays.Hit); } return(Plays.Stand); }
private void EndGame() { Game.End = DateTime.Now; CheckOutPlayers(); Game.Plays = Plays; Game.PlayerGames = PlayerGames; Game.ScoreB = Plays.Where(p => p.TeamB && p.MadeFG).Sum(p => p.Points); Game.ScoreA = Plays.Where(p => !p.TeamB && p.MadeFG).Sum(p => p.Points); _dataAccess.AddGameAsync(Game); _dataAccess.AddPlaysAsync(Plays); _dataAccess.AddPlayerGames(PlayerGames); _dataAccess.SaveChangesAsync(); GameNotStarted = true; GameStarted = false; }
private void CheckOutPlayers() { foreach (Player player in TeamAOnCourt) { _playFactory.NewPlay(player, false); _playFactory.ChoosePlayType(PlayType.CheckOut); Plays.Add(_playFactory.GetPlays().First()); _playFactory.Clear(); } foreach (Player player in TeamBOnCourt) { _playFactory.NewPlay(player, true); _playFactory.ChoosePlayType(PlayType.CheckOut); Plays.Add(_playFactory.GetPlays().First()); _playFactory.Clear(); } }
public Plays FindPlayerPoints(Plays currentPlayer) //Returnera en spelares poäng { using (SqlConnection connection = Connector.GetConnection()) { string query = string.Format("SELECT points FROM Plays WHERE username = '******'", currentPlayer.Username); SqlCommand cmd = new SqlCommand(query, connection); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Plays playerPoints = new Plays(); playerPoints.points = Convert.ToInt32(dr["points"]); return(playerPoints); } return(null); } }
public Plays FindPlayerInTblPlays(string Username) { using (SqlConnection connection = Connector.GetConnection()) { string query = string.Format("SELECT username FROM Plays WHERE username = '******'", Username); SqlCommand cmd = new SqlCommand(query, connection); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Plays player = new Plays(); player.Username = dr["username"] as string; return(player); } return(null); } }
//Se actualizan los archivos de colección y de las partidas private void BtnActualizar_Click(object sender, EventArgs e) { if (txtUsuario.Text.Equals("")) { MessageBox.Show("Falta ingresar un usuario"); txtUsuario.Focus(); } else { Colecccion co = new Colecccion(); co.actualizarArchivoColeccion(txtUsuario.Text, directorioCacheJuego + "colecciones/"); Plays pl = new Plays(); pl.actualizarArchivosPlays(directorioCacheUsuarios + "/" + txtUsuario.Text + "/", co.documentoJuego, txtUsuario.Text); txtUsuario.Focus(); txtUsuario.Text = ""; } }
public async Task <IActionResult> Create([Bind("ID,FirstName,MiddleName,LastName,Phone,DOB,SIN,InstrumentID")] Musician musician, string[] selectedInstruments) { try { if (selectedInstruments != null) { musician.Plays = new List <Plays>(); foreach (var ins in selectedInstruments) { var insToAdd = new Plays { MusicianID = musician.ID, InstrumentID = int.Parse(ins) }; musician.Plays.Add(insToAdd); } } if (ModelState.IsValid) { _context.Add(musician); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (RetryLimitExceededException) { ModelState.AddModelError("", "Unable to save changes after multiple attempts. Try again,"); } catch (DbUpdateException dex) { if (dex.InnerException.Message.Contains("IX_Musicians_SIN")) { ModelState.AddModelError("", "Unable to save changes. Remember, you cannot have duplicate SIN numbers."); } else { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } } PopulateDropDownLists(musician); return(View(musician)); }
public void AddPlay(Play play) { Plays.Add(play); if (!Scores.ContainsKey(play.Alley)) { Scores.Add(play.Alley, new Painel(play.Alley, play.Date)); } var score = GetPainel(play.Alley); if (!score.Players.Any(p => p.Name == play.Name)) { score.Players.Add(new Player() { Name = play.Name }); } score.LastGame = play.Date; score.Players.AddPlay(play); }
public async Task <IActionResult> Create([Bind("ID,StageName,FName,MName,LName,Phone,DOB,SIN,InstrumentID")] Musician musician, string[] selectedInstruments) { try { if (selectedInstruments != null) { musician.Plays = new List <Plays>(); foreach (var inst in selectedInstruments) { var instToAdd = new Plays { MusicianID = musician.ID, InstrumentID = int.Parse(inst) }; musician.Plays.Add(instToAdd); } } if (ModelState.IsValid) { _context.Add(musician); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (DbUpdateException dex) { if (dex.InnerException.Message.Contains("IX_Musicians_SIN")) { ModelState.AddModelError("SIN", "Please ensure SIN numbers are unique"); } else { ModelState.AddModelError("", "Unable to save changes. Please try again later."); } } PopulateAssignedInstrumentData(musician); PopulateInstrumentDropdown(musician); return(View(musician)); }
private void Timer_Tick(object sender, EventArgs e) { if (timeLeft > 0) { timeLeft--; tickingTimeLabel.Text = timeLeft.ToString(); } if (timeLeft == 0) { timer.Stop(); Plays pl = controller.FindPlayerInTblPlays(currentPlayerUsername); Plays plays = controller.FindPlayerPoints(pl); highschore = plays.points; this.Hide(); new ScoreForm(currentSum, currentPlayerUsername, highschore).Show(); } }
public bool PlayLocation(Player player, int location, int card) { if (!CanPlay(location, card, player)) { return(false); } RemoveCardFromHand(player, card); FillLocation(player, location); if (location.Equals(HighestPlayable)) { DetermineHighestPlayable(); } Plays.Add(new Play() { CardNumber = card, PlayedLocationNumber = location, Draw = false, PlayerHand = player.Hand, PlayerNumber = player.PlayerNumber, TurnNumber = TurnNumber }); if (CheckWinCondition(location, player)) { Won = true; WinningPlayer = CurrentPlayer; } else { CheckForAllDeadCards(); } NextTurn(); return(true); }
public void LoadPlyxAllItemsIihfV2() { var play = Plays.LoadPlyxFile(@"testfiles\ALL_ITEMS_IIHF_V2.PLYX"); Assert.NotNull(play); Assert.AreEqual("ALL_ITEMS", play.Name); Assert.AreEqual(26, play.Objects.Count); Assert.AreEqual(RinkType.IIHF, play.RinkType); Assert.AreEqual(2, play.Version); var testObject = play.Objects.FirstOrDefault(o => o.Item.Number == 10); Assert.NotNull(testObject); Assert.AreEqual(Color.Red, testObject.Color); Assert.AreEqual(4, testObject.Line?.LineWidth); Assert.AreEqual(LineType.Forward, testObject.Line.LineType); Assert.AreEqual(EndType.Arrow, testObject.Line.EndType); testObject = play.Objects.FirstOrDefault(o => o.Item.Number == 21); Assert.NotNull(testObject); Assert.True(testObject.Line?.Smoothed); Assert.AreEqual(176, testObject.Line !.Points.Count); }
public async Task <Plays> LoadPlays(string username, int page = 1, DateTime?minDate = null, DateTime?maxDate = null) { try { string url = string.Format(BASE_URL2 + "/plays?username={0}&subtype=boardgame&excludesubtype=videogame&page={1}", username, page); if (minDate != null) { url += "&mindate=" + minDate.Value.ToString("yyyy-MM-dd"); } if (maxDate != null) { url += "&maxdate=" + maxDate.Value.ToString("yyyy-MM-dd"); } Uri teamDataURI = new Uri(url); XDocument xDoc = await ReadData(teamDataURI); // LINQ to XML. IEnumerable <PlayItem> gameCollection = from Boardgame in xDoc.Descendants("play") select new PlayItem { Name = Boardgame.Element("item").Attribute("name").Value, NumPlays = int.Parse(Boardgame.Attribute("quantity").Value), GameId = int.Parse(Boardgame.Element("item").Attribute("objectid").Value), PlayDate = safeParseDateTime(Boardgame.Attribute("date").Value), Comments = Boardgame.Element("comments") != null?TrimmedStringOrNull(Boardgame.Element("comments").Value) : null }; var plays = new Plays(); plays.Total = int.Parse(xDoc.Root.Attribute("total").Value); plays.Items = gameCollection; return(plays); } catch (Exception ex) { throw; //return new Plays(); } }
private void BackButton_Click(object sender, EventArgs e) { Plays player = controller.FindPlayerInTblPlays(tempUsername); Plays plays = controller.FindPlayerPoints(player); currentHighscore = plays.points; //currentHighscore = player.points; //player.points = currentHighscore; if (tempNewPoints > currentHighscore) { controller.UpdatePlayerHighscore(tempNewPoints, player); newHighscore = tempNewPoints; this.Hide(); new LoggedInForm(tempUsername, newHighscore).Show(); } else { newHighscore = currentHighscore; this.Hide(); new LoggedInForm(tempUsername, newHighscore).Show(); } }
public static void MakeSomeData(IServiceProvider serviceProvider) { using (var context = new MusicContext( serviceProvider.GetRequiredService <DbContextOptions <MusicContext> >())) { //This approach to seeding data uses int and string arrays with loops to //create the data using random values Random random = new Random(); //Prepare some string arrays for building objects string[] firstNames = new string[] { "Fred", "Barney", "Wilma", "Betty", "Dave", "Tim", "Elton", "Paul", }; string[] lastsNames = new string[] { "Stovell", "Jones", "Bloggs", "Flintstone", "Rubble", "Brown", "John", "McCartney" }; string[] genres = new string[] { "Classical", "Rock", "Pop", "Jazz", "Country", "Ambient", "Techno" }; string[] instruments = new string[] { "Lead Guitar", "Base Guitar", "Drums", "Keyboards", "Vocals", "Harmonica", "Didgeridoo" }; //Genre if (!context.Genres.Any()) { //loop through the array of Genre names foreach (string g in genres) { Genre genre = new Genre() { Name = g }; context.Genres.Add(genre); } context.SaveChanges(); } //Note: we will use int arrays to hold valid Primary Key values we can //randomly assingn as foreign keys //Create a collection of the primary keys of the Genres int[] genreIDs = context.Genres.Select(g => g.ID).ToArray(); //Album if (!context.Albums.Any()) { context.Albums.AddRange( new Album { Name = "Rocket Food", YearProduced = "2000", Price = 19.99m, GenreID = genreIDs[random.Next(genreIDs.Count())] }, new Album { Name = "Songs of the Sea", YearProduced = "1999", Price = 9.99m, GenreID = genreIDs[random.Next(genreIDs.Count())] }, new Album { Name = "The Horse", YearProduced = "1929", Price = 99.99m, GenreID = genreIDs[random.Next(genreIDs.Count())] }, new Album { Name = "Freedom", YearProduced = "2012", Price = 29.99m, GenreID = genreIDs[random.Next(genreIDs.Count())] }); context.SaveChanges(); } //Create a collection of the primary keys of the Albums int[] albumIDs = context.Albums.Select(a => a.ID).ToArray(); //Song if (!context.Songs.Any()) { //Double loop through the arrays of names //and build song title as you go foreach (string f in firstNames) { foreach (string g in genres) { Song s = new Song() { Title = f + " " + g,//looks silly but gives unique names for the songs GenreID = genreIDs[random.Next(genreIDs.Count())], AlbumID = albumIDs[random.Next(albumIDs.Count())] }; context.Songs.Add(s); } } context.SaveChanges(); } //Create a collection of the primary keys of the Songss int[] songIDs = context.Songs.Select(a => a.ID).ToArray(); //Instrument if (!context.Instruments.Any()) { //loop through the array of Instrument names foreach (string iname in instruments) { Instrument inst = new Instrument() { Name = iname }; context.Instruments.Add(inst); } context.SaveChanges(); } //Create a collection of the primary keys of the Instruments int[] instrumentIDs = context.Instruments.Select(a => a.ID).ToArray(); //Musician if (!context.Musicians.Any()) { // Start birthdate for randomly produced employees // We will subtract a random number of days from today DateTime startDOB = DateTime.Today; //Double loop through the arrays of names //and build the Musician as we go foreach (string f in firstNames) { foreach (string l in lastsNames) { Musician m = new Musician() { FirstName = f, MiddleName = f.Substring(1, 1).ToUpper(), //take second letter of first name LastName = l, SIN = random.Next(213214131, 989898989).ToString(), //Big enough int for required digits //For the phone, needed one more digit than a random int can generate so //concatenated 2 together as strings and then converted Phone = Convert.ToInt64(random.Next(2, 10).ToString() + random.Next(213214131, 989898989).ToString()), InstrumentID = instrumentIDs[random.Next(instrumentIDs.Count())], DOB = startDOB.AddDays(-random.Next(6500, 25000)) }; context.Musicians.Add(m); } } context.SaveChanges(); } //Create a collection of the primary keys of the Musicians int[] musicianIDs = context.Musicians.Select(a => a.ID).ToArray(); //Performance //Add a few musicians as performers on each song if (!context.Performances.Any()) { //i loops through the primary keys of the songs //j is just a counter so we add a few musicians to a song //k lets us step through all musicians so we can make sure each gets used int k = 0;//Start with the first Musician foreach (int i in songIDs) { int howMany = random.Next(1, 7); //How many musicians on a song howMany = (howMany > musicianIDs.Count()) ? 6 : howMany; //Don't try to assign more musicians then are in the system for (int j = 1; j <= howMany; j++) { k = (k >= musicianIDs.Count()) ? 0 : k; Performance p = new Performance() { SongID = i, MusicianID = musicianIDs[k] }; context.Performances.Add(p); k++; } } context.SaveChanges(); } //Plays //Add a few instruments to each musician if (!context.Plays.Any()) { //i loops through the primary keys of the musicians //j is just a counter so we add a few instruments to a musician //k lets us step through all instruments so we can make sure each gets used int k = 0;//Start with the first instrument foreach (int i in musicianIDs) { int howMany = random.Next(5); //add a few instruments to a musician howMany = (howMany > instrumentIDs.Count()) ? 4 : howMany; //Don't try to assign more instruments then are in the system for (int j = 1; j <= howMany; j++) { k = (k >= instrumentIDs.Count()) ? 0 : k; Plays p = new Plays() { MusicianID = i, InstrumentID = instrumentIDs[k] }; context.Plays.Add(p); k++; } } context.SaveChanges(); } } }