Restanti Homework

Applicazione per il calcolo della media di tutti i numeri compresi tra due interi

Questa applicazione, sviluppata sia in C# che in VB.net, prevede l’inserimento in input di due interi, uno massimo ed uno minimo, e il calcolo della media di tutti gli interi compresi tra questi due, estremi inclusi. Vengono inoltre visualizzati separati gli interi pari e gli interi dispari generati. Il calcolo della media avviene attraverso l’algoritmo di Knuth.

Soluzione in C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CalcolaMediaC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        int PrimInt;
        int UltInt;
        int conta;
        double media;

        private void Calcola_Click(object sender, EventArgs e)
        {
            media = 0;
            conta = 0;
            PrimInt = int.Parse(this.NumPri.Text);
            UltInt = int.Parse(this.NumUlt.Text);
            if (PrimInt > UltInt)
            {
                MessageBox.Show("Inserimento non valido", "Riprova");
            }
            else
            {
                String testoP = "";
                String testoD = "";
                while (PrimInt <= UltInt)
                {
                    conta += 1;
                    media = ((conta - 1) * media + PrimInt) / conta;
                    if (PrimInt % 2 == 0)
                    {
                        testoP = String.Concat(testoP, PrimInt.ToString(), "     ");
                    }
                    else
                    {
                        testoD = String.Concat(testoD, PrimInt.ToString(), "     ");
                    }

                    if (conta % 8 == 0)
                    {
                        testoP = testoP + "\n";
                        testoD = testoD + "\n";
                    }

                    PrimInt += 1;
                }
                LabNP.Text = testoP;
                LabND.Text = testoD;
                LabMedia.Text = media.ToString();
            }
        }
    }
}

Link all’applicazione in C#.

Soluzione in VB.net

Public Class Form1
    Dim PrimInt As Integer
    Dim UltInt As Integer
    Dim Conta As Integer
    Dim Media As Double


    Private Sub Inserimento(sender As Object, e As EventArgs) Handles Calcola.Click
        Media = 0
        Conta = 0
        PrimInt = Integer.Parse(Me.NumPri.Text)
        UltInt = Integer.Parse(Me.NumUlt.Text)
        If PrimInt > UltInt Then
            MessageBox.Show("Inserimento non valido", "Riprova")

        Else
            Dim testoP As String = ""
            Dim testoD As String = ""
            While PrimInt <= UltInt
                Conta += 1
                Media = ((Conta - 1) * Media + PrimInt) / Conta
                If PrimInt Mod 2 = 0 Then
                    testoP = testoP & String.Format("{0, -12}", PrimInt.ToString)
                Else
                    testoD = testoD & String.Format("{0, -12}", PrimInt.ToString)
                End If
                If Conta Mod 8 = 0 Then
                    testoP = testoP & vbCrLf
                    testoD = testoD & vbCrLf
                End If

                PrimInt += 1
            End While
            LabNP.Text = testoP
            LabND.Text = testoD
            LabMedia.Text = Media.ToString
        End If
    End Sub
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                Calcola.PerformClick()
        End Select
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

End Class

Link all’applicazione in VB.net.

Applicazione per il calcolo della media e della varianza di tutti i numeri interi compresi tra due interi

Soluzione in C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CalcolaVarianzaC
{
    public partial class Form1 : Form
    {
        int PrimInt;
        int UltInt;
        double MediaPar;
        double MediaDis;
        double VarianzaPar;
        double VarianzaDis;
        double Cov;

        public Form1()
        {
            InitializeComponent();
        }

        private void Calcola_Click(object sender, EventArgs e)
        {
            MediaPar = 0;
            MediaDis = 0;
            VarianzaPar = 0;
            VarianzaDis = 0;
            PrimInt = int.Parse(this.NumPri.Text);
            UltInt = int.Parse(this.NumUlt.Text);
            var InteriPar = new List<int>();
            var InteriDis = new List<int>();




            if (PrimInt > UltInt)
                MessageBox.Show("Inserimento non valido", "Riprova");
            else
            {
                for (int counter = PrimInt; counter <= UltInt; counter++)
                    if (counter % 2 == 0)
                        InteriPar.Add(counter);
                    else
                        InteriDis.Add(counter);
                string testoP = StringTesto(InteriPar);
                string testoD = StringTesto(InteriDis);
                MediaPar = CalcolaMedia(InteriPar);
                MediaDis = CalcolaMedia(InteriDis);
                VarianzaPar = CalcolaVar(InteriPar);
                VarianzaDis = CalcolaVar(InteriDis);

                if (InteriDis.Count == InteriPar.Count)
                {
                    Cov = CalcolaCov(InteriPar, InteriDis);
                    LabCov.Text = (Math.Round(Cov / InteriPar.Count, 2)).ToString();
                }
                else
                    LabCov.Text = "Impossibile";


                LabNP.Text = testoP;
                LabND.Text = testoD;
                LabMedia.Text = MediaPar.ToString();
                LabMedia2.Text = MediaDis.ToString();
                LabVar.Text = (Math.Round(VarianzaPar / (double)InteriPar.Count, 2)).ToString();
                LabVar2.Text = (Math.Round(VarianzaDis / (double)InteriDis.Count, 2)).ToString();
            }
        }

        public string StringTesto(List<int> Interi)
        {
            int Filler;
            int Conta = 0;
            string Testo = "";
            while (Conta < Interi.Count())
            {
                if (Interi[Conta] < 10)
                    Filler = 12;
                else if (Interi[Conta] < 100)
                    Filler = 11;
                else
                    Filler = 10;
                Testo = Testo + string.Format("{0, -" + Filler.ToString() + "}", Interi[Conta].ToString());
                if ((Conta + 1) % 4 == 0)
                    Testo = Testo + Environment.NewLine;
                Conta += 1;
            }

            return Testo;
        }

        public double CalcolaMedia(List<int> Interi)
        {
            int Conta = 0;
            double Media = 0;
            double MediaPred = 0;
            while (Conta < Interi.Count())
            {
                MediaPred = Media;
                Media = ((Conta) * Media + Interi[Conta]) / (Conta + 1);
                Conta += 1;
            }
            return Media;
        }

        public double CalcolaVar(List<int> Interi)
        {
            double Var = 0;
            int Conta = 0;
            double Media = 0;
            double MediaPred = 0;
            while (Conta < Interi.Count())
            {
                MediaPred = Media;
                Media = ((Conta) * Media + Interi[Conta]) / (Conta + 1);
                Var = Var + (Interi[Conta] - Media) * (Interi[Conta] - MediaPred);
                Conta += 1;
            }
            return Var;
        }

        public double CalcolaCov(List<int> Int1, List<int> Int2)
        {
            double Cov = 0;
            int Conta = 0;
            double Media1 = 0;
            double Media2 = 0;
            double MediaPred1 = 0;
            double MediaPred2 = 0;
            while (Conta < Int1.Count())
            {
                MediaPred1 = Media1;
                Media1 = ((Conta) * Media1 + Int1[Conta]) / (Conta + 1);

                MediaPred2 = Media2;
                Media2 = ((Conta) * Media2 + Int2[Conta]) / (Conta + 1);

                Cov = Cov + ((Int1[Conta] - Media1) * (Int2[Conta] - MediaPred2));

                Conta += 1;
            }
            return Cov;
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }
    }
}


Link all’applicazione in C#.

Soluzione in VB.net

