Physics in OO game programming - c#

So I am in the process of trying to learn how to develop 2D games.
I am playing around with both Android and C#.
The issue that I am having is this.
It is easy enough to draw a sprite of some sort. Where I struggle is to visualize how one can code interactions of various objects on screen.
For example lets say I have the following Object.
public class MyGenericObject {
public MyGenericObject() {}
public Int32 Width { get; set; }
public Int32 Height { get; set; }
public Int32 X { get; set; }
public Int32 Y { get; set; }
public Image ObjectImage { get; set; }
}
Lets say I want to model the behavior of an interaction between N number of these Objects. What is a typical pattern one would utilize in such a scenario?
So for example would you simply call a method such as MyPhysicsSim.DoPhysics(List<MyGenericObjects>);
Assuming this is not a huge stretch. Inside of this method then, how do you calculate the interactions and resulting movements? I just can't get my head around it (Obviously I do understand that there are basic equations that can solve direction and speed and so forth but I just can't seem to work out how to apply these as an algorithm).
I have looked at numerous tutorials and all of them seem to concentrate on just drawing an object or assume a level of understanding about the internals that is way over my head. So I am hoping for a really simple, dumbed down response.
So basically what I am asking is how do you approach interactions between 2D objects in a OO paradigm for dummies?

Traditionally, most games have a loop similar to the one below somewhere at the core:
while (1) {
World.respondToInput();
World.updatePhysics();
World.renderScene();
Timer.waitUntilFrameExpires();
}
and the 'updatePhysics()' method can do something very basic, such as:
for (Object obj1 in World.trackedObjects()) {
for (Object obj2 in World.trackedObjects()) {
if (obj1.influences(obj2)) {
obj1.update(); obj2.update();
}
}
}
So you basically have a 'tick' in the world you're simulating, and your code works to reflect the delta in the scene that would have occurred.

Related

How do I go about saving multiple modified prefabs instantiated from the same scriptable object C#

Work with me now, I'm a confused lost little child at this point.
Intro
I have an inventory that allows me to place items into a gear slot, instantiating that item in my players hand/ on body. For example, I have a simple rifle, I put it in my gear slot and it is created. My player can now run around shoot, kill, and unequip it too! BUUUT I can not figure out how to save my modified variables.
Problem Lore
All my items are Scriptable Objects while in the inventory, so I can easily create different items. The Scriptable Object holds; some text data, other things, and the actual prefab of the weapon I want to instantiate. The problem is, when I unequip the item from the gear slot it deletes the prefab, as it should, I don't want to see or use it anymore while in game. I can easily create an upgrade system, but saving those changed variables is a problem. I'm deleting it when I unequip it and instantiating a new copy when I equip it. My game allows the player to pickup the same weapon until the inventory is full too.
Overall Problems
How do I go about saving multiple modified prefabs instantiated from the same scriptable object?
Should I figure out how to create a unique Id that represents the weapon and allows the scriptable object to instantiate this unique Id?
I'm not sure if the second question is possible, but I think you might get the gist of the problem, any solutions are helpful, if I should recreate my inventory, I'd cry for sure, but I really want a weapon upgrade system in my game, so I'LL HECKIN DO IT! Thank you guys.
Problem
I will have a lot of various classes, which is very similar("simple sword", "diamond sword", "giga sword"...)
Solution
Strategy pattern, instead of creation whole new object, i will change the property of this object
Example
interface IHandle
{
public int Speed { get; set; }
}
class SimpleHandle : IHandle
{
public int Speed { get; set; }
public SimpleHandle()
{
Speed = 5;
}
}
interface IBlade
{
public int Damage { get; set; }
}
class SimpleBlade : IBlade
{
public int Damage { get; set; }
public SimpleBlade()
{
Damage = 5;
}
}
class Sword
{
private IHandle _handle { get; set; }
private IBlade _blade { get; set; }
public void ChangeHandle(IHandle handle)
{
_handle = handle;
}
public void ChangeBlade(IBlade blade)
{
_blade = blade;
}
}

