Hi everyone I have a question about how to make this more clean, reusable and readable. I have some data models (relics) and this has rarity and level. Depending on the level and the rarity it has to be grouped to later apply this in some math calculation. For this reason, I need to parse all my relics and check for the level and rarity and store in a var counter.
public double TotalGlobalBonus
{
get
{
float commonRarityMultiplier = 20;
float rareRarityMultiplier = 120;
float epicRarityMultiplier = 320;
float legendaryRarityMultiplier = 540;
int rarityCommonLevel1 = 0;
int rarityCommonLevel2 = 0;
int rarityCommonLevel3 = 0;
int rarityCommonLevel4 = 0;
int rarityCommonLevel5 = 0;
int rarityRareLevel1 = 0;
int rarityRareLevel2 = 0;
int rarityRareLevel3 = 0;
int rarityRareLevel4 = 0;
int rarityRareLevel5 = 0;
int rarityEpicLevel1 = 0;
int rarityEpicLevel2 = 0;
int rarityEpicLevel3 = 0;
int rarityEpicLevel4 = 0;
int rarityEpicLevel5 = 0;
int rarityLegendaryLevel1 = 0;
int rarityLegendaryLevel2 = 0;
int rarityLegendaryLevel3 = 0;
int rarityLegendaryLevel4 = 0;
int rarityLegendaryLevel5 = 0;
foreach (RelicModel relic in this.equipedRelics)
{
switch (relic.rarity)
{
case RarityType.COMMON:
switch (relic.Level)
{
case 1:
rarityCommonLevel1++;
break;
case 2:
rarityCommonLevel2++;
break;
case 3:
rarityCommonLevel3++;
break;
case 4:
rarityCommonLevel4++;
break;
case 5:
rarityCommonLevel5++;
break;
}
break;
case RarityType.RARE:
switch (relic.Level)
{
case 1:
rarityRareLevel1++;
break;
case 2:
rarityRareLevel2++;
break;
case 3:
rarityRareLevel3++;
break;
case 4:
rarityRareLevel4++;
break;
case 5:
rarityRareLevel5++;
break;
}
break;
case RarityType.EPIC:
switch (relic.Level)
{
case 1:
rarityEpicLevel1++;
break;
case 2:
rarityEpicLevel2++;
break;
case 3:
rarityEpicLevel3++;
break;
case 4:
rarityEpicLevel4++;
break;
case 5:
rarityEpicLevel5++;
break;
}
break;
case RarityType.LEGENDARY:
{
switch (relic.Level)
{
case 1:
rarityLegendaryLevel1++;
break;
case 2:
rarityLegendaryLevel2++;
break;
case 3:
rarityLegendaryLevel3++;
break;
case 4:
rarityLegendaryLevel4++;
break;
case 5:
rarityLegendaryLevel5++;
break;
}
break;
}
}
}
double common = (commonRarityMultiplier / 100) * (rarityCommonLevel1 * 1 + rarityCommonLevel2 * 5 +
rarityCommonLevel3 * 10 + rarityCommonLevel4 * 20 +
rarityCommonLevel5 * 40);
double rare = (rareRarityMultiplier / 100) * (rarityRareLevel1 * 1 + rarityRareLevel2 * 5 +
rarityRareLevel3 * 10 + rarityRareLevel4 * 20 +
rarityRareLevel5 * 40);
double epic = (epicRarityMultiplier / 100) * (rarityEpicLevel1 * 1 + rarityEpicLevel2 * 5 +
rarityEpicLevel3 * 10 + rarityEpicLevel4 * 20 +
rarityEpicLevel5 * 40);
double legendary = (legendaryRarityMultiplier / 100) * (rarityLegendaryLevel1 * 1 + rarityLegendaryLevel2 * 5 +
rarityLegendaryLevel3 * 10 + rarityLegendaryLevel4 * 20 +
rarityLegendaryLevel5 * 40);
double final = common + rare + epic + legendary;
return final;
}
}
It is a really longe property and will grow if the number of levels grows, so this is not precisely scalable
You need to put all these values in a Dictionary with keys of type RarityType and values of type int[].
var rarity = new Dictionary<RarityType, int[]>();
rarity[RarityType.COMMON] = new int[6];
rarity[RarityType.RARE] = new int[6];
rarity[RarityType.EPIC] = new int[6];
rarity[RarityType.LEGENDARY] = new int[6];
foreach (RelicModel relic in this.equipedRelics)
{
rarity[relic.rarity][relic.Level]++;
}
The first element of each array, the one having index = 0, is intended to be unused.
Related
there is a project for Windows application that I'm still working on and is about a set of card deck. The application utilizes 52 cards which consist of 4 suits and 13 face values such as 2 of Clubs, Jack of Hearts, and so forth. The part that I'm working is that I also have to use five pictureboxes to display each random card so I click on a "Deal" button. I'm aware that I would have to use a "Random" keyword along with using a for-loop to do the shuffle.
Therefore, I'm not too sure how would I display each picturebox with different random cards and display each card's name accordingly.
Beneath of this contain screenshots of what the windows application looks like and my code for the project.
List<PlayingCard> cardDeckList = new List<PlayingCard>();
private void buttonDeal_Click(object sender, EventArgs e)
{
int integer = 0;
Random picRandom = new Random();
int n = 0;
integer = picRandom.Next(0, imageListCards.Images.Count);
for( n = 0; n < cardDeckList.Count; n++)
{
pictureBox_Card1.Image = cardDeckList[integer].CardImage;
pictureBox_Card2.Image = cardDeckList[integer].CardImage;
pictureBox_Card3.Image = cardDeckList[integer].CardImage;
pictureBox_Card4.Image = cardDeckList[integer].CardImage;
pictureBox_Card5.Image = cardDeckList[integer].CardImage;
}
listBoxOutput.Items.Add(cardDeckList[integer].ToString());
}
private void FormShuffleCardDeck_Load(object sender, EventArgs e)
{
try
{
string[] suitList = { "Clubs", "Diamonds", "Hearts", "Spades" };
string[] faceList = new string[13];
List<int> pointValues = new List<int>();
pointValues.Add(2);
pointValues.Add(3);
pointValues.Add(4);
pointValues.Add(5);
pointValues.Add(6);
pointValues.Add(7);
pointValues.Add(8);
pointValues.Add(9);
pointValues.Add(10);
pointValues.Add(10);
pointValues.Add(11);
string suit = "";
string face = "";
int counter = 0;
int i = 0;
int k = 0;
for (i = 0; i < 4; i++)
{
suit = i.ToString();
switch (suit)
{
case "0":
suit = "Clubs";
break;
case "1":
suit = "Diamonds";
break;
case "2":
suit = "Hearts";
break;
case "3":
suit = "Spades";
break;
}
for (k = 0; k < 13; k++)
{
face = k.ToString();
switch (k)
{
case 0:
face = "2";
break;
case 1:
face = "3";
break;
case 2:
face = "4";
break;
case 3:
face = "5";
break;
case 4:
face = "6";
break;
case 5:
face = "7";
break;
case 6:
face = "8";
break;
case 7:
face = "9";
break;
case 8:
face = "10";
break;
case 9:
face = "Ace";
break;
case 10:
face = "King";
break;
case 11:
face = "Jack";
break;
case 12:
face = "Queen";
break;
}
cardDeckList.Add(new PlayingCard(suit, face, imageListCards.Images[counter],2));
counter++;
}
}
//for (int l = 0; l < cardDeckList.Count; l++)
//{
// listBoxOutput.Items.Add(cardDeckList[l].ToString());
// //MessageBox.Show(cardDeckList.Count.ToString());
//}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Windows App Program
I'm not sure how your PlayingCard class is coded, but it seems like a large portion of your problems stem from its design. Take this implementation for example:
PlayingCard Class
public class PlayingCard : IComparable<PlayingCard>
{
private int value;
private int suit;
private Bitmap cardImage;
public int Value => value;
public string ValueName => ValueToName(value);
public int Suit => suit;
public string SuitName => SuitToName(suit);
public Bitmap CardImage => cardImage;
public PlayingCard(int value, int suit, Bitmap cardImage)
{
this.value = value;
this.suit = suit;
this.cardImage = cardImage;
}
private string ValueToName(int n)
{
switch (n)
{
case 0:
return "Ace";
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return (n+1).ToString();
case 10:
return "Jack";
case 11:
return "Queen";
case 12:
return "King";
default:
throw new ArgumentException("Unrecognized card value.");
}
}
private string SuitToName(int s)
{
switch (s)
{
case 0:
return "Clubs";
case 1:
return "Diamonds";
case 2:
return "Spades";
case 3:
return "Hearts";
default:
throw new ArgumentException("Unrecognized card suit");
}
}
public int CompareTo(PlayingCard other)
{
int result = this.Suit.CompareTo(other.Suit);
if (result != 0)
return result;
return this.Value.CompareTo(other.Value);
}
public override string ToString()
{
return String.Format("{0} of {1}", ValueName, SuitName);
}
}
It has all the comparison and value conversion coded within it, so you don't have to worry about creating highly specialized methods to do extraneous conversions. You can use it in a deck like so:
Array Implementation
// How to initialize deck
PlayingCard[] deck = Enumerable.Range(0, 52)
.Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
.ToArray();
// How to shuffle deck
Random r = new Random();
Array.Sort(deck, (a, b) => r.Next(0, 2) == 0 ? -1 : 1);
// How to reset deck
Array.Sort(deck);
// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;
List Implementation
// How to initialize deck
List<PlayingCard> deck = Enumerable.Range(0, 52)
.Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
.ToList();
// How to shuffle deck
Random r = new Random();
deck.Sort((a, b) => r.Next(0, 2) == 0 ? -1 : 1);
// How to reset deck
deck.Sort();
// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;
EDIT:
Manual Shuffling
If you want to do a shuffle manually, there's a simple algorithm called the Fisher-Yates Shuffle that will do the trick:
private static Random r = new Random();
static void Shuffle<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
int idx = r.Next(i, array.Length);
T temp = array[idx];
array[idx] = array[i];
array[i] = temp;
}
}
(List Implementation)
private static Random r = new Random();
static void Shuffle<T>(List<T> list)
{
for (int i = 0; i < list.Count; i++)
{
int idx = r.Next(i, list.Count);
T temp = list[idx];
list[idx] = list[i];
list[i] = temp;
}
}
I have some months read into an array from an external text file and I need to convert the months to an array that holds the value equivalent of the months e.g. January = 1, February = 2 etc. So that they can then be put through Quicksort.
public static void Main(string[] args)
{
//Read external files into arrays.
string[] Month = File.ReadLines(#"Month.txt").ToArray();
string[] Year = File.ReadLines(#"Year.txt").ToArray();
//Convert arrays from string to double to be used in sort.
double[] YearSort = Array.ConvertAll(Year, double.Parse);
int UserInput1;
//Create new array that will hold selected array to be used in sort.
double[] data = new double[1022];
//Prompt user to select action.
Console.WriteLine("Press 1 to Sort by month or 2 to sort by year.");
UserInput1 = Convert.ToInt32(Console.ReadLine());
if(UserInput1 == 1)
{
Array.Copy(Month,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else if (UserInput1 == 2)
{
Array.Copy(YearSort,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else
{
Console.WriteLine("Please try again and select a valid option");
}
}
static int MonthToDouble( string Month )
{
int NewMonth = 0;
switch(Month)
{
case "January":
case "january":
NewMonth = 1;
break;
case "February":
case "february":
NewMonth = 2;
break;
case "March":
case "march":
NewMonth = 3;
break;
case "April":
case "april":
NewMonth = 4;
break;
case "May":
case "may":
NewMonth = 5;
break;
case "June":
case "june":
NewMonth = 6;
break;
case "July":
case "july":
NewMonth = 7;
break;
case "August":
case "august":
NewMonth = 8;
break;
case "September":
case "september":
NewMonth = 9;
break;
case "October":
case "october":
NewMonth = 10;
break;
case "November":
case "november":
NewMonth = 11;
break;
case "December":
case "december":
NewMonth = 12;
break;
}
return NewMonth;
}
static string DoubleToMonth(double Month)
{
string NewMonth = "";
switch ((int)Month)
{
case 1:
NewMonth = "January";
break;
case 2:
NewMonth = "February";
break;
case 3:
NewMonth = "March";
break;
case 4:
NewMonth = "April";
break;
case 5:
NewMonth = "May";
break;
case 6:
NewMonth = "June";
break;
case 7:
NewMonth = "July";
break;
case 8:
NewMonth = "August";
break;
case 9:
NewMonth = "September";
break;
case 10:
NewMonth = "October";
break;
case 11:
NewMonth = "November";
break;
case 12:
NewMonth = "December";
break;
}
return NewMonth;
}
//QuickSort for double data values are in ascending order.
public static void QuickSort(double[] data)
{
Quick_Sort(data, 0, data.Length - 1);
}
public static void Quick_Sort(double[] data, int left, int right)
{
int i, j;
double pivot, temp;
i = left;
j = right;
pivot = data[(left + right) / 2];
do
{
while ((data[i] < pivot) && (i < right)) i++;
while ((pivot < data[j]) && (j > left)) j--;
if (i <= j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
i++;
j--;
}
} while (i <= j);
if (left < j) Quick_Sort(data, left, j);
if (i < right) Quick_Sort(data, i, right);
}
}
A DateTime object's Month property gives you the integer value of the month starting at 1 like you need. So you can use DateTime.ParseExact() to parse the string into a full DateTime object then grab the Month property:
int monthNumber = DateTime.ParseExact("January", "MMMM", CultureInfo.CurrentCulture).Month;
You just need to replace "January" with your month strings, and leave "MMMM"which is the Custom Format String for "The full name of the month".
All the above code does is simplify your MonthToDouble() method, which you are not even using for some reason (also it should return a double, not an int). Contrary to your title, you already have a method to "Convert months to number equivalent", you just aren't using it.
So, I assume the only thing you are missing is to replace this:
Array.Copy(Month,data,1022);
QuickSort(data);
With this:
double[] monthsAsDoubles = new double[Month.Length];
for (int i = 0; i < monthsAsDoubles.Length; i++)
{
monthsAsDoubles[i] = MonthToDouble(Month[i]);
}
QuickSort(monthsAsDoubles);
Also change the return value of MonthToDouble() from int to double (cast if you need to).
Edit: On second thought, Quantic's answer is simpler. I'll just leave this here as an alternative.
Your code can be simplified a lot by using the DateTimeFormatInfo.MonthNames property, along with a case-insensitive string comparison. This also has the advantage of being much easier to port to use different languages for the month names.
Here is a snippet:
using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var InputMonths = new List<string> { "January","march","sepTEmber","smarch" };
var MonthNames = new DateTimeFormatInfo().MonthNames.ToList();
var InputMonthNumbers = new List<int>();
foreach (var m in InputMonths)
{
//Find index of the month name, ignoring case
//Note if the input month name is invalid, FindIndex will return 0
int month_num = 1 + MonthNames.FindIndex(name => name.Equals(m, StringComparison.OrdinalIgnoreCase));
if (month_num > 0)
{
InputMonthNumbers.Add(month_num);
}
}
foreach (var n in InputMonthNumbers)
{
Console.WriteLine(n.ToString());
}
}
}
output:
1
3
9
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm developing a text-based RPG and I'm implementing a stat system. My code for the classes that interact with it is:
switch (charClass)
{
case "a":
Player.charC(0);
break;
case "b":
Player.charC(1);
break;
case "c":
Player.charC(2);
break;
}
public static void charC(int charPath)
{
switch (charPath)
{
case 0:
Player.stats(0);
break;
case 1:
Player.stats(1);
break;
case 2:
Player.stats(2);
break;
}
}
public static void stats(int stat)
{
Player p = new Player();
switch (stat)
{
case 0:
p.m_health = 200;
p.m_mana = 75;
p.fast = 7;
p.strng = 20;
p.smrt = 7;
p.move = 7;
p.level = 1;
break;
case 1:
p.m_health = 100;
p.m_mana = 200;
p.fast = 10;
p.strng = 7;
p.smrt = 15;
p.move = 7;
p.level = 1;
break;
case 2:
p.m_health = 100;
p.m_mana = 100;
p.fast = 10;
p.strng = 10;
p.smrt = 10;
p.move = 10;
p.level = 1;
break;
}
}
When I try to run it, it returns all the stats as 0.
Example: MAX HEALTH 0. MAX MANA 0. FAST 0. STRONG 0. SMART 0.
In the stats method you're not returning the player object. You create a new player, set its properties, but discard the object at the end of the method.
In short: You're not working on the object you think you're working on.
Why is all this static?
You need to remove the static-ness of stats and call it with the instance of the player
public void stats(int stat)
{
switch (stat)
{
case 0:
m_health = 200;
m_mana = 75;
fast = 7;
strng = 20;
smrt = 7;
move = 7;
break;
case 1:
m_health = 100;
m_mana = 200;
fast = 10;
strng = 7;
smrt = 15;
move = 7;
break;
case 2:
m_health = 100;
m_mana = 100;
fast = 10;
strng = 10;
smrt = 10;
move = 10;
break;
}
level = 1;
}
use the instance of player in both switches, i.e
switch (charClass)
{
case "a":
playerInstance.charC(0);
break;
case "b":
playerInstance.charC(1);
break;
case "c":
playerInstance.charC(2);
break;
}
public void charC(int charPath)
{
switch (charPath)
{
case 0:
this.stats(0);
break;
case 1:
this.stats(1);
break;
case 2:
this.stats(2);
break;
}
}
This code:
private int GetColumnToPopulate(int columnBase, int offset) {
int duckbillColNum = 0;
switch (columnBase) {
case 0:
duckbillColNum = 1;
break;
case 1:
duckbillColNum = 5;
break;
case 2:
duckbillColNum = 9;
break;
case 3:
duckbillColNum = 13;
break;
case 4:
duckbillColNum = 17;
break;
case 5:
duckbillColNum = 21;
break;
case 6:
duckbillColNum = 25;
break;
case 7:
duckbillColNum = 29;
break;
}
duckbillColNum += offset;
return duckbillColNum;
}
...is easy to grok, but verbose and clunky. I would like to streamline it. My pseudocode idea is something like:
int[] colBases
{
0..7
}
int[] offsets
{
1,5,9,13,17,21,25,29
}
int idx = colBases.IndexOf(columnBase);
duckbillColNum = offsets[idx];
...or perhaps a multidimensional int array? At any rate, the "IndexOf" business, of course, does not comp[ile,ute].
How about:
private int GetColumnToPopulate(int columnBase, int offset) {
return (columnBase * 4) + 1 + offset;
}
Consider using a Dictionary, you could define it like this:
Dictionary<int, int> offsets = new Dictionary<int, int>()
{
{ 0, 1 },
{ 1, 5 },
{ 2, 9 },
{ 3, 13 },
{ 4, 17 },
{ 5, 21 },
{ 6, 25 },
{ 7, 29 },
}
And then when using it:
return offsets[columnBase];
It seems to me that you should replace the switch with this expression duckbillColNum = columnBase*4 +1; isn't it?
This is just a simple mathematical pattern:
private int GetColumnToPopulate(int columnBase, int offset)
{ return 1 + (columnBase * 4) + offset; }
I have written code to display many image (100 image) with PictureBox but when run the application, just one image has been shown...
please help me guys...
Here is my code:
Random r = new Random();
private int randomPoint()
{
return 1 + r.Next() % 15;
}
// x0, y0
private int[] initialLocation = new int[2];
private void setLocation(int i)
{
int x0 = 50, y0=50;
initialLocation[1] = y0;
switch (i)
{
case 1: initialLocation[0] = x0;
break;
case 2: initialLocation[0] = x0 + 50;
break;
case 3: initialLocation[0] = x0 + 100;
break;
case 4: initialLocation[0] = x0 + 150;
break;
case 5: initialLocation[0] = x0 + 200;
break;
case 6: initialLocation[0] = x0 + 250;
break;
case 7: initialLocation[0] = x0 + 300;
break;
case 8: initialLocation[0] = x0 + 350;
break;
case 9: initialLocation[0] = x0 + 400;
break;
case 10: initialLocation[0] = x0 + 450;
break;
}
}
public Form1()
{
InitializeComponent();
PictureBox[] p = new PictureBox[10];
for (int i=0; i<10;i++)
{
p[i] = new PictureBox();
p[i].ImageLocation = "1.png";
int[] l = new int[2];
// create random location for images
setLocation(randomPoint());
p[i].Location = new Point(initialLocation[0], initialLocation[1]);
this.Controls.Add(p[i]);
}
}
It's because you are declaring your random number generator every time you want an image:
private int randomPoint()
{
Random r = new Random();
return 1 + r.Next() % 15;
}
replace this with:
private Random r = new Random();
private int randomPoint()
{
return 1 + r.Next() % 15;
}
UPDATE
If I understand you correctly you want to display 15 images in a random order across the form.
To ensure that you don't get any repeats you need to make sure that you remove the picture you've picked from the list before picking the next. So (in pseudo code) you need something like this:
this.folderList = new List<string>();
// Populate it in an orderly manner
// Create temporary list to put the randomly selected items into
var radomisedList = new List<string>();
// Randomise the list.
var random = new Random();
int num = 0;
while (this.folderList.Count > 0)
{
num = random.Next(0, this.folderList.Count);
radomisedList.Add(this.folderList[num]);
this.folderList.RemoveAt(num);
}
This will ensure you get a random order and no repeats.