Public Class Form1
    Dim PrimInt As Integer
    Dim UltInt As Integer
    Dim Conta As Integer
    Dim Media As Double
    Dim MediaPred As Double
    Dim Varianza As Double
    Dim Filler As Integer


    Private Sub Inserimento(sender As Object, e As EventArgs) Handles Calcola.Click
        Media = 0
        MediaPred = 0
        Conta = 0
        Varianza = 0
        PrimInt = Integer.Parse(Me.NumPri.Text)
        UltInt = Integer.Parse(Me.NumUlt.Text)
        Dim Interi = New List(Of Integer)




        If PrimInt > UltInt Then
            MessageBox.Show("Inserimento non valido", "Riprova")

        Else
            For counter As Integer = PrimInt To UltInt
                Interi.Add(counter)
            Next
            Dim testoP As String = ""
            Dim testoD As String = ""
            While Conta < Interi.Count()
                Conta += 1
                MediaPred = Media
                Media = ((Conta - 1) * Media + Interi(Conta - 1)) / Conta
                If Interi(Conta - 1) < 10 Then
                    Filler = 12
                ElseIf Interi(Conta - 1) < 100 Then
                    Filler = 11
                Else
                    Filler = 10
                End If
                If Interi(Conta - 1) Mod 2 = 0 Then

                    testoP = testoP & String.Format("{0, -" + Filler.ToString + "}", Interi(Conta - 1).ToString)
                Else
                    testoD = testoD & String.Format("{0, -" + Filler.ToString + "}", Interi(Conta - 1).ToString)
                End If
                If Conta Mod 8 = 0 Then
                    testoP = testoP & vbCrLf
                    testoD = testoD & vbCrLf
                End If
                Varianza = Varianza + (Interi(Conta - 1) - Media) * (Interi(Conta - 1) - MediaPred)
            End While
            LabNP.Text = testoP
            LabND.Text = testoD
            LabMedia.Text = Media.ToString
            LabVar.Text = (Math.Round(Varianza / Conta, 2)).ToString

        End If
    End Sub

    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                Calcola.PerformClick()
        End Select
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

End Class

Link all’applicazione in VB.net.

Applicazione per il calcolo della media e della varianza rispettivamente di tutti i numeri pari e di tutti i dispari interi compresi tra due interi e della covarianza tra le due liste

Soluzione in C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CalcolaListeC
{
        public partial class Form1 : Form
    {
        int PrimInt;
        int UltInt;
        double MediaPar;
        double MediaDis;
        double VarianzaPar;
        double VarianzaDis;
        double Cov;

        public Form1()
        {
            InitializeComponent();
        }

        private void Calcola_Click(object sender, EventArgs e)
        {
            MediaPar = 0;
            MediaDis = 0;
            VarianzaPar = 0;
            VarianzaDis = 0;
            PrimInt = int.Parse(this.NumPri.Text);
            UltInt = int.Parse(this.NumUlt.Text);
            var InteriPar = new List<int>();
            var InteriDis = new List<int>();




            if (PrimInt > UltInt)
                MessageBox.Show("Inserimento non valido", "Riprova");
            else
            {
                for (int counter = PrimInt; counter <= UltInt; counter++)
                    if (counter % 2 == 0)
                        InteriPar.Add(counter);
                    else
                        InteriDis.Add(counter);
                string testoP = StringTesto(InteriPar);
                string testoD = StringTesto(InteriDis);
                MeidaPar = CalcolaMedia(InteriPar);
                MeidaDis = CalcolaMedia(InteriDis);
                VarianzaPar = CalcolaVarianzaC(InterPar);
                VarianzaDis = CalcolaVarianzaC(InterDis);

                if (InteriDis.Count == InteriPar.Count)
                {
                    Cov = CalcolaCov(InteriPar, InteriDis);
                    LabCov.Text = (Math.Round(Cov/InteriPar.Count,2)).ToString
                }
                else
                    LabCov.Text = "Impossibile";


                LabNP.Text = testoP;
                LabND.Text = testoD;
                LabMedia.Text = MediaPar.ToString();
                LabMedia2.Text = MediaDis.ToString();
                LabVar.Text = (Math.Round(VarianzaPar / (double)InteriPar.Count, 2)).ToString();
                LabVar2.Text = (Math.Round(VarianzaDis / (double)InteriDis.Count, 2)).ToString();
            }
        }

        public string StringTesto(List<int> Interi)
        {
            int Filler;
            int Conta = 0;
            string Testo = "";
            while (Conta < Interi.Count())
            {
                if (Interi[Conta] < 10)
                    Filler = 12;
                else if (Interi[Conta] < 100)
                    Filler = 11;
                else
                    Filler = 10;
                Testo = Testo + string.Format("{0, -" + Filler.ToString() + "}", Interi[Conta].ToString());
                if ((Conta + 1) % 4 == 0)
                    Testo = Testo + Environment.NewLine;
                Conta += 1;
            }

            return Testo;
        }

        public double CalcolaMedia(List<int> Interi)
        {
            int Conta = 0;
            double Media = 0;
            double MediaPred = 0;
            while (Conta < Interi.Count())
            {
                MediaPred = Media;
                Media = ((Conta) * Media + Interi[Conta]) / (Conta + 1);
                Conta += 1;
            }
            return Media;
        }

        public double CalcolaVar(List<int> Interi)
        {
            double Var = 0;
            int Conta = 0;
            double Media = 0;
            double MediaPred = 0;
            while (Conta < Interi.Count())
            {
                MediaPred = Media;
                Media = ((Conta) * Media + Interi[Conta]) / (Conta + 1);
                Var = Var + (Interi[Conta] - Media) * (Interi[Conta] - MediaPred);
                Conta += 1;
            }
            return Var;
        }

        public double CalcolaCov(List<int> Int1, List<int> Int2)
        {
            double Cov = 0;
            int Conta = 0;
            double Media1 = 0;
            double Media2 = 0;
            double MediaPred1 = 0;
            double MediaPred2 = 0;
            while (Conta < Int1.Count())
            {
                MediaPred1 = Media1;
                Media1 = ((Conta) * Media1 + Int1[Conta]) / (Conta + 1);

                MediaPred2 = Media2;
                Media2 = ((Conta) * Media2 + Int2[Conta]) / (Conta + 1);

                Cov = Cov + ((Int1[Conta] - Media1) * (Int2[Conta] - MediaPred2));

                Conta += 1;
            }
            return Cov;
        }
                    private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }
}

Link all’applicazione in C#.

Soluzione in VB.net

