Python :: Aufgabe #237

7 Lösungen Lösungen öffentlich

Glücksspiel Zufällige Zahl 0-9

Fortgeschrittener - Python von re_mas - 27.11.2019 um 18:30 Uhr
Die Aufgabenstellung ist wie folgt:
- Glücksspiel bei der eine random Zahl zwischen 0 - 9 erzeugt werden soll.
- Der Spieler hat ein Startkonto von 10.000 Punkten und kann damit einen beliebigen Teilbetrag auf die zufällig erzeugte Zahl setzen.
- Liegt er richtig bekommt er das 9 Fache seines Einsatzes als Gewinn
- Programmieren Sie ein entsprechendes Programm, welches die Eingaben von der Tastatur einliest und
die Ausgaben auf dem Bildschirm liefert. Die zu erratende Zahl kann durch einen verfügbaren Zufallsgenerator gezogen werden.

Lösungen:

vote_ok
von ZRX88 (2770 Punkte) - 15.12.2019 um 11:35 Uhr
Quellcode ausblenden Python-Code
'''
Created on 15.12.2019

@author: robert
'''
import random

def get_user_amount(current_amount):
    try:
        input_amount = int(input("how much do you want to bet?"))
    except:
        print("not a valid number")
        return -1
    if current_amount >= input_amount and input_amount >0:
        return input_amount
    else:
        print("invalid number")
        return -1

amount = 10000

"""
single iteration of the game
checks if valid amount is selected

"""
def game(amount):
    input_amount = -1
    while input_amount <0:
        input_amount = get_user_amount(amount)
    
    try: 
        input_number = int(input("select number 0-9?"))
    except:
        input_number = -1
        
    x = random.randint(0,9)
    if x == input_number:
        print('you won')
        print('you selected ' + str(input_number) + ' game returned ' + str(x))
        amount = amount + input_amount*9
    else:
        print("you lost")
        print('you selected ' + str(input_number) + ' game returned ' + str(x))
        amount =  amount - input_amount
        
    print("your current balance: " + str(amount))
    return amount

while amount > 0:
    amount = game(amount)
print("game over")
vote_ok
von Kotgreifer (1100 Punkte) - 17.12.2019 um 11:13 Uhr
Quellcode ausblenden Python-Code
import random
import os
clear = lambda: os.system('cls') 


points=1000
stop=False

while not stop:
    choice =500
    while not (int(choice) in range(9)):
        clear()
        choice=input("Wählen sie eine Zahl: ")
    bet=points+5
    while not (int(bet) in range(points)):
       clear()
       print("Aktuelle Punktzahl: "+str(points))
       bet=input("Dein Einsatz bitte: ")
    points-=int(bet)
    number= random.choice(range(9))
    print("Die gezogene Zahl ist: "+str(number))
    if number == int(choice):
        print("GEWONNEN!!! Du bekommst "+str(int(bet)*9)+" Punkte")
        points+=int(bet)*9
    else:
        print("Leider verloren :(")

    if 'n' == input("Nochmal spielen? (y/n): "):
        stop=True


1x
vote_ok
von jigga (4260 Punkte) - 19.01.2020 um 10:18 Uhr
Quellcode ausblenden Python-Code
import random

random.seed()
punkte = 10000

while punkte > 0:
	print()
	zahl = random.randint(0,9)

	print("Aktueller Punktestand:", punkte)
	betrag = int(input("Setze einen Betrag: "))
	inp = int(input("Zahl von 0 bis 9: "))
	
	if inp == zahl:
		punkte += 9*betrag
		print("Zahl richig erraten!")
	else:
		punkte -= betrag
		print("Leider falsch geraten")

print("\nKonto leer, Spiel vorbei")
1x
vote_ok
von Nachbar (2820 Punkte) - 29.01.2020 um 22:26 Uhr
Quellcode ausblenden Python-Code
import random

punkte = 10000

while punkte > 0:
    print("\nAktueller Punktestand: " + str(punkte))
    einsatz = int(input("Dein Einsatz: "))
    tip = int(input("Dein Tip: "))
    
    zahl = random.randint(0, 9)
    
    print()
    print(20 * "*")
    print("Gezogene Zahl: " + str(zahl))
    
    if tip == zahl:
        print("Gewonnen!")
        print(20 * "*")
        punkte = punkte + (9 * einsatz)
    else: 
        print("Leider verloren!")
        print(20 * "*")
        punkte = punkte - einsatz
        
