So I've made this form that acts as a cake shop. I have everything working perfectly except for the price. For some reason it isn't displaying properly and shows "$22.60" every time. I'm thinking there might be something wrong with the method
public virtual double CalculateCakeCost()
{
return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
}
from class "Cake" since it seems to return the cake price, but not add it up with the bracket values. The calculate cost with tax method from the class "CustomCake" also seems to be working fine. You can read the rest of the code is down below and please tell me if there is a problem, because I don't see anything wrong.
namespace Lab_OrderCake_The_Bakery_
{
public partial class frmOrderCake : Form
{
Cake objcake;
CustomCake objcustcake;
Customer objcustomer;
Order objorder;
public frmOrderCake()
{
InitializeComponent();
}
private void btnOrder_Click(object sender, EventArgs e)
{
//flavour
if (radVanilla.Checked == true)
{
txtRadFlavour.Text = "Vanilla";
}
if (radChocolate.Checked == true)
{
txtRadFlavour.Text = "Chocolate";
}
if (radBanana.Checked == true)
{
txtRadFlavour.Text = "Banana";
}
if (radLemonBerry.Checked == true)
{
txtRadFlavour.Text = "Lemon banana";
}
//layers
if (rad1layer.Checked == true)
{
numRadLayers.Value = 1;
}
if (rad2layers.Checked == true)
{
numRadLayers.Value = 2;
}
if (rad3layers.Checked == true)
{
numRadLayers.Value = 3;
}
if (rad4layers.Checked == true)
{
numRadLayers.Value = 4;
}
//occassion
if (radAnniversary.Checked == true)
{
txtRadOcc.Text = "Anniversary";
}
if (radBirthday.Checked == true)
{
txtRadOcc.Text = "Birthday";
}
if (radRetirement.Checked == true)
{
txtRadOcc.Text = "Retirement";
}
if (radWedding.Checked == true)
{
txtRadOcc.Text = "Wedding";
}
//size
if (rad6inch.Checked == true)
{
numRadSize.Value = 6;
}
if (rad8inch.Checked == true)
{
numRadSize.Value = 8;
}
if (rad10inch.Checked == true)
{
numRadSize.Value = 10;
}
if (rad12inch.Checked == true)
{
numRadSize.Value = 12;
}
//design
if (radPolka.Checked == true)
{
txtRadDesign.Text = "Polka Dots";
}
if (rad8inch.Checked == true)
{
txtRadDesign.Text = "Edible Images";
}
if (rad10inch.Checked == true)
{
txtRadDesign.Text = "Fondant Bow";
}
if (rad12inch.Checked == true)
{
txtRadDesign.Text = "3D Figures";
}
objcake = new Cake(txtRadFlavour.Text, (int)numRadLayers.Value);
objcustomer = new Customer(txtFName.Text, txtLName.Text);
objcustcake = new CustomCake(txtRadFlavour.Text, (int)numRadLayers.Value, txtRadOcc.Text,
(int)numRadSize.Value, txtRadDesign.Text);
objorder = new Order();
lblOutOrder.Text = objcustomer.ToString() + objcustcake.ToString() + objorder.ToString();
}
}
namespace CakeClasses
{
public class Cake
{
public int NumOfLayers { get; set; }
public string Flavour { get; set; }
public double Price { get; set; }
public const double CAKE_PRICE = 20;
public const int LAYER_PRICE = 3;
public Cake()
{
Flavour = "";
NumOfLayers = 0;
}
public Cake(string flavour, int numLayers)
{
NumOfLayers = numLayers;
Flavour = flavour;
}
**public virtual double CalculateCakeCost()
{
return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
}**
public override string ToString()
{
return " " + Flavour + " flavoured cake with " + NumOfLayers + " layer(s)";
}
}
}
namespace CakeClasses
{
public class Order
{
public Customer Customer { get; set; }
public Cake Cake { get; set; }
public int NumOfCakes { get; set; }
public Order()
{
Customer = new Customer();
Cake = new Cake();
NumOfCakes = 1;
}
public Order(string fName, string lName, string flavour, int numLayers, string occasion, int
diameter, string design)
{
Customer = new Customer(fName, lName);
Cake = new CustomCake(flavour, numLayers, occasion,diameter,design);
NumOfCakes = 1;
}
public Order(string fName, string lName, string flavour, int numLayers)
{
Customer = new Customer(fName, lName);
Cake = new Cake(flavour, numLayers);
NumOfCakes = 1;
}
public double CalculateCostWithTax()
{
return Cake.CalculateCakeCost() * 1.13;
}
public override string ToString()
{
return "for the total cost of " + CalculateCostWithTax().ToString("C");
}
}
}
namespace CakeClasses
{
public class CustomCake : Cake
{
public string Occasion { get; set; }
public int Size { get; set; }
public string Design { get; set; }
private double DesignCost { get; set; }
public CustomCake(string flavour, int numLayers,string occasion, int diameter, string design)
:base(flavour,numLayers)
{
Occasion = occasion;
Size = diameter;
Design = design;
switch (Design)
{
case "Polka Dots":
DesignCost = 5;
break;
case "Edible Images":
DesignCost = 12;
break;
case "Fondant Bow":
DesignCost = 10;
break;
default:
DesignCost = 15;
break;
}
}
public override double CalculateCakeCost()
{
return base.CalculateCakeCost() + Size + DesignCost;
}
public override string ToString()
{
return base.ToString() + " with " + Design + " design for " + Occasion + " occassion and
size is " + Size + " inches " ;
}
}
}
Try replacing following line in your code:
objorder = new Order();
with:
objorder = new Order("First Name","Last Name",txtRadFlavour.Text, (int)numRadLayers.Value);
Related
I'm working on webRTC connection with SFU server to make multiple p2p audio connections between unity and js clients (js <-> js, unity <-> unity, unity <-> js). So far I've made stable connections between clients and I started working on audio streaming. While I managed to make audio stream between js <-> js clients I still can't make Unity to send or receive any audio.
SFU server and js client files: Google Drive
Newtonsoft.Json for object deserialization: nuget
The code works more or less like this:
Connect to server via ws
Create local peer (Connect() => CreatePeer())
Add track to local peer (Connect())
Handle negotiation of local peer (set local description and send sdp to server)
Ask server for peer list (Subscribe())
Receive list of peer that are currently connected to server and create remote peers (HandlePeers()) and create their local descriptions
Set remote descriptions of created peers.
Code:
using System;
using UnityEngine;
using Unity.WebRTC;
using WebSocketSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections;
public class clientEnum : MonoBehaviour
{
private List<IEnumerator> threadPumpList = new List<IEnumerator>();
private WebSocket ws;
[SerializeField] private string serverURL = "ws://localhost:6969";
private string username = null;
private string localUUID = null;
private RTCPeerConnection localPeer;
private IDictionary<string, clonePeer> clients = new Dictionary<string, clonePeer>();
private IDictionary<string, RTCPeerConnection> consumers = new Dictionary<string, RTCPeerConnection>();
private RTCPeerConnection _transport;
private MediaStream _sendStream;
private MediaStream _receiveStream;
[SerializeField]
private AudioSource _audioSourceInput;
[SerializeField]
private AudioSource _audioSourceOutput;
private AudioStreamTrack track;
private string _defaulMicrophone;
private AudioClip m_clipInput;
#region payload_classes
[Serializable]
public class payload_consume
{
public string type = "consume";
public string id;
public string consumerId;
public sdp_c sdp;
}
[Serializable]
public class payload_ice_consumer
{
public string type = "consumer_ice";
public string uqid;
public string consumerId;
}
[Serializable]
public class payload_ice
{
public string type = "ice";
public ice_c ice;
public string uqid;
}
[Serializable]
public class payload_connect
{
public string type = "connect";
public sdp_c sdp;
public string uqid;
public string username;
}
[Serializable]
public class sdp_c
{
public string type = "offer";
public string sdp;
}
[Serializable]
public class ice_c
{
public string candidate;
public string sdpMid;
public string sdpMLineIndex;
public string usernameFragment;
}
#endregion
#region JSON_Classes
public class J_baptist
{
public string type { get; set; }
public string username { get; set; }
}
public class J_Witaj
{
public string type { get; set; }
public string id { get; set; }
}
public class J_Peers
{
public string type { get; set; }
public _peer[] peers { get; set; }
}
public class J_Producer
{
public string type
{
get; set;
}
public string id
{
get; set;
}
public string username
{
get; set;
}
}
public class J_Answer
{
public string type
{
get; set;
}
public sdp_class sdp
{
get; set;
}
}
public class J_user_left
{
public string type
{
get; set;
}
public string id
{
get; set;
}
}
public class J_Consume
{
public string type
{
get; set;
}
public string username
{
get; set;
}
public string id
{
get; set;
}
public string consumerId
{
get; set;
}
public sdp_class sdp
{
get; set;
}
}
public class sdp_class
{
public string type
{
get; set;
}
public string sdp
{
get; set;
}
}
#endregion
public class _peer
{
public string? consumerId { get; set; }
public string id { get; set; }
public string username { get; set; }
}
public class clonePeer
{
public string? consumerId { get; set; }
public string id { get; set; }
public string username { get; set; }
public clonePeer(string id, string username)
{
this.consumerId = null;
this.id = id;
this.username = username;
}
public clonePeer(string consumerId, string id, string username)
{
this.consumerId = consumerId;
this.id = id;
this.username = username;
}
public string toString()
{
return "{id = " + this.id + ", username = " + this.username + ", consumerId = " + this.consumerId + "}";
}
}
private IEnumerator HandleMessage(string message)
{
Debug.Log("HandleMessage: Start...");
//try
//{
if (message.Contains("\"type\":\"witaj\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, WITAJ!");
J_Witaj witaj = JsonConvert.DeserializeObject<J_Witaj>(message);
//Debug.Log("HandleMessage: Recevied message" + message);
Debug.Log("HandleMessage: Your ID: " + witaj.id);
localUUID = witaj.id;
yield return StartCoroutine(Connect());
}
if (message.Contains("\"type\":\"baptism\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, Baptism!");
J_baptist baptism = JsonConvert.DeserializeObject<J_baptist > (message);
Debug.Log("HandleMessage: Your Username:" + baptism.username);
username = baptism.username;
}
if (message.Contains("\"type\":\"peers\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, peers!");
J_Peers peers_msg = JsonConvert.DeserializeObject<J_Peers>(message);
//Debug.Log("HandleMessage: Recevied message: " + message);
yield return StartCoroutine(HandlePeers(peers_msg));
}
if (message.Contains("\"type\":\"newProducer\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, newProducer!");
J_Producer producer_msg = JsonConvert.DeserializeObject<J_Producer>(message);
//Debug.Log("HandleMessage: Recevied message " + message);
yield return StartCoroutine(HandleProducer(producer_msg));
}
if (message.Contains("\"type\":\"answer\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, answer!");
J_Answer answer_msg = JsonConvert.DeserializeObject<J_Answer>(message);
//Debug.Log("HandleMessage: Recevied message " + message);
yield return StartCoroutine(HandleAnswer(answer_msg));
}
if (message.Contains("\"type\":\"user_left\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, user_left!");
J_user_left user_left_msg = JsonConvert.DeserializeObject<J_user_left>(message);
//Debug.Log("HandleMessage: Recevied message " + message);
yield return StartCoroutine(HandleUserLeft(user_left_msg));
}
if (message.Contains("\"type\":\"consume\"") == true)
{
Debug.Log("HandleMessage: Wiadomosc zawierala, consume!");
J_Consume consume_msg = JsonConvert.DeserializeObject<J_Consume>(message);
//Debug.Log("HandleMessage: Recevied message " + message);
yield return StartCoroutine(HandleConsume(consume_msg));
}
yield break;
}
private IEnumerator HandlePeers(J_Peers peers_msg)
{
Debug.Log("HandlePeers: Starting...");
//Debug.Log(peers_msg.peers.Length);
if (peers_msg.peers.Length > 0)
{
foreach (_peer peer in peers_msg.peers)
{
Debug.Log("HandlePeers: Peer ID: " + peer.id);
clonePeer newP = new clonePeer(peer.id, peer.username);
Debug.Log("HandlePeers: New peer: " + newP.toString());
clients.Add(peer.id, newP);
yield return StartCoroutine(ConsumeOnce(newP));
}
}
else
{
Debug.Log("HandlePeers: You are alone in session...");
}
}
private IEnumerator HandleProducer(J_Producer producer)
{
if (localUUID == producer.id) yield break;
Debug.Log("HandleProducer: New user in session.");
clonePeer peer = new clonePeer(producer.id, producer.username);
clients.Add(producer.id, peer);
Debug.Log("HandleProducer: List of users: ");
foreach (var c in clients)
{
Debug.Log(c.Value.username + " -> " + c.Key);
}
yield return StartCoroutine(ConsumeOnce(peer));
}
private IEnumerator HandleAnswer(J_Answer answer)
{
Debug.Log("HandleAnswer: Starting...");
RTCSessionDescription desc = new RTCSessionDescription();
desc.sdp = answer.sdp.sdp;
yield return localPeer.SetRemoteDescription(ref desc);
}
public IEnumerator HandleUserLeft(J_user_left user_left)
{
string cId = null;
try
{
cId = clients[user_left.id].consumerId;
Debug.Log($"HandleUserLeft: User {cId} left the session");
}
catch
{
Debug.Log("HandleUserLeft: User without an Id");
}
try
{
var uN = clients[user_left.id].username;
Debug.Log($"HandleUserLeft: His username: {uN}.");
}
catch
{
Debug.Log("HandleUserLeft: User without an username");
}
if (cId != null)
{
yield return StartCoroutine(RemoveConsumer(cId));
}
clients.Remove(user_left.id);
yield break;
}
public IEnumerator RemoveConsumer(string consumerId)
{
foreach(var transceiver in consumers[consumerId].GetTransceivers())
{
if (transceiver.Receiver.Track.Id == consumerId && transceiver.Direction != RTCRtpTransceiverDirection.Stopped)
{
transceiver.Stop();
break;
}
}
foreach (var sender in consumers[consumerId].GetSenders())
{
sender.Dispose();
}
foreach (var receiver in consumers[consumerId].GetReceivers())
{
receiver.Dispose();
}
yield break;
}
public IEnumerator HandleConsume(J_Consume consume)
{
Debug.Log("HandleConsume: Starting...");
RTCSessionDescription desc = new RTCSessionDescription();
desc.sdp = consume.sdp.sdp;
try
{
consumers[consume.consumerId].SetRemoteDescription(ref desc);
Debug.Log("HandleConsume: Remote description set.");
}
catch (Exception e)
{
Debug.Log("HandleConsume: Error: " + e);
}
yield break;
}
public IEnumerator ConsumeOnce(clonePeer peer)
{
Debug.Log("ConsumeOnce: Starting...");
Debug.Log("ConsumeOnce: " + peer.id + " " + peer.username);
yield return StartCoroutine(CreateConsumerTransport(peer));
RTCPeerConnection transport = _transport;
if (transport != null)
{
sdp_c sdp = new sdp_c();
sdp.sdp = transport.LocalDescription.sdp;
payload_consume payload = new payload_consume();
payload.id = peer.id;
payload.consumerId = peer.consumerId;
payload.sdp = sdp;
string JSON = JsonUtility.ToJson(payload);
Debug.Log("ConsumeOnce: Sending message: " + JSON);
ws.Send(JSON);
} else {
Debug.Log("ConsumeOnce: Tranport is null.");
}
yield return _transport;
}
public IEnumerator CreateConsumerTransport(clonePeer peer)
{
Debug.Log("CreateConsumerTransport: Starting...");
string consumerID = peer.id;
RTCPeerConnection consumerTransport = new RTCPeerConnection();
clients[peer.id].consumerId = consumerID;
consumers.Add(consumerID, consumerTransport);
consumers[consumerID].AddTransceiver(TrackKind.Audio).Direction = RTCRtpTransceiverDirection.RecvOnly;
yield return StartCoroutine(HandleTransportNegotiation(consumers[consumerID]));
consumers[consumerID].OnIceCandidate += consumerTransport => StartCoroutine(HandleConsumerIceCandidate(consumerTransport, consumerID));
consumers[consumerID].OnTrack += (RTCTrackEvent e) => StartCoroutine(handleRemoteTrack(e));
_transport = consumerTransport;
}
public IEnumerator handleRemoteTrack(RTCTrackEvent e)
{
if (e.Track.Kind == TrackKind.Audio)
{
_receiveStream.AddTrack(e.Track);
}
yield break;
}
public IEnumerator HandleTransportNegotiation(RTCPeerConnection peer)
{
Debug.Log("HandleTransportNegotiation: Creating offer...");
var offer = peer.CreateOffer();
while(offer.Desc.sdp == null)
yield return null;
Debug.Log("HandleTransportNegotiation: Offer created: " + offer.Desc.sdp.ToString());
yield return StartCoroutine(OnTransportOfferCreateSuccess(offer.Desc, peer));
}
public IEnumerator OnTransportOfferCreateSuccess(RTCSessionDescription offer, RTCPeerConnection peer)
{
Debug.Log("OnTransportOfferCreateSuccess: Setting consumer description...");
var desc = peer.SetLocalDescription(ref offer);
yield return null;
Debug.Log("OnTransportOfferCreateSuccess: Consumer description set: " + peer.LocalDescription.sdp.ToString());
yield return desc;
}
public IEnumerator Connect()
{
Debug.Log("Connect: Starting P2P connection.");
yield return StartCoroutine(CreatePeer());
localPeer.AddTrack(track, _sendStream);
yield return StartCoroutine(Subscribe());
}
public IEnumerator CreatePeer()
{
Debug.Log("CreatePeer: Creating peer...");
var config = new RTCConfiguration();
config.iceServers = new[]{
new RTCIceServer { urls = new[] { "stun:stun.l.google.com:19302" } },
new RTCIceServer { urls = new[] { "stun:stun.stunprotocol.org:3478" } }
};
localPeer = new RTCPeerConnection(ref config);
localPeer.OnIceCandidate = (e) => StartCoroutine(HandleIceCandidate(e));
localPeer.OnNegotiationNeeded += () => StartCoroutine(HandleNegotiation(localPeer));
yield return localPeer;
}
public IEnumerator Subscribe()
{
Debug.Log("Subscribe: Starting");
yield return StartCoroutine(ConsumeAll());
yield break;
}
private IEnumerator ConsumeAll()
{
Debug.Log("ConsumeAll: Sending getPeers");
string getPeers = "{\"type\":\"getPeers\",\"uqid\":\"" + localUUID + "\"}";
Debug.Log("ConsumeAll: Sending message: " + getPeers);
ws.Send(getPeers);
yield break;
}
public IEnumerator HandleNegotiation(RTCPeerConnection peer)
{
Debug.Log("HandleNegotiation: Creating offer...");
var offer = peer.CreateOffer();
yield return offer;
Debug.Log("HandleNegotiation: Offer created: " + offer.Desc.sdp.ToString());
yield return StartCoroutine(OnOfferCreateSuccess(offer.Desc, peer));
}
public IEnumerator OnOfferCreateSuccess(RTCSessionDescription offer, RTCPeerConnection peer)
{
Debug.Log("OnOfferCreateSuccess: Setting local description...");
var desc = peer.SetLocalDescription(ref offer);
yield return desc;
Debug.Log("OnOfferCreateSuccess: Local description set: " + peer.LocalDescription.sdp.ToString());
sdp_c sdp = new sdp_c();
sdp.sdp = peer.LocalDescription.sdp.ToString();
payload_connect payload = new payload_connect();
payload.sdp = sdp;
payload.uqid = localUUID;
payload.username = username;
string JSON = JsonUtility.ToJson(payload);
Debug.Log("OnOfferCreateSuccess: Sending message: " + JSON);
ws.Send(JSON);
}
public IEnumerator HandleIceCandidate(RTCIceCandidate candidate)
{
if (candidate != null && candidate.Candidate != null && candidate.Candidate.Length > 0)
{
ice_c ice = new ice_c();
ice.candidate = candidate.Candidate;
ice.sdpMid = candidate.SdpMid;
ice.sdpMLineIndex = candidate.SdpMLineIndex.ToString();
ice.usernameFragment = candidate.UserNameFragment;
payload_ice payload = new payload_ice();
payload.ice = ice;
payload.uqid = localUUID;
string JSON = JsonUtility.ToJson(payload);
Debug.Log("HandleIceCandidate: Sending message: Sending message: " + JSON);
ws.Send(JSON);
}
yield break;
}
private IEnumerator HandleConsumerIceCandidate(RTCIceCandidate candidate, string consumentID)
{
if (candidate != null && candidate.Candidate != null && candidate.Candidate.Length > 0)
{
payload_ice_consumer ice = new payload_ice_consumer();
ice.uqid = localUUID;
ice.consumerId = consumentID;
string JSON = JsonUtility.ToJson(ice);
Debug.Log("HandleConsumerIceCandidate: Sending message: " + JSON);
ws.Send(JSON);
}
yield break;
}
void Start()
{
_defaulMicrophone = Microphone.devices[0];
Microphone.GetDeviceCaps(_defaulMicrophone, out int minFreq, out int maxFreq);
m_clipInput = Microphone.Start(_defaulMicrophone, true, 10, 44100);
_sendStream = new MediaStream();
_audioSourceInput.clip = m_clipInput;
_audioSourceInput.Play();
track = new AudioStreamTrack(_audioSourceInput);
_receiveStream = new MediaStream();
_receiveStream.OnAddTrack += OnAddTrack;
Init();
}
private void OnAddTrack(MediaStreamTrackEvent e)
{
var track = e.Track as AudioStreamTrack;
_audioSourceOutput.SetTrack(track);
_audioSourceOutput.Play();
}
private void Init()
{
Debug.Log("Init: Starting...");
ws = new WebSocket(serverURL);
ws.OnOpen += (sender, e) =>
{
Debug.Log("Connection: Connection started.");
string JSON = "{\"type\":\"user_connected_via_ws\",\"user_type\":\"UNI\"}";
ws.Send(JSON);
};
ws.OnMessage += (sender, e) =>
{
Debug.Log("Connection: Recevied message: "+ e.Data);
threadPumpList.Add(HandleMessage(e.Data));
Debug.Log("Connection: Message handled.");
};
ws.OnClose += (sender, e) =>
{
Debug.Log("Connection: Connection closed.");
ws = null;
};
ws.Connect();
}
private void Update()
{
while(threadPumpList.Count > 0)
{
StartCoroutine(threadPumpList[0]);
threadPumpList.RemoveAt(0);
}
}
}
Despite the established connection and data exchange, there is no audio transmission. I honestly don't know what I'm doing wrong and why Unity isn't sending or receiving audio stream.
Form1
public Form1()
{
InitializeComponent();
new GameSetting();
new GameSetting2();
GameTimer.Interval = 60;
GameTimer.Tick += UpdateScreen;
GameTimer.Start();
startGame();
}
private void UpdateScreen(object sender, EventArgs e)
{
if (GameSetting.Gameover == true || GameSetting2.Gameover2 == true)
{
if (KeyInput.KeyInputs(Keys.Enter))
{
startGame();
}
}
else
{
if (KeyInput.KeyInputs(Keys.Right) && GameSetting.Movment != SnakeMovment.Left)
{
GameSetting.Movment = SnakeMovment.Right;
}
else if (KeyInput.KeyInputs(Keys.Left) && GameSetting.Movment != SnakeMovment.Right)
{
GameSetting.Movment = SnakeMovment.Left;
}
else if (KeyInput.KeyInputs(Keys.Up) && GameSetting.Movment != SnakeMovment.Down)
{
GameSetting.Movment = SnakeMovment.Up;
}
else if (KeyInput.KeyInputs(Keys.Down) && GameSetting.Movment != SnakeMovment.Up)
{
GameSetting.Movment = SnakeMovment.Down;
}
PlayerMovment();
}
private void PlayerMovment()
{
for (int i = SnakeBoddy.Count - 1; i >= 0; i--)
{
if (i == 0)
{
switch (GameSetting.Movment)
{
case SnakeMovment.Right:
SnakeBoddy[i].X++;
break;
case SnakeMovment.Left:
SnakeBoddy[i].X--;
break;
case SnakeMovment.Up:
SnakeBoddy[i].Y--;
break;
case SnakeMovment.Down:
SnakeBoddy[i].Y++;
break;
}
GameSetting
class GameSetting
{
public static int Width { get; set; }
public static int Height { get; set; }
public static int SnakeSpeed { get; set; }
public static int GameScore { get; set; }
public static int GamePoint { get; set; }
public static bool Gameover { get; set; }
public static SnakeMovment Movment { get; set; }
public GameSetting()
{
Height = 16;
Width = 16;
Gameover = false;
SnakeSpeed = 60;
Movment = SnakeMovment.Down;
GamePoint = 1;
GameScore = 0;
}
}
How would I make it so that the snake speed is = to SnakeSpeed. I can do something like GameTimer.Interval = 360/GameSetting.SnakeSpeed;but that wouldn't work if I have more than 1 snake + I feel like changing the interval is not the right way, and instead of setting the speed of snake to the interval how would i set it to the snake individually?
I trying to import data from excel and for each two connected column i store the data into two dimensional list except the last column which will be in a 1D list. i wanna assign an id for each set of data the code get to be able to build a dictionary later for them.
that means for the first( valLat and valLng together ) i want to assign id = 1 and so on for each List
for (int i = 2; i <= rowCount; i++)
{
var pickLocation = new PickLocation();
var valLat = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLat]).Value;
var valLng = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
pickLocation.Lat = Convert.ToDouble(valLat);
pickLocation.Lng = Convert.ToDouble(valLng);
ListPickLocations.Add(pickLocation);
}
var setLocation = new SetLocation();
valLat = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
setLocation.Lat = Convert.ToDouble(valLat); ;
setLocation.Lng = Convert.ToDouble(valLng);
ListSetlocations.Add(setLocation);
}
var craneLocation = new CraneLocation();
valLat = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
craneLocation.Lat = Convert.ToDouble(valLat); ;
craneLocation.Lng = Convert.ToDouble(valLng);
ListCranelocations.Add(craneLocation);
}
var weight = ((Excel.Range)wks.Cells[i, 10]).Value;
if (!(weight == null))
{
Weights.Add(Convert.ToDouble(weight));
}
var clearance = ((Excel.Range)wks.Cells[2, 12]).Value;
if (!(clearance == null))
{
Clearance = clearance;
}
}
}
}
}
}
public class PickLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 4;
public static int ColumnLng { get; } = 5;
}
public class CraneLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 1;
public static int ColumnLng { get; } = 2;
}
public class SetLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 7;
public static int ColumnLng { get; } = 8;
}
I got the code of detecting poor grammar from here - Detecting Poor grammar
I am new to C# and Xamarin. I want to merge this code into my speech to text conversion app.
I tried to do it, but I am not getting the desired results.
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
namespace SpeechToText
{
[Activity(Label = "SpeechToText", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, IRecognitionListener
{
public const string Tag = "VoiceRec";
SpeechRecognizer Recognizer { get; set; }
Intent SpeechIntent { get; set; }
TextView Label { get; set; }
TextView Label1 { get; set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
Recognizer.SetRecognitionListener(this);
SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
var button = FindViewById<Button>(Resource.Id.btn);
button.Click += ButtonClick;
var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
Grammarbutton.Click += new EventHandler(ButtonClick2);
Label = FindViewById<TextView>(Resource.Id.tv);
Label1 = FindViewById<TextView>(Resource.Id.tv1);
}
private void ButtonClick(object sender, EventArgs e)
{
Recognizer.StartListening(SpeechIntent);
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches != null && matches.Count > 0)
{
Label.Text = matches[0];
}
}
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
for (; ; )
{
Console.Write("Text to check: ");
var text = Label.Text;
if (string.IsNullOrEmpty(text)) break;
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
public void OnReadyForSpeech(Bundle #params)
{
Log.Debug(Tag, "OnReadyForSpeech");
}
public void OnBeginningOfSpeech()
{
Log.Debug(Tag, "OnBeginningOfSpeech");
}
public void OnEndOfSpeech()
{
Log.Debug(Tag, "OnEndOfSpeech");
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Log.Debug("OnError", error.ToString());
}
public void OnBufferReceived(byte[] buffer) { }
public void OnEvent(int eventType, Bundle #params) { }
public void OnPartialResults(Bundle partialResults) { }
public void OnRmsChanged(float rmsdB) { }
}
}
class GingerItApi
{
public CheckResult Check(string text)
{
var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
WebResponse response = null;
try
{
response = request.GetResponse();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string data = reader.ReadToEnd();
var first = data.IndexOf('{');
var last = data.LastIndexOf('}');
var json = data.Substring(first, last - first + 1);
return JsonConvert.DeserializeObject<CheckResult>(json);
}
}
}
catch (Exception)
{
throw;
}
return null;
}
}
public class LrnFrgOrigIndx
{
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Mistake
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("CanAddToDict")]
public bool CanAddToDict { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Suggestion
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("LrnCatId")]
public int LrnCatId { get; set; }
[JsonProperty("Text")]
public string Text { get; set; }
}
public class Correction
{
[JsonProperty("Confidence")]
public int Confidence { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("LrnFrg")]
public string LrnFrg { get; set; }
[JsonProperty("LrnFrgOrigIndxs")]
public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }
[JsonProperty("Mistakes")]
public IList<Mistake> Mistakes { get; set; }
[JsonProperty("ShouldReplace")]
public bool ShouldReplace { get; set; }
[JsonProperty("Suggestions")]
public IList<Suggestion> Suggestions { get; set; }
[JsonProperty("To")]
public int To { get; set; }
[JsonProperty("TopLrnCatId")]
public int TopLrnCatId { get; set; }
[JsonProperty("Type")]
public int Type { get; set; }
[JsonProperty("UXFrgFrom")]
public int UXFrgFrom { get; set; }
[JsonProperty("UXFrgTo")]
public int UXFrgTo { get; set; }
}
public class Sentence
{
[JsonProperty("FromIndex")]
public int FromIndex { get; set; }
[JsonProperty("IsEnglish")]
public bool IsEnglish { get; set; }
[JsonProperty("ToIndex")]
public int ToIndex { get; set; }
}
public class CheckResult
{
[JsonProperty("Corrections")]
public IList<Correction> Corrections { get; set; }
[JsonProperty("Sentences")]
public IList<Sentence> Sentences { get; set; }
}
I want to get the recognized speech, send it to grammar corrector, and display the output.
Please help me to solve this, or at least help me to further research the problem.
Thank you.
You have put an infinite loop in your code. Please remove it.
For example:
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
Console.Write("Text to check: ");
var text = Label.Text;
if (!string.IsNullOrEmpty(text))
{
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Label1.Text = "Looks okay.\n";
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
And the result is:
I'm setting up a little "shop" system for a small self-teaching project. I can get it to work if I define each class argument accepted by the form, but what if I want to pass different classes with different properties?
Here is my item class, each with different properties.
public class Items
{
public int ID { get; set; }
public string ItemName { get; set; }
public int ItemType { get; set; }
public int GoldValue { get; set; }
}
public class Weapons : Items
{
public int MinDamage { get; set; }
public int MaxDamage { get; set; }
public Weapons(int id, string itemName, int itemType, int goldValue, int minDamage, int maxDamage)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
MinDamage = minDamage;
MaxDamage = maxDamage;
}
}
public class Armors : Items
{
public int Defense { get; set; }
public Armors(int id, string itemName, int itemType, int goldValue, int defense)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
Defense = defense;
}
}
public class Shields : Items
{
public int Defense { get; set; }
public Shields(int id, string itemName, int itemType, int goldValue, int defense)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
Defense = defense;
}
}
public class Potions : Items
{
public int HPHeal { get; set; }
public int MPHeal { get; set; }
public int SPHeal { get; set; }
public Potions(int id, string itemName, int itemType, int goldValue, int hpHeal, int mpHeal, int spHeal)
{
ID = id;
ItemName = itemName;
ItemType = itemType;
GoldValue = goldValue;
HPHeal = hpHeal;
MPHeal = mpHeal;
SPHeal = spHeal;
}
}
Here is my Shop form.
public partial class Shop : Form
{
Weapons item1;
Armors item2;
Shields item3;
int Gold;
public Shop(int gold, Weapons weapon1, Armors armor1, Shields shield1)
{
InitializeComponent();
item1 = weapon1;
item2 = armor1;
Gold = gold;
item1Lbl.Text = item1.ItemName + " " + item1.MinDamage + " - " + item1.MaxDamage + " Damage -- " + item1.GoldValue + " Gold";
item2Lbl.Text = item2.ItemName + " " + item2.Defense + " Defense -- " + item2.GoldValue + " Gold";
item3Lbl.Text = item3.ItemName + " " + item3.Defense + " Defense -- " + item3.GoldValue + " Gold";
}
public Shop(int gold, Potions potion1, Potions potion2, Potions potion3)
{
}
private void Shop_Load(object sender, EventArgs e)
{
}
private void buy1Btn_Click(object sender, EventArgs e)
{
if (Gold >= item1.GoldValue)
{
Equipment.ChangeWeapon(item1.ID, item1.ItemName, item1.MinDamage, item1.MaxDamage);
Equipment.Gold -= item1.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item1.GoldValue - Gold) + " additional gold.");
}
}
private void buy2Btn_Click(object sender, EventArgs e)
{
if (Gold >= item2.GoldValue)
{
Equipment.ChangeArmor(item2.ID, item2.ItemName, item2.Defense);
Equipment.Gold -= item2.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item2.GoldValue - Gold) + " additional gold.");
}
}
private void buy3Btn_Click(object sender, EventArgs e)
{
if (Gold >= item3.GoldValue)
{
Equipment.ChangeShield(item3.ID, item3.ItemName, item3.Defense);
Equipment.Gold -= item3.GoldValue;
this.Close();
}
else
{
MessageBox.Show("You need " + (item3.GoldValue - Gold) + " additional gold.");
}
}
}
What would be an efficient way to set it up so that I can pass any item type (Weapons, Armors, Potions, etc) to the same form without having to write code explicitly for each possibility?