Public Class Form1
    Dim PrimInt As Integer
    Dim UltInt As Integer
    Dim MediaPar As Double
    Dim MediaDis As Double
    Dim VarianzaPar As Double
    Dim VarianzaDis As Double
    Dim Cov As Double


    Private Sub Inserimento(sender As Object, e As EventArgs) Handles Calcola.Click
        MediaPar = 0
        MediaDis = 0
        VarianzaPar = 0
        VarianzaDis = 0
        PrimInt = Integer.Parse(Me.NumPri.Text)
        UltInt = Integer.Parse(Me.NumUlt.Text)
        Dim InteriPar = New List(Of Integer)
        Dim InteriDis = New List(Of Integer)

        If PrimInt > UltInt Or PrimInt < 0 Then
            MessageBox.Show("Inserimento non valido", "Riprova")

        Else
            For counter As Integer = PrimInt To UltInt
                If counter Mod 2 = 0 Then
                    InteriPar.Add(counter)
                Else
                    InteriDis.Add(counter)
                End If

            Next
            Dim testoP As String = StringTesto(InteriPar)
            Dim testoD As String = StringTesto(InteriDis)
            MediaPar = CalcolaMedia(InteriPar)
            MediaDis = CalcolaMedia(InteriDis)
            VarianzaPar = CalcolaVar(InteriPar)
            VarianzaDis = CalcolaVar(InteriDis)

            If InteriDis.Count = InteriPar.Count Then
                Cov = CalcolaCov(InteriPar, InteriDis)
                LabCov.Text = (Math.Round(Cov / InteriPar.Count, 2)).ToString
            Else
                LabCov.Text = "Impossibile"
            End If

            LabNP.Text = testoP
            LabND.Text = testoD
            LabMediaPari.Text = MediaPar.ToString
            LabMediaDis.Text = MediaDis.ToString
            LabVarPari.Text = (Math.Round(VarianzaPar / InteriPar.Count, 2)).ToString
            LabVarDis.Text = (Math.Round(VarianzaDis / InteriDis.Count, 2)).ToString

        End If
    End Sub

    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                Calcola.PerformClick()
        End Select
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

    Public Function StringTesto(ByVal Interi As List(Of Integer)) As String

        Dim Filler As Integer
        Dim Conta As Integer = 0
        Dim Testo As String = ""
        While Conta < Interi.Count()
            If Interi(Conta) < 10 Then
                Filler = 12
            ElseIf Interi(Conta) < 100 Then
                Filler = 11
            Else
                Filler = 10
            End If
            Testo = Testo & String.Format("{0, -" + Filler.ToString + "}", Interi(Conta).ToString)
            If (Conta + 1) Mod 4 = 0 Then
                Testo = Testo & vbCrLf
            End If
            Conta += 1
        End While

        Return Testo

    End Function

    Public Function CalcolaMedia(ByVal Interi As List(Of Integer)) As Double
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Conta += 1
        End While
        Return Media
    End Function

    Public Function CalcolaVar(ByVal Interi As List(Of Integer)) As Double
        Dim Var As Double = 0
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Var = Var + (Interi(Conta) - Media) * (Interi(Conta) - MediaPred)
            Conta += 1
        End While
        Return Var

    End Function

    Public Function CalcolaCov(ByVal Int1 As List(Of Integer), ByVal Int2 As List(Of Integer)) As Double

        Dim Cov As Double = 0
        Dim Conta As Integer = 0
        Dim Media1 As Double = 0
        Dim Media2 As Double = 0
        Dim MediaPred1 As Double = 0
        Dim MediaPred2 As Double = 0
        While Conta < Int1.Count()
            MediaPred1 = Media1
            Media1 = ((Conta) * Media1 + Int1(Conta)) / (Conta + 1)

            MediaPred2 = Media2
            Media2 = ((Conta) * Media2 + Int2(Conta)) / (Conta + 1)

            Cov = Cov + ((Int1(Conta) - Media1) * (Int2(Conta) - MediaPred2))

            Conta += 1
        End While
        Return Cov

    End Function

End Class

Link all’applicazione in VB.net.

Lettura dei dati da un file .csv e calcolo delle frequenze

Soluzione in VB.net

Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.RichTextBox1.Clear()

        Dim separator As String = Me.RichTextBox2.Text.ToString
        Dim dimensioni As Integer
        Try
            dimensioni = Integer.Parse(Me.RichTextBox3.Text)
        Catch ex As Exception
            Me.RichTextBox1.Text = "Il numero di dimensioni deve essere un intero tra 1 e 2!"
            Exit Sub
        End Try

        If dimensioni < 1 Or dimensioni > 2 Then
            Me.RichTextBox1.Text = "Il numero di dimensioni deve essere un intero tra 1 e 2!"
            Exit Sub
        End If

        Dim ofd As New OpenFileDialog

        ofd.ShowDialog()

        Me.RichTextBox1.Text = "Nome scelto " & ofd.FileName

        If dimensioni = 2 Then
            Dim sr As New StreamReader(ofd.FileName)

            Dim Y As New List(Of Double)
            Dim X As New List(Of Double)
            Me.RichTextBox1.AppendText(vbCrLf & "Y    X ")
            While Not sr.EndOfStream
                Dim RigaDati As String = sr.ReadLine()
                Dim Dati() As String = RigaDati.Split(separator.ToCharArray, StringSplitOptions.RemoveEmptyEntries)

                Y.Add(Convert.ToDouble(Dati(1)))
                X.Add(Convert.ToDouble(Dati(0)))

                Me.RichTextBox1.AppendText(vbCrLf & Convert.ToDouble(Dati(1)).ToString & Convert.ToDouble(Dati(0)).ToString)

            End While

            Dim beta As Double
            Dim alfa As Double

            beta = CalcolaCov(X, Y) / CalcolaVar(X)
            alfa = CalcolaMedia(Y) - beta * CalcolaMedia(X)

            Dim Y_hat As New List(Of Double)
            Dim Epsilon As New List(Of Double)

            For conta As Integer = 0 To (Y.Count - 1)
                Dim th = alfa + beta * X(conta)
                Y_hat.Add(th)
                Epsilon.Add(Y(conta) - th)
            Next

            Dim R2 As Double
            Dim Ess As Double
            Dim Rss As Double

            Ess = CalcolaVar(Epsilon)
            Rss = CalcolaVar(Y_hat)
            R2 = Rss / CalcolaVar(Y)


            Me.RichTextBox1.AppendText(vbCrLf & "I valori della regressione sono:" & vbCrLf & "Intercetta: " & alfa.ToString & vbCrLf &
                "Coefficiente angolare: " & beta.ToString & vbCrLf & "R2: " & R2.ToString & vbCrLf & "Ess: " & Ess.ToString & vbCrLf &
                "Rss: " & Rss.ToString)

            DisegnaGrafico(X, Y)
            Y.Sort()
            X.Sort()
            Dim DistY As New ContaFreq

            DistY.Fill(Y, Y(0), ((Y(Y.Count - 1) - Y(0)) / 10))

            Dim DistX As New ContaFreq

            DistX.Fill(X, X(0), ((X(X.Count - 1) - X(0)) / 10))

            Me.RichTextBox1.AppendText(vbCrLf & "Distribuzione X")
            Me.RichTextBox1.AppendText(DistX.Stampa())
            Me.RichTextBox1.AppendText(vbCrLf & "Distribuzione Y")
            Me.RichTextBox1.AppendText(DistY.Stampa())


        End If

    End Sub

    Public Function CalcolaMedia(ByVal Interi As List(Of Double)) As Double
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Conta += 1
        End While
        Return Media
    End Function

    Public Function CalcolaVar(ByVal Interi As List(Of Double)) As Double
        Dim Var As Double = 0
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Var = Var + (Interi(Conta) - Media) * (Interi(Conta) - MediaPred)
            Conta += 1
        End While
        Return Var

    End Function

    Public Function CalcolaCov(ByVal Int1 As List(Of Double), ByVal Int2 As List(Of Double)) As Double

        Dim Cov As Double = 0
        Dim Conta As Integer = 0
        Dim Media1 As Double = 0
        Dim Media2 As Double = 0
        Dim MediaPred1 As Double = 0
        Dim MediaPred2 As Double = 0
        While Conta < Int1.Count()
            MediaPred1 = Media1
            Media1 = ((Conta) * Media1 + Int1(Conta)) / (Conta + 1)

            MediaPred2 = Media2
            Media2 = ((Conta) * Media2 + Int2(Conta)) / (Conta + 1)

            Cov = Cov + ((Int1(Conta) - Media1) * (Int2(Conta) - MediaPred2))

            Conta += 1
        End While
        Return Cov

    End Function

    Private Sub DisegnaGrafico(X As List(Of Double), Y As List(Of Double))
        'Creazione Grafico

        Dim b As New Bitmap(Me.PictureBox1.Width, Me.PictureBox1.Height)

        Dim g As Graphics = Graphics.FromImage(b)

        g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
        g.InterpolationMode = Drawing2D.InterpolationMode.High

        Dim FinestraVirtuale As New Rectangle(10, 10, Me.PictureBox1.Width - 20, Me.PictureBox1.Height - 20)

        g.Clear(Color.White)

        g.DrawRectangle(Pens.Blue, FinestraVirtuale)

        Dim MinX As Double = 0
        Dim MinY As Double = 0
        Dim MaxX As Double = 3.607
        Dim MaxY As Double = 4.737



        For h As Integer = 0 To X.Count - 1

            Dim X_graf As Integer = xVirtuale(X(h), MinX, MaxX, FinestraVirtuale)
            Dim Y_graf As Integer = yVirtuale(Y(h), MinY, MaxY, FinestraVirtuale)

            g.FillEllipse(Brushes.OrangeRed, New Rectangle(X_graf, Y_graf, 5, 5))
        Next

        Me.PictureBox1.Image = b

    End Sub

    Private Function xVirtuale(p1 As Double, MinX As Double, MaxX As Double, FinestraVirtuale As Rectangle) As Integer
        Return CInt(FinestraVirtuale.Left + (FinestraVirtuale.Width * ((p1 - MinX) / (MaxX - MinX))))
    End Function

    Private Function yVirtuale(p1 As Double, MinY As Double, MaxY As Double, FinestraVirtuale As Rectangle) As Integer
        Return CInt(FinestraVirtuale.Top + (FinestraVirtuale.Height * (1 - ((p1 - MinY) / (MaxY - MinY)))))
    End Function