Getting typed items from a collection of objects - how to keep track of type?

I instantiate my class firedragon. I store it in a public List collection that holds objects.
List<object> currentEnemies = new List<object>();
I want to grab that list item,
currentEnemies[0]
and convert it back into my class. I just don't know how to do that. Can anyone explain to me how to do that, or a better way to store my data?
NOTE: The reason why I am using a list that holds objects is because I have many different classes that may be stored in the list.
One way of handling this is with pattern matching. You could implement a common handler for currentEnemies like,
foreach (var enemy in currentEnemies)
{
switch (enemy)
{
case FireDragon dragon:
UpdateDragon(dragon);
break;
case Bulbasaur plant:
BeAdorable(plant);
break;
// and so on...
}
}
If you have just a handful of types, and won't have much more in the future (consider this carefully), this isn't too bad, but gets horribly cumbersome quickly.
Ideally, you should look for common elements on your enemies, so that you can simplify this. For example, if you have code that moves the enemy in the world every step, they could all implement a common interface,
interface IMobile
{
(int X, int Y) Move(int x, int y);
int Speed { get; }
}
Then code to handle movement of enemies could be just,
var mobiles = new List<IMobile>();
// then in other code that can access `mobiles`
foreach (var mobile in mobiles)
{
mobile.Move(mobile.Speed);
}
Generally it's a bad idea when you have direct control over the items be inserted and removed from a list to use object as the generic type for a List. It sounds like you're building a game, and if you are I would architect it using interfaces and then use OfType<> quite a bit.
// Anything you want to track in the game
public interface IGameEntity {}
// Anything that opposes a plyaer
public interface IEnemy : IGameObject {}
// Anything used to do Physical Harm
public interface IWeapon : IGameObject {}
// Anything that can be collected for a purpose (wood, gold, etc)
public interface IResource : IGameObject {}
I'm honestly not sure if a red dragon would be much different then a blue dragon, I would assume not so I would just create a Dragon class.
public class Dragon : IEnemy
{
public DragonColor Color { get; set; }
}
public enum DragonColor
{
Red,
}
Then you're list is:
List<IGameEntity> entities;
All dragons are
var dragons = entities.OfType<Dragon>();
I have a feeling you are looking for a solution using composition. Example:
public class Enemies {
public FireDragon TheDraggon { get; set; }
public List<Troll> Trolls { get; set; }
/* other enemies that you need to track */
}
With this approach you do not have to guess or check what type an instance is within the list of objects.

I want to spawn two types of enemies in rows (think Galaga), how should I set up my classes inheritance wise?

