M
M
mirindanda2021-12-18 20:23:20
Python
mirindanda, 2021-12-18 20:23:20

Inheritance and overriding, how to be?

I wrote a little code that asks users for a word and the shorter word wins. Now I want to add the same thing, only the longest word should win, only I inherit parts from the already finished code.
And now I'm trying to understand how, using inheritance and overriding, to write it beautifully and correctly, from the point of view of OOP.

import random

class Sanapeli():
    def __init__(self, kierrokset: int):
        self.voitot1 = 0
        self.voitot2 = 0
        self.kierrokset = kierrokset

    def kierroksen_voittaja(self, pelaaja1_sana: str, pelaaja2_sana: str):
        # arvotaan voittaja
        return random.randint(1, 2)

    def pelaa(self):
        print("Sanapeli:")
        for i in range(1, self.kierrokset+1):
            print(f"kierros {i}")
            vastaus1 = input("pelaaja1: ")
            vastaus2 = input("pelaaja2: ")

            if self.kierroksen_voittaja(vastaus1, vastaus2) == 1:
                self.voitot1 += 1
                print("pelaaja 1 voitti")
            elif self.kierroksen_voittaja(vastaus1, vastaus2) == 2:
                self.voitot2 += 1
                print("pelaaja 2 voitti")
            else:
                pass # tasapeli

        print("peli päättyi, voitot:")
        print(f"pelaaja 1: {self.voitot1}")
        print(f"pelaaja 2: {self.voitot2}")

p = Sanapeli(3)
p.pelaa()


Do I understand correctly that I should create a new class that will call methods from the already written code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LXSTVAYNE, 2021-12-18
@mirindanda

You have a player's victory determined by some rule. I don't know why the game logic is constantly being rewritten, if you can rewrite your own function-rule. I would write an abstract Comparator class that has a compare method with 2 parameters (words), also abstract. And from him I would inherit the following classes, already your rules for the game, how to compare words. And in your Game class, where the game logic is defined, I would pass the rules for comparing words and that's it. So you do not have to change the logic of the code, but simply write your own rules.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question