End Class

Prima applicazione semi interattiva

Soluzione in VB.net

Imports System.IO
Public Class Form1

    Public Loc_MD As Point
    Public Loc_Rett As Point
    Dim FinestraVirtuale As New Rectangle(10, 10, 200, 100)
    Dim b As New Bitmap(300, 200)
    Dim g As Graphics = Graphics.FromImage(b)
    Public drag As Boolean


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.RichTextBox1.Clear()

        Dim separator As String = Me.RichTextBox2.Text.ToString
        Dim dimensioni As Integer
        Try
            dimensioni = Integer.Parse(Me.RichTextBox3.Text)
        Catch ex As Exception
            Me.RichTextBox1.Text = "Il numero di dimensioni deve essere un intero tra 1 e 2!"
            Exit Sub
        End Try

        If dimensioni < 1 Or dimensioni > 2 Then
            Me.RichTextBox1.Text = "Il numero di dimensioni deve essere un intero tra 1 e 2!"
            Exit Sub
        End If

        Dim ofd As New OpenFileDialog

        ofd.ShowDialog()

        Me.RichTextBox1.Text = "Nome scelto " & ofd.FileName

        If dimensioni = 2 Then
            Dim sr As New StreamReader(ofd.FileName)

            Dim Y As New List(Of Double)
            Dim X As New List(Of Double)
            Me.RichTextBox1.AppendText(vbCrLf & "Y    X ")
            While Not sr.EndOfStream
                Dim RigaDati As String = sr.ReadLine()
                Dim Dati() As String = RigaDati.Split(separator.ToCharArray, StringSplitOptions.RemoveEmptyEntries)

                Y.Add(Convert.ToDouble(Dati(1)))
                X.Add(Convert.ToDouble(Dati(0)))

                Me.RichTextBox1.AppendText(vbCrLf & Convert.ToDouble(Dati(1)).ToString & Convert.ToDouble(Dati(0)).ToString)

            End While

            Dim beta As Double
            Dim alfa As Double

            beta = CalcolaCov(X, Y) / CalcolaVar(X)
            alfa = CalcolaMedia(Y) - beta * CalcolaMedia(X)

            Dim Y_hat As New List(Of Double)
            Dim Epsilon As New List(Of Double)

            For conta As Integer = 0 To (Y.Count - 1)
                Dim th = alfa + beta * X(conta)
                Y_hat.Add(th)
                Epsilon.Add(Y(conta) - th)
            Next

            Dim R2 As Double
            Dim Ess As Double
            Dim Rss As Double

            Ess = CalcolaVar(Epsilon)
            Rss = CalcolaVar(Y_hat)
            R2 = Rss / CalcolaVar(Y)


            Me.RichTextBox1.AppendText(vbCrLf & "I valori della regressione sono:" & vbCrLf & "Intercetta: " & alfa.ToString & vbCrLf &
                "Coefficiente angolare: " & beta.ToString & vbCrLf & "R2: " & R2.ToString & vbCrLf & "Ess: " & Ess.ToString & vbCrLf &
                "Rss: " & Rss.ToString)

            DisegnaGrafico(X, Y)
            Y.Sort()
            X.Sort()
            Dim DistY As New ContaFreq

            DistY.Fill(Y, Y(0), ((Y(Y.Count - 1) - Y(0)) / 10))

            Dim DistX As New ContaFreq

            DistX.Fill(X, X(0), ((X(X.Count - 1) - X(0)) / 10))

            Me.RichTextBox1.AppendText(vbCrLf & "Distribuzione X")
            Me.RichTextBox1.AppendText(DistX.Stampa())
            Me.RichTextBox1.AppendText(vbCrLf & "Distribuzione Y")
            Me.RichTextBox1.AppendText(DistY.Stampa())


        End If

    End Sub

    Public Function CalcolaMedia(ByVal Interi As List(Of Double)) As Double
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Conta += 1
        End While
        Return Media
    End Function

    Public Function CalcolaVar(ByVal Interi As List(Of Double)) As Double
        Dim Var As Double = 0
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Var = Var + (Interi(Conta) - Media) * (Interi(Conta) - MediaPred)
            Conta += 1
        End While
        Return Var

    End Function

    Public Function CalcolaCov(ByVal Int1 As List(Of Double), ByVal Int2 As List(Of Double)) As Double

        Dim Cov As Double = 0
        Dim Conta As Integer = 0
        Dim Media1 As Double = 0
        Dim Media2 As Double = 0
        Dim MediaPred1 As Double = 0
        Dim MediaPred2 As Double = 0
        While Conta < Int1.Count()
            MediaPred1 = Media1
            Media1 = ((Conta) * Media1 + Int1(Conta)) / (Conta + 1)

            MediaPred2 = Media2
            Media2 = ((Conta) * Media2 + Int2(Conta)) / (Conta + 1)

            Cov = Cov + ((Int1(Conta) - Media1) * (Int2(Conta) - MediaPred2))

            Conta += 1
        End While
        Return Cov

    End Function

    Private Sub DisegnaGrafico(X As List(Of Double), Y As List(Of Double))
        'Creazione Grafico


        g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
        g.InterpolationMode = Drawing2D.InterpolationMode.High

        g.Clear(Color.White)

        g.DrawRectangle(Pens.Blue, FinestraVirtuale)

        Dim MinX As Double = 0
        Dim MinY As Double = 0
        Dim MaxX As Double = 3.607
        Dim MaxY As Double = 4.737



        For h As Integer = 0 To X.Count - 1

            Dim X_graf As Integer = xVirtuale(X(h), MinX, MaxX, FinestraVirtuale)
            Dim Y_graf As Integer = yVirtuale(Y(h), MinY, MaxY, FinestraVirtuale)

            g.FillEllipse(Brushes.OrangeRed, New Rectangle(X_graf, Y_graf, 5, 5))
        Next

        Me.PictureBox1.Image = b

    End Sub

    Private Function xVirtuale(p1 As Double, MinX As Double, MaxX As Double, FinestraVirtuale As Rectangle) As Integer
        Return CInt(FinestraVirtuale.Left + (FinestraVirtuale.Width * ((p1 - MinX) / (MaxX - MinX))))
    End Function

    Private Function yVirtuale(p1 As Double, MinY As Double, MaxY As Double, FinestraVirtuale As Rectangle) As Integer
        Return CInt(FinestraVirtuale.Top + (FinestraVirtuale.Height * (1 - ((p1 - MinY) / (MaxY - MinY)))))
    End Function

    Private Sub PictureBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
        Me.Loc_MD = e.Location

        Me.Loc_Rett = Me.FinestraVirtuale.Location

        Me.drag = False
    End Sub

    Private Sub PictureBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If Not drag Then
            Dim deltaX As Integer = e.X - Loc_MD.X

            Dim deltaY As Integer = e.Y - Loc_MD.Y

            Me.FinestraVirtuale.Location = New Point(Loc_Rett.X + deltaX, Loc_Rett.Y + deltaY)
            g.Clear(Color.White)
            g.DrawRectangle(Pens.RoyalBlue, FinestraVirtuale)
            Me.PictureBox1.Image = b
        End If
    End Sub

    Private Sub PictureBox1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        Me.drag = True
    End Sub