I want to make a game similar to galaga in xna using C#. I have two types of enemies (behavior and sprite are different, as well as sound effects), and I want each to have their own rows. I was earlier using arrays to generate enemies on screen, but apparently this isn't a good approach and was told I should use lists instead. Now, I was thinking there could be a few of ways of creating the enemy classes themselves. One was using inheritance, with a base class of Enemy, and then two other classes that inherit from Enemy but have their own behavior and sprite. Another way of doing this would be to create an enemy interface. And one other way of setting this up would be to use structs. I think using interface would be more time consuming compared to the other two, but I could be wrong (if I am, let me know). The other two I am not sure about though. Technically, I believe they both use classes, just one uses structs. What would be the better way of doing this, inheriting from an enemy class, or using an enemy struct?
Considering a simple scenario, creating the Enemy class and then using inheritance is the way to go.
If you need a more complex logical tree to add specific methods to entities that don't belong to the same tree then start using Interfaces. For example, if there is an "Enemy" tree and an "Ally" tree and you want some kind of same behaviour for enemy Type1 (inherits from Enemy) and ally Type2 (inherits from Ally) when they die, then consider using an interface for that.
Anyway and just as an example, the use of an Interface could be justified when you need to manage Lists of objects that are tagged with that interface to call specific methods (entities that for example "ExplodeWhenDying"). If you don't need to manage those kind of lists, then just use methods on a common parent class (for example "Entity" (Enemy and Ally inherit from Entity) and overwrite those methods (Explode()).
Interfaces are better suited to situations in which your program requires many possibly unrelated object types to provide certain functionality which i guess is not the case here.
The longer I code up solutions the more I like the concept of "Favor Composition over inheritance". It doesn't mean reject inheritance but many times in my past I over-used inheritance. The advantages to composition are that the lowest object in the hierarchy is always expandable, there is NEVER any name confusion and it leads to better unit testing.
But what is composition? It's simply the ability to contain some other object within your parent object. I typically use property getters and setters to expose the object like example below. All cars have wheels and engines and color and could be inherted, but they are NOT a type of any of those, so it's better to compose them or "inject" the traits... This is composition and shows concrete classes (not interfaces). Interfaces are better but you don't have to do them.
public class ComposeACar
{
public ComposeACar(Wheels theWheels, Engine theEngine, Color theColor)
{
MyWheels = theWheels;
MyEngine = theEngine;
MyColor = theColor;
}
public Wheels MyWheels { get; set; }
public Engine MyEngine { get; set; }
public Color MyColor { get; set; }
}
public class Wheels {
public string size { get; set; }
public decimal price { get; set; }
public string Manufacturer { get; set; }
}
/// <summary>
/// Same here for the next two class examples
/// </summary>
public class Engine {}
public class Color {};
public class BuildACar {
public BuildACar()
{
var wheels = new Wheels { Manufacturer = "GoodYear", size = "17", price = 195.00M };
var engien = new Engine();
var color = new Color();
var newCar = new ComposeACar(wheels,engien,color);
}
}

game design improvement

I was having a discussion with my developer mate on following game design.
I have a collection of Move in the Game class. my developer mate is asking me to remove the collection and only have the current move information there.
what is your suggestions?
public class Game
{
public String Id { get; set; }
public String CreatorId { get; set; }
public List<Player> Players { get; set; }
public List<Move> Moves { get; set; }
}
public class Player
{
public String Id { get; set; }
public String Name { get; set; }
}
public class Move
{
public String Id { get; set; }
public String PlayerId { get; set; }
public String PlayerName { get; set; }
public String NextMoveId { get; set; }
public String NextPlayerId { get; set; }
public String Position { get; set; }
}
Edit:
my developer mate suggests me to only have a single Move object in the Game class.
There's no really correct approach that any of us can provide for your design. It isn't a cut-and-dry situation; there's no "right" or "wrong" answer. And it's especially difficult for us to make suggestions given that we don't know all of the details behind your game's design. For example, as I asked in a comment and several of the other answers have hinted towards, if you have an "Undo" or "Replay" feature, you will need to store a history of all the moves. If not, and you have no desire to implement such a feature, there is no need to store information about all of the moves.
This is the kind of design decision that you need to learn how to make as a programmer. Consider all of the possible benefits of one approach and the benefits of the other approach, then decide which one best suits your application. Make a "T" chart if you find it helpful. Something like:
Keeping List of All Moves | Storing Only Last Move
---------------------------------------|------------------------------------
- Allows you to implement Undo | - Simplifies your game's design
or Replay feature |
- Consumes more memory | - Saves memory by only storing the
| minimum amount of data
|
|
...etc.
In the end, you (and your colleague) are the ones in the best position to make this decision. Making sure that you've armed yourself with a careful comparison of the advantages and disadvantages is the best way to ensure that you've made the right one.
A game often consists of a set of moves performed by one or more players. Between each move, the game is in a certain state.
If you have the current state, and no need to playback or undo any moves, you would never access the previous moves. Future moves are not known yet, so with just the information you provided, I'd say Game should not have any Move, just a State and a ProcessMove(Move move) method to change the Game's State. The Move is generated by one of the Players.
public class Game
{
public String Id { get; set; }
public String CreatorId { get; set; }
public List<Player> Players { get; set; }
public String PlayerId { get; set; }
}
public class Player
{
public String Id { get; set; }
public String Name { get; set; }
public String Position { get; set; }
public Move(string NewPosition);
public event EventHandler onMoved;
}
This would be my prefered option, although without knowing what type of game it it it's hard to know. Either way, a player should encapsulate its own position, and the Game should know the current player.
As for moves, its game dependant, but move will change the players position, and this may or may not effect other players, so I'd probably implement move on the player and have a onMoved event on the players, which the game is subscribed to..
I think having the collection could be useful in implementing an 'undo move' feature in your game. The list of Move objects could be an implementation of commands, and you could save/restore the state of your game using information in the commands.
I see nothing wrong with having a collection of moves in there. You can expose the current move with another property, then both, you and your mate are statisfied.
That's all I can say with the information you provided. I do not know your game logic. The Collection of Moves can be an advantage when you need to have a history of moves (e.g. a replay function) or you want to plan several moves ahead. I see nothing wrong there besides the fact that you probably do not necessarily need it.
By the way: List<T> is meant for implementations, not for ObjectModels. I'd wrap the List in a class called MovesCollection. And Move should implement an interface (an abstract contract) in case you need many different moves implementations (e.g. AttackMove, Fortify-Move, Retreat-Move ...)
From my point of view. If you don't want that UNDO feature then placing list of MOVES is useless because you already mentioned that no we do not have Undo feature, nor we think about having it . then why having this list here ?
think this as, you have declare lots of variables in your code and not using them. It is good practice that keeping code clean and simple =)