print("\nSpiel vorbei")
vote_ok
von claas1007 (130 Punkte) - 06.02.2020 um 13:54 Uhr
Quellcode ausblenden C#-Code
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 WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        // Initialisierung

        public int iKontostand = 10000;
        Random rnd = new Random();
        public int iZahlUser;
        public int iZufallszahl;
        public int iEinsatz;
        public bool bZahlenGleich;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txt_regeln.Text = "Glücksspiel bei der eine random Zahl zwischen 0 - 9 erzeugt wird.\r\nDer Spieler hat ein Startkonto von 10.000 Punkten und kann damit einen beliebigen Teilbetrag auf die zufällig erzeugte Zahl setzen.\r\nLiegt er richtig bekommt er das 9 Fache seines Einsatzes als Gewinn.\r\n";
            txt_kontostand.Text = Convert.ToString(iKontostand);
        }

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

        private void txt_kontostand_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            iZahlUser = Convert.ToInt32(txt_zahlUser.Text);

            iZufallszahl = rnd.Next(0, 9);
            txt_zufallszahl.Text = Convert.ToString(iZufallszahl);

           vergleiche(iZufallszahl , iZahlUser);
            berechne(iKontostand);
            if (iEinsatz < 1)
            {
                this.Close();
            }
            if (iZahlUser < 0 && iZahlUser > 10)
            {
                this.Close();
            }
        }


        public bool vergleiche(int zahl1, int zahl2)
        {
           
            if (zahl1 == zahl2)
            {
                bZahlenGleich = true;
            }
            else
            {
                bZahlenGleich = false;
            }
            return bZahlenGleich;
        }


        public int berechne(int zahl1)
        {
            if (bZahlenGleich)
            {
                iEinsatz = Convert.ToInt32(txt_einsatz.Text);
                iKontostand = iKontostand + (iEinsatz * 9);
                txt_endeSpiel.Text = "gewonnen";
            }
            else
            {
                iEinsatz = Convert.ToInt32(txt_einsatz.Text);
                iKontostand = iKontostand - iEinsatz;
                if (iKontostand <= 0)
                {
                    MessageBox.Show("Sie haben verloren\nKontostand < 0");
                    this.Close();
                }
                txt_endeSpiel.Text = "verloren";
            }
            txt_kontostand.Text = Convert.ToString(iKontostand);

            return iKontostand;
        }
    }
}


namespace WindowsFormsApplication8
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txt_regeln = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.txt_einsatz = new System.Windows.Forms.TextBox();
            this.txt_zahlUser = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.txt_zufallszahl = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.txt_kontostand = new System.Windows.Forms.TextBox();
            this.txt_endeSpiel = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18.14286F);
            this.label1.ForeColor = System.Drawing.Color.Black;
            this.label1.Location = new System.Drawing.Point(263, 29);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(464, 51);
            this.label1.TabIndex = 0;
            this.label1.Text = "Glücksspiel Zufallszahl";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.label2.Location = new System.Drawing.Point(22, 152);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(115, 33);
            this.label2.TabIndex = 1;
            this.label2.Text = "Regeln:";
            // 
            // txt_regeln
            // 
            this.txt_regeln.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.14286F);
            this.txt_regeln.Location = new System.Drawing.Point(177, 152);
            this.txt_regeln.Multiline = true;
            this.txt_regeln.Name = "txt_regeln";
            this.txt_regeln.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
            this.txt_regeln.Size = new System.Drawing.Size(841, 190);
            this.txt_regeln.TabIndex = 2;
            this.txt_regeln.TextChanged += new System.EventHandler(this.txt_regeln_TextChanged);
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.label3.Location = new System.Drawing.Point(22, 389);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(119, 33);
            this.label3.TabIndex = 3;
            this.label3.Text = "Einsatz:";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.label4.Location = new System.Drawing.Point(-1, 463);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(138, 33);
            this.label4.TabIndex = 4;
            this.label4.Text = "Ihre Zahl:";
            // 
            // txt_einsatz
            // 
            this.txt_einsatz.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.txt_einsatz.Location = new System.Drawing.Point(177, 389);
            this.txt_einsatz.Name = "txt_einsatz";
            this.txt_einsatz.Size = new System.Drawing.Size(346, 40);
            this.txt_einsatz.TabIndex = 5;
            // 
            // txt_zahlUser
            // 
            this.txt_zahlUser.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.txt_zahlUser.Location = new System.Drawing.Point(177, 463);
            this.txt_zahlUser.Name = "txt_zahlUser";
            this.txt_zahlUser.Size = new System.Drawing.Size(346, 40);
            this.txt_zahlUser.TabIndex = 6;
            // 
            // button1
            // 
            this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F);
            this.button1.Location = new System.Drawing.Point(-2, 524);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(139, 48);
            this.button1.TabIndex = 7;
            this.button1.Text = "Zufallszahl:";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // txt_zufallszahl
            // 
            this.txt_zufallszahl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.14286F);
            this.txt_zufallszahl.Location = new System.Drawing.Point(177, 532);
            this.txt_zufallszahl.Name = "txt_zufallszahl";
            this.txt_zufallszahl.Size = new System.Drawing.Size(346, 40);
            this.txt_zufallszahl.TabIndex = 8;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 18.14286F);
            this.label5.Location = new System.Drawing.Point(671, 385);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(253, 51);
            this.label5.TabIndex = 9;
            this.label5.Text = "Kontostand:";
            // 
            // txt_kontostand
            // 
            this.txt_kontostand.Font = new System.Drawing.Font("Microsoft Sans Serif", 18.14286F);
            this.txt_kontostand.Location = new System.Drawing.Point(673, 475);
            this.txt_kontostand.Name = "txt_kontostand";
            this.txt_kontostand.Size = new System.Drawing.Size(251, 55);
            this.txt_kontostand.TabIndex = 10;
            this.txt_kontostand.TextChanged += new System.EventHandler(this.txt_kontostand_TextChanged);
            // 
            // txt_endeSpiel
            // 
            this.txt_endeSpiel.Font = new System.Drawing.Font("Microsoft Sans Serif", 18.14286F);
            this.txt_endeSpiel.Location = new System.Drawing.Point(38, 642);
            this.txt_endeSpiel.Multiline = true;
            this.txt_endeSpiel.Name = "txt_endeSpiel";
            this.txt_endeSpiel.Size = new System.Drawing.Size(928, 161);
            this.txt_endeSpiel.TabIndex = 11;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1079, 939);
            this.Controls.Add(this.txt_endeSpiel);
            this.Controls.Add(this.txt_kontostand);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.txt_zufallszahl);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.txt_zahlUser);
            this.Controls.Add(this.txt_einsatz);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.txt_regeln);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txt_regeln;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox txt_einsatz;
        private System.Windows.Forms.TextBox txt_zahlUser;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox txt_zufallszahl;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.TextBox txt_kontostand;
        private System.Windows.Forms.TextBox txt_endeSpiel;
    }
}