End Class

Link all’applicazione in VB.net.

Calcolo regressione da file .csv

Soluzione in VB.net

Imports System.IO
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.RichTextBox1.Clear()

        Dim separator As String = Me.RichTextBox2.Text.ToString

        Dim ofd As New OpenFileDialog

        ofd.ShowDialog()

        Me.RichTextBox1.Text = "Nome scelto " & ofd.FileName

        Dim sr As New StreamReader(ofd.FileName)

        Dim Y As New List(Of Double)
        Dim X As New List(Of Double)

        While Not sr.EndOfStream
            Dim RigaDati As String = sr.ReadLine()
            Dim Dati() As String = RigaDati.Split(separator)

            Y.Add(Convert.ToDouble(Dati(0)))
            X.Add(Convert.ToDouble(Dati(0)))

        End While

        Dim beta As Double
        Dim alfa As Double

        beta = CalcolaCov(X, Y) / CalcolaVar(X)
        alfa = CalcolaMedia(Y) - beta * CalcolaMedia(X)

        Dim Y_hat As New List(Of Double)
        Dim Epsilon As New List(Of Double)

        For conta As Integer = 0 To (Y.Count - 1)
            Dim th = alfa + beta * X(conta)
            Y_hat.Add(th)
            Epsilon.Add(Y(conta) - th)
        Next

        Dim R2 As Double
        Dim Ess As Double
        Dim Rss As Double

        Ess = CalcolaVar(Epsilon)
        Rss = CalcolaVar(Y_hat)
        R2 = Rss / CalcolaVar(Y)


        Me.RichTextBox1.AppendText(vbCrLf & "I valori della regressione sono:" & vbCrLf & "Intercetta: " & alfa.ToString & vbCrLf &
            "Coefficiente angolare: " & beta.ToString & vbCrLf & "R2: " & R2.ToString & vbCrLf & "Ess: " & Ess.ToString & vbCrLf &
            "Rss: " & Rss.ToString)

    End Sub

    Public Function CalcolaMedia(ByVal Interi As List(Of Double)) As Double
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Conta += 1
        End While
        Return Media
    End Function

    Public Function CalcolaVar(ByVal Interi As List(Of Double)) As Double
        Dim Var As Double = 0
        Dim Conta As Integer = 0
        Dim Media As Double = 0
        Dim MediaPred As Double = 0
        While Conta < Interi.Count()
            MediaPred = Media
            Media = ((Conta) * Media + Interi(Conta)) / (Conta + 1)
            Var = Var + (Interi(Conta) - Media) * (Interi(Conta) - MediaPred)
            Conta += 1
        End While
        Return Var

    End Function

    Public Function CalcolaCov(ByVal Int1 As List(Of Double), ByVal Int2 As List(Of Double)) As Double

        Dim Cov As Double = 0
        Dim Conta As Integer = 0
        Dim Media1 As Double = 0
        Dim Media2 As Double = 0
        Dim MediaPred1 As Double = 0
        Dim MediaPred2 As Double = 0
        While Conta < Int1.Count()
            MediaPred1 = Media1
            Media1 = ((Conta) * Media1 + Int1(Conta)) / (Conta + 1)

            MediaPred2 = Media2
            Media2 = ((Conta) * Media2 + Int2(Conta)) / (Conta + 1)

            Cov = Cov + ((Int1(Conta) - Media1) * (Int2(Conta) - MediaPred2))

            Conta += 1
        End While
        Return Cov

    End Function
End Class
Loc_MD = e.Location

        Me.Loc_Rett = Me.FinestraVirtuale.Location

        Me.drag = False
    End Sub

    Private Sub PictureBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
        If Not drag Then
            Dim deltaX As Integer = e.X - Loc_MD.X

            Dim deltaY As Integer = e.Y - Loc_MD.Y

            Me.FinestraVirtuale.Location = New Point(Loc_Rett.X + deltaX, Loc_Rett.Y + deltaY)
            g.Clear(Color.White)
            g.DrawRectangle(Pens.RoyalBlue, FinestraVirtuale)
            Me.PictureBox1.Image = b
        End If
    End Sub

    Private Sub PictureBox1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
        Me.drag = True
    End Sub
End Class

Link all’applicazione in VB.net.

Generatore di numeri casuale

Soluzione in VB.net

Link all’applicazione in VB.net.

Generatore di Random Walk

Soluzione in VB.net

Link all’applicazione in VB.net.

Secondo Homework

Applicazione avventura grafica

La seconda applicazione sviluppata consiste in una breve avventura grafica, dove l’utente si muove all’interno di un dungeon e deve sconfiggere un boss finale. Per la flessibilità della gestione dei comandi input, questa applicazione è stata sviluppata solo in VB.net. Il codice è portato qui di seguito:

Public Class Form1

    Private vita As Integer
    Private atk As Integer
    Private mana As Integer
    Private posH As Integer
    Private posV As Integer
    Private key1 As Boolean
    Private key2 As Boolean
    Private spada As Boolean
    Private poz As Boolean
    Private boss As Boolean
    Private vitaBoss As Integer
    Private atkBoss As Integer
    Private randomizer As New Random


    Private Sub startButton_Click() Handles startButton.Click
        For Each c As Control In Me.Controls
            If TypeOf c Is Panel Then
                For Each lbl As Label In c.Controls.OfType(Of Label)()
                    lbl.BackColor = Color.Black
                Next
            End If

        Next
        startButton.Enabled = False
        Timer1.Start()
        Room1.BackColor = Color.White
        p1a2.BackColor = Color.White
        Me.Room1.Text = "+"
        vita = 100
        atk = 20
        mana = 50
        posH = 1
        posV = 1
        key1 = False
        key2 = False
        spada = False
        poz = True
        boss = False
        vitaBoss = 250
        atkBoss = 30
        MoveUp.Enabled = True
        MoveDown.Enabled = True
        MoveLeft.Enabled = True
        MoveRight.Enabled = True
        ButtonA.Enabled = True
        ButtonB.Enabled = True
    End Sub

    Private Sub Posizione()
        If (posH = 1) Then
            If (posV = 1) Then
                Me.Room1.BackColor = Color.White
                Me.Room1.Text = "+"
                Me.LabInt.Text = "Sei nella stanza numero 1" & vbCrLf & "Questa stanza è vuota "
                Me.Room2.Text = ""
            ElseIf (posV = 2) Then
                Me.p2a3.BackColor = Color.White
                Me.p2a4.BackColor = Color.White
                Me.Room2.BackColor = Color.White
                Me.Room1.Text = ""
                Me.Room3.Text = ""
                Me.Room4.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 2" & vbCrLf & "Questa stanza è vuota "
                Me.Room2.Text = "+"
            ElseIf (posV = 3) Then
                Me.p3a5.BackColor = Color.White
                Me.Room3.BackColor = Color.White
                Me.Room2.Text = ""
                Me.Room5.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 3" & vbCrLf & "Questa stanza è vuota "
                Me.Room3.Text = "+"
            End If
        ElseIf (posH = 2) Then
            If (posV = 2) Then
                Me.p4a7.BackColor = Color.White
                Me.Room4.BackColor = Color.White
                Me.Room2.Text = ""
                Me.Room7.Text = ""
                If (key1) Then
                    Me.LabInt.Text = "Sei nella stanza numero 4" & vbCrLf & "Questa stanza è vuota "
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 4" & vbCrLf & "Questa stanza è vuota " & vbCrLf & "Ti serve una chiave!"
                End If
                Me.Room4.Text = "+"
            ElseIf (posV = 3) Then
                Me.Room5.BackColor = Color.White
                Me.Room3.Text = ""
                If (Not key1) Then
                    Me.LabInt.Text = "Sei nella stanza numero 5" & vbCrLf & "Hai trovato una chiave!" & vbCrLf & "A: Raccogli"
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 5" & vbCrLf & "Questa stanza è vuota"
                End If
                Me.Room5.Text = "+"
                End If
        ElseIf (posH = 3) Then
            If (posV = 2) Then
                Me.p6a7.BackColor = Color.White
                Me.p7a9.BackColor = Color.White
                Me.Room7.BackColor = Color.White
                Me.Room4.Text = ""
                Me.Room6.Text = ""
                Me.Room9.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 7" & vbCrLf & "Questa stanza è vuota "
                Me.Room7.Text = "+"
            ElseIf (posV = 1) Then
                Me.Room6.BackColor = Color.White
                Me.Room7.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 6" & vbCrLf & "Questa stanza è vuota "
                Me.Room6.Text = "+"
            End If
        ElseIf (posH = 4) Then
            If (posV = 2) Then
                Me.p8a9.BackColor = Color.White
                Me.p9a10.BackColor = Color.White
                Me.p9a11.BackColor = Color.White
                Me.Room9.BackColor = Color.White
                Me.Room7.Text = ""
                Me.Room8.Text = ""
                Me.Room10.Text = ""
                Me.Room11.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 9" & vbCrLf & "Questa stanza è vuota "
                Me.Room9.Text = "+"
            ElseIf (posV = 1) Then
                Me.Room8.BackColor = Color.White
                Me.Room9.Text = ""
                If (spada) Then
                    Me.LabInt.Text = "Sei nella stanza numero 8" & vbCrLf & "Questa stanza è vuota "
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 8" & vbCrLf & "Hai trovato una spada!" & vbCrLf & "A: Raccogli"
                End If
                Me.Room8.Text = "+"
            ElseIf (posV = 3) Then
                Me.p10a12.BackColor = Color.White
                Me.Room10.BackColor = Color.White
                Me.Room9.Text = ""
                Me.Room12.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 10" & vbCrLf & "Questa stanza è vuota "
                Me.Room10.Text = "+"
            End If
        ElseIf (posH = 5) Then
            If (posV = 2) Then
                Me.p11a12.BackColor = Color.White
                Me.p11a14.BackColor = Color.White
                Me.Room11.BackColor = Color.White
                Me.Room9.Text = ""
                Me.Room12.Text = ""
                Me.Room14.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 11" & vbCrLf & "Questa stanza è vuota "
                Me.Room11.Text = "+"
            ElseIf (posV = 3) Then
                Me.p11a12.BackColor = Color.White
                Me.p10a12.BackColor = Color.White
                Me.Room12.BackColor = Color.White
                Me.Room10.Text = ""
                Me.Room11.Text = ""
                If (Not key2) Then
                    Me.LabInt.Text = "Sei nella stanza numero 12" & vbCrLf & "Hai trovato una chiave!" & vbCrLf & "A: Raccogli"
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 12" & vbCrLf & "Questa stanza è vuota "
                End If

                Me.Room12.Text = "+"
            End If
        ElseIf (posH = 6) Then
            If (posV = 2) Then
                Me.p14a16.BackColor = Color.White
                Me.p13a14.BackColor = Color.White
                Me.Room14.BackColor = Color.White
                Me.Room11.Text = ""
                Me.Room13.Text = ""
                Me.Room16.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 14" & vbCrLf & "Questa stanza è vuota "
                Me.Room14.Text = "+"
            ElseIf (posV = 1) Then
                Me.Room13.BackColor = Color.White
                Me.Room14.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 13" & vbCrLf & "Questa stanza è vuota "
                Me.Room13.Text = "+"
            End If
        ElseIf (posH = 7) Then
            If (posV = 2) Then
                Me.p15a16.BackColor = Color.White
                Me.p16a17.BackColor = Color.White
                Me.p16a18.BackColor = Color.White
                Me.Room16.BackColor = Color.White
                Me.Room14.Text = ""
                Me.Room15.Text = ""
                Me.Room17.Text = ""
                Me.Room18.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 16" & vbCrLf & "Questa stanza è vuota "
                Me.Room16.Text = "+"
            ElseIf (posV = 1) Then
                Me.Room15.BackColor = Color.White
                Me.Room16.Text = ""
                Me.LabInt.Text = "Sei nella stanza numero 15" & vbCrLf & "Questa stanza è vuota "
                Me.Room15.Text = "+"
            ElseIf (posV = 3) Then
                Me.pFinal.BackColor = Color.LightCoral
                Me.Room17.BackColor = Color.White
                Me.Room16.Text = ""
                If (key2) Then
                    Me.LabInt.Text = "Sei nella stanza numero 17" & vbCrLf & "Questa stanza è vuota "
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 17" & vbCrLf & "Questa stanza è vuota " & vbCrLf & "Ti serve una chiave!"
                End If
                Me.Room17.Text = "+"
            ElseIf (posV = 4) Then
                Me.RoomFinal.BackColor = Color.LightCoral
                Me.Room17.Text = ""
                Me.LabInt.Text = "Stanza del boss!"
                Me.RoomFinal.Text = "+"
                FunBoss()
            End If
        ElseIf (posH = 8) Then
            If (posV = 2) Then
                Me.Room18.BackColor = Color.White
                Me.Room16.Text = ""
                If (Not poz) Then
                    Me.LabInt.Text = "Sei nella stanza numero 18" & vbCrLf & "Questa stanza è vuota "
                Else
                    Me.LabInt.Text = "Sei nella stanza numero 18" & vbCrLf & "Hai trovato una pozione!" & vbCrLf & "Può darti un bonus o un malus casuale!" & vbCrLf & "A: Bevi"
                End If
                Me.Room18.Text = "+"
            End If
        End If

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        Dim testo As String = "Vita: " & vita & vbCrLf & "Attacco : " & atk & vbCrLf & "Mana: " & mana & vbCrLf & vbCrLf & "Inventario:"
        If (key1) Then
            testo = testo & vbCrLf & "Chiave 1"
        End If
        If (key2) Then
            testo = testo & vbCrLf & "Chiave 2"
        End If
        If (spada) Then
            testo = testo & vbCrLf & "Spada"
        End If
        Me.LabStats.Text = testo
        If (Me.vita <= 0) Then
            Morto()
        End If
        If vitaBoss <= 0 Then
            Vinto()
        End If
    End Sub

    Private Sub Morto()
        Timer1.Stop()
        Me.LabInt.Text = "GAME OVER"
        MessageBox.Show("Sei morto", "Vuoi riprovare?")
        startButton.Enabled = True
        MoveUp.Enabled = False
        MoveDown.Enabled = False
        MoveLeft.Enabled = False
        MoveRight.Enabled = False
        ButtonA.Enabled = False
        ButtonB.Enabled = False

    End Sub
    Private Sub Vinto()
        Timer1.Stop()
        Me.LabInt.Text = "YOU WIN!"
        MessageBox.Show("Complimenti, hai vinto!", "Vuoi giocare di nuovo?")
        startButton.Enabled = True
        MoveUp.Enabled = False
        MoveDown.Enabled = False
        MoveLeft.Enabled = False
        MoveRight.Enabled = False
        ButtonA.Enabled = False
        ButtonB.Enabled = False

    End Sub

    Private Sub Move_Click(sender As Object, e As EventArgs) Handles MoveUp.Click, MoveDown.Click, MoveLeft.Click, MoveRight.Click

        If (posV = 1 And (posH = 1 Or posH = 3 Or posH = 4 Or posH = 6 Or posH = 7)) Then
            If (sender Is MoveUp) Then
                posV += 1
            End If
        ElseIf ((posV = 3 And posH = 2) Or (posV = 2 And posH = 8)) Then
            If (sender Is MoveRight) Then
                posH -= 1
            End If
        ElseIf (posV = 2 And posH = 1) Then
            If (sender Is MoveUp) Then
                posV += 1
            ElseIf (sender Is MoveDown) Then
                posV -= 1
            ElseIf (sender Is MoveLeft) Then
                posH += 1
            End If
        ElseIf (posV = 3 And (posH = 1 Or posH = 4)) Then
            If (sender Is MoveDown) Then
                posV -= 1
            ElseIf (sender Is MoveLeft) Then
                posH += 1
            End If
        ElseIf (posV = 2 And posH = 2) Then
            If (sender Is MoveRight) Then
                posH -= 1
            ElseIf (sender Is MoveLeft And key1) Then
                posH += 1
            End If
        ElseIf (posV = 2 And (posH = 3 Or posH = 6)) Then
            If (sender Is MoveRight) Then
                posH -= 1
            ElseIf (sender Is MoveLeft) Then
                posH += 1
            ElseIf (sender Is MoveDown) Then
                posV -= 1
            End If
        ElseIf (posV = 2 And (posH = 7 Or posH = 4)) Then
            If (sender Is MoveDown) Then
                posV -= 1
            ElseIf (sender Is MoveUp) Then
                posV += 1
            ElseIf (sender Is MoveRight) Then
                posH -= 1
            ElseIf (sender Is MoveLeft) Then
                posH += 1
            End If
        ElseIf (posH = 5 And posV = 2) Then
            If (sender Is MoveUp) Then
                posV += 1
            ElseIf (sender Is MoveRight) Then
                posH -= 1
            ElseIf (sender Is MoveLeft) Then
                posH += 1
            End If
        ElseIf (posV = 3 And posH = 5) Then
            If (sender Is MoveDown) Then
                posV -= 1
            ElseIf (sender Is MoveRight) Then
                posH -= 1
            End If
        ElseIf (posV = 3 And posH = 7) Then
            If (sender Is MoveDown) Then
                posV -= 1
            ElseIf (sender Is MoveUp And key1 And key2) Then
                posV += 1
            End If
        End If


        Posizione()


    End Sub


    Public Sub Interazione(sender As Object, e As EventArgs) Handles ButtonA.Click, ButtonB.Click

        If (posV = 3 And posH = 2) Then
            If (sender Is ButtonA) Then
                key1 = True

            End If
        ElseIf (posV = 3 And posH = 5) Then
            If (sender Is ButtonA) Then
                key2 = True
            End If
        ElseIf (posV = 1 And posH = 4 And Not spada) Then
            If (sender Is ButtonA) Then
                spada = True
                atk += 30
            End If
        ElseIf (posV = 2 And posH = 8 And poz) Then
            If (sender Is ButtonA) Then
                Dim cat As Integer
                Dim eff As Integer
                cat = randomizer.Next(1, 3)
                If (cat = 1) Then
                    eff = randomizer.Next(-20, 50)
                    vita += eff
                Else
                    eff = randomizer.Next(-5, 20)
                    atk += eff
                End If
                poz = False
            End If
        End If

        If (boss) Then
            If (sender Is ButtonA) Then
                vitaBoss -= randomizer.Next(atk - 20, atk)
                vita -= randomizer.Next(atkBoss - 15, atkBoss)
                LabInt.Text = "Vita Boss: " & vitaBoss & vbCrLf & "A: Attacca" & " B: Curati"
            End If
            If ((sender Is ButtonB) And (mana > 0)) Then
                mana -= 10
                vita += 25
                vita -= randomizer.Next(atkBoss - 30, atkBoss)
                LabInt.Text = "Vita Boss: " & vitaBoss & vbCrLf & "A: Attacca" & " B: Curati"
            ElseIf((sender Is ButtonB) And (mana <= 0)) Then
                    LabInt.Text = "Vita Boss: " & vitaBoss & vbCrLf & "Non puoi più curarti, non hai mana" & vbCrLf & " A: Attacca" & " B: Curati"

                End If
            End If

            Posizione()

    End Sub

    Public Sub FunBoss()
        MoveUp.Enabled = False
        MoveDown.Enabled = False
        MoveLeft.Enabled = False
        MoveRight.Enabled = False
        boss = True
        LabInt.Text = "Vita Boss: " & vitaBoss & vbCrLf & "A: Attacca" & " B: Curati"
    End Sub

    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Select Case keyData
            Case Keys.Up
                MoveUp.PerformClick()
            Case Keys.Down
                MoveDown.PerformClick()
            Case Keys.Right
                MoveRight.PerformClick()
            Case Keys.Left
                MoveLeft.PerformClick()
            Case Keys.A
                ButtonA.PerformClick()
            Case Keys.B
                ButtonB.PerformClick()
            Case Keys.Enter
                startButton.PerformClick()
        End Select
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