Object representation of betting rounds at poker

I'm writing a HandConverter of a poker hand. This is my first project and I'm trying to do it right from the beginning.
I got already the most parts, like lists of players, their position, stack sizes, cards for different boards, what game is being played and so on, but I struggle with the representation of the betting, especially the different raises, bets and multiple calls from the same player.
I found some cases where my naive case based solution does not work, and it's really complicated and I dislike it. As it currently works for NL Hold'em I think I'll have more workarounds to do if I want to implement games like Stud, Razz and so on altough the betting structure is likely the same.
For now I use this representation and I would like to improve especially the Round and Action classes. Do you have some suggestions for me?
public class HandHistory
{
public GameInfo GameInfo;
public TableInfo TableInfo;
public List<Player> Players;
public List<Round> Rounds;
public string rawtext;
public bool withHero;
}
public Round
{
public List<Action> Action;
public string Name;
public decimal Potsize;
public ulong Cards; //usually would have used a custom class,
//but I need them in a ulong mask for some library I use
}
public class Action
{
public Player Player;
public string Type;
public decimal Amount;
}
P.S. I'm also using a List to store the different rounds, is there better way like inheriting the round class for Flop, Turn and River e.g?
Instead of a string for your Action.Type, you could use an enum:
enum BettingAction
{
Check,
Bet,
Call,
Raise,
Fold
}
When you say first project what do you mean? I am guessing you are a student or new to programming.
Under that assumption I would suggest picking something simpler and than a poker hand history. As in game programming it is unreasonable to think on your first shot of programming a game you create the latest Call of Duty. You start with breakout and move up from there.
If you do not wish to start smaller than I suggest never jump into coding. When you do that you will spend more time just spinning your wheels rather than getting something done.
For instance you should first spend time designing what your program will do and what it will not do. Try to be as complete as possible. This can be done from something as complicated using a UML program or as simple as pen and paper.
I would flow out how you want a hand to progress. Information you want to track. Once you really understand this your data structures will start to come to life.
Since you are new to programming, I would start to write proof of concept code. Then move it to your final project. What I mean by proof of concept is code that you are just testing an idea to see how it works. For example, how would hand history work? Can you create some 'mock' history and set them up? Ideally you would unit test, but lets start a little smaller.
It is important to know that you are constructing a program, just like a house. You need to know what you want it to do and not do (blue prints). What each step is. And you build upon other pieces slowly. It is a process that takes time, but in the end is well worth it.
Cards could have a better name, but I am assuming you mean the community cards. I would make it a list of Cards, then the turn and river subclasses would just only ever have one card in the list. I would also suggest representing the cards in a way that makes sense to you and then doing a conversion when you need to interface with the library.
Not really a programming related answer; but the betting styles for Razz or Stud is different from Hold 'em in several ways.
1.) There are no blinds; rather antes
2.) The person opening can either bring-in or complete the bet
3.) There are more rounds of betting
You have a pretty good start. You'd probably want to create a List<Hands> which has List<Rounds> inside it. Otherwise you'll have a huge list of rounds without being able to tell when one hand started/ended and another one began.
I think you probably need to define out your action types, and then things will probably start to fall into place. Here's what I would have for types:
Check
Bet
Fold
Call
Raise (essentially a call and bet)
Might also want to think about implementing something like "Prior Action" on your action class; as each player is reacting to the action before them.
You'd also want to address some nuances of the game; where player a bets 500 and player b goes all in for 250; since except in this instance, the call needs to match the prior bet.
The term Round is a little ambiguous. BettingRound makes it more obvious.
I don't see the need to have cards, name and potsize here. Potsize is a function of the actions and changes throughout the betting round.
Seats represent the game a little better than a list of players does as this allows you to represent the game state (stack sizes etc.) a little more obviously.
I don't see the need to make the flop, river cards explicitly assigned to rounds - just use a list of cards and some conventions. e.g. first three cards = flop... first betting round = flop. Use some extension methods for convenience of referring to the flop for holdem.
Use the ulong version of cards via conversion when you need to use it rather than cluttering your domain model.
This is how I see the model of a particular individual Game (i.e. 1 flop, river, turn etc.). There's still a bunch of work to do to model all games (e.g. limit games use small bet / big bet instead of blinds to define the stakes).
public class Card
{
public Suit Suit;
public Rank Rank;
public ulong ToCardMask();
}
public enum Suit
{
Clubs,
Diamonds,
Hearts,
Spades
}
public enum Rank
{
Ace,
Deuce,
Trey,
//...
Jack,
Queen,
King
}
public class Game
{
public GameInfo GameInfo;
public TableInfo TableInfo;
public List<BettingRound> BettingRounds;
public List<Card> CommunityCards;
public string Rawtext;
public bool WithHero; //??
}
public static class GameExtensions
{
public static BettingRound Flop(this Game game)
{
return game.BettingRounds[0];
}
public static List<Card> FlopCards(this Game game)
{
return game.CommunityCards.Take(3).ToList();
}
}
public class GameInfo
{
public GameType GameType;
public GameBettingStructure BettingStructure; // Limit, PotLimit, NoLimit
public Stakes Stakes; // e.g. { $1, $2 }
public long Id;
public List<Seat> Seats;
}
enum GameType // prob change to a class for extensibility
{
HoldEm,
Razz,
StudHi,
StudHiLo,
OmahaHi,
OmahaHiLo
}
enum GameBettingStructure
{
Limit,
PotLimit,
NoLimit
}
class Stakes // probably needs some tweeking for stud games (e.g. bring-in ...)
{
public Money Ante;
public List<Money> Blinds;
}
public class Seat
{
public Player Player;
public Money InitialStackAmount;
public Money FinalStackAmount; // convienience field can be calculated
public List<Card> Hand;
}
class Money
{
public decimal Amount;
public Unit Unit;
}
enum Unit
{
USD,
EUR,
AUD,
TournamentDollars
}
public class Player
{
public string Name;
}
public class TableInfo
{
public string Name;
}
public class BettingRound
{
public List<BettingAction> BettingActions;
}
public class BettingAction
{
public abstract Money PotSizeAfter();
public byte SeatNumber;
}
public class Fold : BettingAction { }
public class Call : BettingAction { }
public class BringIn : BettingAction { }
public class Complete : BettingAction { }
public class Bet : BettingAction
{
public Money Amount;
}
public class Raise : Bet { }
instead of SubClassing Round into FlopRound TurnRound etc, I would use a Street attribute within round, and within Action as well.
static public enum Street {PREFLOP, FLOP, TURN, RIVER};
...

Categories