1 Kommentar
vote_ok
von Squalen (60 Punkte) - 11.06.2020 um 14:34 Uhr
Quellcode ausblenden Python-Code
print("Glücksspiel:")
import pickle
import random
aktiv = True
punkte = 10000
file = open('Spielerpunkte', 'wb')
pickle.dump(punkte, file)
file.close()
while aktiv:
    zufallszahl = random.randint(0,9)
    print(zufallszahl)
    file = open('Spielerpunkte', 'rb')
    punkte = pickle.load(file)
    file.close()
    print("Deine Punkte:", punkte)
    einsatz = input("Einsatz:")
    if einsatz == "exit":
        break
    eingabe = input("Ihre Zahl:")
    if eingabe == "exit":
        break
    einsatz = int(einsatz)
    eingabe = int(eingabe)
    punkte = punkte - einsatz
    if eingabe == zufallszahl:
        einsatz1 = einsatz * 9
        punkte = einsatz1 + punkte
        print("Richtig, Sie haben", einsatz1, "Punkte gewonnen")
    else:
        print("Falsch, Sie haben", einsatz, "Punkte verloren")
    file = open('Spielerpunkte', 'wb')
    pickle.dump(punkte, file)
    file.close()
    if punkte == 0:
        print("Sie haben keine Punkte mehr übrig.")
        break

vote_ok
von Ahzul (50 Punkte) - 12.08.2021 um 20:36 Uhr
Quellcode ausblenden Python-Code
import random


class Player:
    __balance = None
    __pot = None

    def __init__(self, balance):
        self.__balance = balance
        self.__pot = 0

    def get_balance(self):
        return self.__balance

    def set_balance(self, balance):
        self.__balance = balance

    def __bet(self, amount):
        self.__pot += amount
        self.__balance -= amount

    def __win(self):
        self.__balance += (9 * self.__pot)
        self.__pot = 0

    def lose(self):
        self.__pot = 0

    def print_player_info(self):
        print(f'-----------------------------------\n'
              f'Balance:\t{self.__balance} points\n')

    def game(self):
        number = random.randint(0, 9)
        try:
            bet = int(input("Bet:\n"))
            print(f'Bet is:\t{bet} points')
        except ValueError:
            print("Invalid bet\n")
            return
        if self.__balance >= bet:
            try:
                guess = int(input("Guess number from 0-9!\n"))
                print(f'\nYour Guess:\t{guess}\n'
                      f'correct number:\t{number}\n')
            except ValueError:
                print("Invalid Guess\n")
                return
            if 0 <= guess <= 9:
                self.__bet(bet)
                if guess == number:
                    self.__win()
                    print("WINNER WINNER!")
                    self.print_player_info()
                else:
                    print("Loser!")
                    self.print_player_info()
            else:
                print("Guess is not Valid!")
        else:
            print("Bet is not Valid!")


def options(var_player):

    if player.get_balance() == 0:
        print("You don't have any points!")
    else:
        option = input("-----------------------------------\n"
                       "Would you like to play again?\n"
                       "-y for yes\n"
                       "-n for no\n"
                       "-show_info for balance info!\n"
                       "-----------------------------------\n")
        if option == 'y':
            return True
        elif option == 'n':
            return False
        elif option == 'show_info':
            var_player.print_player_info()
            return options(var_player)
        elif option == 'exit':
            quit()
        else:
            print("Invalid Option!")
            return options(var_player)


if __name__ == '__main__':
    player = Player(10000)
    play_again = True
    while play_again:
        player.game()
        play_again = options(player)



with python 3.9
1801090

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.