End Class

Link all’applicazione su google drive.

Primo Homework

Quiz Matematico

Il primo programma è una sorta di piccolo quiz matematico. Qui è presentato scritto sia in C# che in VB.NET. È possibile scaricare i file del codice dei due esercizi nei link presenti dopo i riquadri contenenti il codice.

Soluzione in C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HW1C
{
    public partial class Form1 : Form
    {
        // Creo oggetto chiamato randomizer che è un oggetto Random.
        Random randomizer = new Random();
        // Aggiungo variabili per il problema di somma.
        int addend1;
        int addend2;

        // Aggiungo variabili per il problema di differenza, prodotto e div.
        int sub1;
        int sub2;

        int prod1;
        int prod2;

        int div1;
        int div2;

        // Aggiungo una variabile per il timer
        int timeLeft;

        // Aggiungo il metodo StartTheQuiz() che usa il metodo Next().
        // Inizio il problema riempiendo le caselle e iniziando il timer.

        public void StartTheQuiz()
        {
            // Metto due numeri randomici nei due addendi.
            // Il valore tra parentesi è il valore massimo (non compreso).
            addend1 = randomizer.Next(51);
            addend2 = randomizer.Next(51);

            // Converto i due numeri in stringhe per mostrarli
            // nel label controls.
            plusLeftLabel.Text = addend1.ToString();
            plusRightLabel.Text = addend2.ToString();

            // Imposto il valore del controllo "sum" a 0.
            sum.Value = 0;

            // Stessa cosa per il problema della sottrazione, prod e div.
            sub1 = randomizer.Next(1, 101);
            sub2 = randomizer.Next(1, sub1);

            minusLeftLabel.Text = sub1.ToString();
            minusRightLabel.Text = sub2.ToString();

            difference.Value = 0;

            prod1 = randomizer.Next(2, 11);
            prod2 = randomizer.Next(2, 11);
            
            timesLeftLabel.Text = prod1.ToString();
            timesRightLabel.Text = prod2.ToString();
            
            prod.Value = 0;

            int temp = randomizer.Next(2,11);
            div2 = randomizer.Next(2,11);
            div1 = div2 * temp;
            
            diviedLeftLabel.Text = div1.ToString();
            diviedRightLabel.Text = div2.ToString();

            quoz.Value = 0;
            
            // Inizio il timer.
            timeLeft = 30;
            timeLabel.Text = "30 secondi";
            timer1.Start();
        }

        private bool CheckTheAnswer()
        {
            if ((addend1 + addend2 == sum.Value) 
                && (sub1-sub2 == difference.Value)
                && (prod1*prod2 == prod.Value)
                && (div1/div2 == quoz.Value))
                return true;
            else
                return false;
        }

        private void answer_Enter(object sender, EventArgs e)
        {
            // Select the whole answer in the NumericUpDown control.
            NumericUpDown answerBox = sender as NumericUpDown;

            if (answerBox != null)
            {
                int lengthOfAnswer = answerBox.Value.ToString().Length;
                answerBox.Select(0, lengthOfAnswer);
            }
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void plusLeftLabel_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void label12_Click(object sender, EventArgs e)
        {

        }

        private void startButton_Click(object sender, EventArgs e)
        {
            StartTheQuiz();
            startButton.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (CheckTheAnswer())
            {
                timer1.Stop();
                MessageBox.Show("Hai risposto bene a tutto!", "Complimenti!");
                startButton.Enabled = true;

            }
            if (timeLeft > 0)
            {
                // Cambio il nuovo tempo rimanente
                timeLeft = timeLeft - 1;
                timeLabel.Text = timeLeft + " secondi";
                if (timeLeft <= 5)
                {
                    timeLabel.BackColor = Color.Red;
                }
            }
            else
            {
                // Se il tempo finisce blocco tutto
                timer1.Stop();
                timeLabel.Text = "Tempo finito!";
                MessageBox.Show("Non hai terminato in tempo.", "Puoi riporvare però!");
                sum.Value = addend1 + addend2;
                difference.Value = sub1 - sub2;
                prod.Value = prod1 * prod2;
                quoz.Value = div1 / div2;
                startButton.Enabled = true;
            }
        }
    }
}

Link per scaricare il programma in C#.

Soluzione in VB.NET

Public Class Form1
    ' Creo un oggetto Random.
    Private randomizer As New Random

    ' Creo variabili di addizione.
    Private sum1 As Integer
    Private sum2 As Integer

    ' Creo variabili per sottrazione, prodotto e quoz
    Private min1 As Integer
    Private min2 As Integer

    Private prod1 As Integer
    Private prod2 As Integer

    Private quoz1 As Integer
    Private quoz2 As Integer

    ' Aggiungo una variabile per il timer
    Private timeLeft As Integer



    ' Aggiungo il metodo StartTheQuiz() che usa il metodo Next().
    ' Inizio il problema riempiendo le caselle e iniziando il timer.

    Public Sub StartTheQuiz()
        ' Metto due numeri randomici nei due addendi.
        sum1 = randomizer.Next(51)
        sum2 = randomizer.Next(51)

        'Metto due numeri randomici anche per sottrazione, prod e div
        min1 = randomizer.Next(1, 100)
        min2 = randomizer.Next(1, min1)

        prod1 = randomizer.Next(1, 11)
        prod2 = randomizer.Next(1, 11)

        quoz2 = randomizer.Next(1, 11)
        Dim temp As Integer = randomizer.Next(1, 11)
        quoz1 = quoz2 * temp

        plusLeftLabel.Text = sum1.ToString()
        plusRightLabel.Text = sum2.ToString()

        minusLeftLabel.Text = min1.ToString()
        minusRightLabel.Text = min2.ToString()

        prodLeftLabel.Text = prod1.ToString
        prodRightLabel.Text = prod2.ToString

        quozLeftLabel.Text = quoz1.ToString
        quozRightLabel.Text = quoz2.ToString


        sum.Value = 0
        dif.Value = 0
        prod.Value = 0
        quoz.Value = 0

        ' Inizio il timer
        timeLeft = 30
        timeLabel.Text = "30 seconds"
        Timer1.Start()

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Label5_Click(sender As Object, e As EventArgs) Handles Label5.Click

    End Sub

    Private Sub startButton_Click() Handles startButton.Click
        StartTheQuiz()
        startButton.Enabled = False
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        If CheckTheAnswer() Then
            Timer1.Stop()
            MessageBox.Show("Hai risposto bene a tutto!", "Complimenti!")
            startButton.Enabled = True
        ElseIf timeLeft > 0 Then
            timeLeft -= 1
            timeLabel.Text = timeLeft & " secondi"
            If timeLeft <= 5 Then
                timeLabel.BackColor = Color.Red
            Else
                timeLabel.BackColor = Color.White
            End If
        Else
            ' Se il tempo finisce blocco tutto
            Timer1.Stop()
            timeLabel.Text = "Tempo finito!"
            MessageBox.Show("Non hai terminato in tempo.", "Puoi riporvare però!")
            sum.Value = sum1 + sum2
            dif.Value = min1 - min2
            prod.Value = prod1 * prod2
            quoz.Value = quoz1 / quoz2
            startButton.Enabled = True
        End If
    End Sub
    Public Function CheckTheAnswer() As Boolean

        If sum1 + sum2 = sum.Value AndAlso
            min1 - min2 = dif.Value AndAlso
            prod1 * prod2 = prod.Value AndAlso
            quoz1 / quoz2 = quoz.Value Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub answer_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sum.Enter, prod.Enter, dif.Enter, quoz.Enter

        Dim answerBox = TryCast(sender, NumericUpDown)

        If answerBox IsNot Nothing Then
            Dim lengthOfAnswer = answerBox.Value.ToString().Length
            answerBox.Select(0, lengthOfAnswer)
        End If

    End Sub
End Class

Link per scaricare il programma in VB.NET.