Objektorientierte Programmierung OOP -- Anwendung

hier gibt es eine längere Wiederholung zum Thema OOP.

Spiel "Rock–Paper–Scissors–Lizard–Spock"

Es handelt sich hier um eine erweiterte Version des altbekannten Spiels. Durch Hinzufügen von Lizard und Spock sinkt die Wahrscheinlichkeit gleicher Ereignisse, sodass man schneller zum Spielende kommt. Die Regeln lauten:

    Schere schneidet Papier, Papier bedeckt Stein, Stein zerquetscht Echse, Echse vergiftet Spock, Spock zertrümmert Schere, Schere köpft Echse, Echse frisst Papier, Papier widerlegt Spock, Spock verdampft Stein und Stein schleift Schere.

In Tabellenform (Spalte gegen Zeile):

RockScissorPaperMr SpockLizard
Rock X++
Scissor X++
Paper +X+
Mr Spok ++X
Lizard ++X

class Participant:
  """
  Lizard spock is a free expansion pack for the much-loved game of rock paper scissors. 
  The additional characters were added by Sam Kass and Karen Bryla before being adopted, 
  reordered, and overpopularised by The Big Bang Theory.

  The rules:

  Scissors cuts paper. Paper covers rock. Rock crushes lizard. Lizard poisons Spock. 
  Spock smashes scissors. Scissors decapitates lizard. Lizard eats paper. Paper 
  disproves Spock. Spock vaporizes rock. Rock crushes scissors.
  """
  def __init__(self, name):
    self.name = name
    self.points = 0
    self.choice = ""
  def choose(self):
    self.choice = input("{name}, select rock, paper, scissor, lizard or spock: ".format(name= self.name))
    print("{name} selects {choice}".format(name=self.name, choice = self.choice))
  def toNumericalChoice(self):
    switcher = {
      "rock":    0,
      "paper":   1,
      "scissor": 2,
      "lizard":  3,
      "spock":   4 
    }
    return switcher[self.choice]
  def incrementPoint(self):
    self.points += 1 

class GameRound:
  def __init__(self, p1, p2):
    self.rules = [
      [0, -1, 1, 1, -1],
      [1, 0, -1, -1, 1],
      [-1, 1, 0, 1, -1],
      [-1, 1, -1, 0, 1],
      [1, -1, 1, -1, 0]
    ] 

    p1.choose()
    p2.choose()
    result = self.compareChoices(p1,p2)
    print("Round resulted in a {result}".format(result = self.getResultAsString(result) ))
    if result > 0:
      p1.incrementPoint()
    elif result < 0:
      p2.incrementPoint()
    else:
      print("No points for anybody")
    
  def compareChoices(self, p1, p2):
    return self.rules[p1.toNumericalChoice()][p2.toNumericalChoice()]
  def awardPoints(self):
    print("implement")
  def getResultAsString(self, result):
    res = {
      0: "draw",
      1: "win",
      -1: "loss"
    }
    return res[result]

class Game:
  def __init__(self):
    self.endGame = False
    self.participant = Participant("Johnny Mauser")
    self.secondParticipant = Participant("Franz von Hahn")
  def start(self):
    while not self.endGame:
      GameRound(self.participant, self.secondParticipant)
      self.checkEndCondition()
      
  def checkEndCondition(self):
     answer = input("Continue game y/n: ")
     if answer == 'y':
        GameRound(self.participant, self.secondParticipant)
        self.checkEndCondition()
     else:
       print("Game ended, {p1name} has {p1points}, and {p2name} has {p2points}".format(p1name = self.participant.name, 
              p1points= self.participant.points, p2name=self.secondParticipant.name, p2points=self.secondParticipant.points))
       self.determineWinner()
       self.endGame = True
  def determineWinner(self):
    resultString = "It's a Draw"
    if self.participant.points > self.secondParticipant.points:
      resultString = "Winner is {name}".format(name=self.participant.name)
    elif self.participant.points < self.secondParticipant.points:
      resultString = "Winner is {name}".format(name=self.secondParticipant.name)
    
    print(resultString)  

game = Game()
game.start()

Eine mögliche Durchführung des Spiels wäre:

# Hinweis
Johnny Mauser, select rock, paper, scissor, lizard or spock:  paper

Johnny Mauser selects paper

Franz von Hahn, select rock, paper, scissor, lizard or spock:  lizard

Franz von Hahn selects lizard
Round resulted in a loss

Continue game y/n:  y
Johnny Mauser, select rock, paper, scissor, lizard or spock:  rock

Johnny Mauser selects rock

Franz von Hahn, select rock, paper, scissor, lizard or spock:  spock

Franz von Hahn selects spock
Round resulted in a loss

Continue game y/n:  n

Game ended, Johnny Mauser has 0, and Franz von Hahn has 2
Winner is Franz von Hahn

Da eine Interaktion vorliegt, kann das Programm hier nur mit Jupyter Lab laufen.

Brownsche Molekularbewegung

#! /usr/bin/env python
# Plot random pixels on the screen.
import pygame
import random
import os, sys

def StartPunkt():
  return MaxX//2,MaxY//2

def NeueKoordinatenBestimmen(x, y):
  x = x + random.randint(0,2)-1
  y = y + random.randint(0,2)-1   # nur nach oben
  return x,y

MaxX = 800
MaxY = 800
white = [255, 255, 255]
green = [0, 255, 0]
black = [0, 0, 0]

os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()

screen = pygame.display.set_mode((MaxX, MaxY))
screen.fill(white)
pygame.display.set_caption('Brownsche Bewegung')
pygame.display.update()
clock = pygame.time.Clock()

x,y = StartPunkt()
zufall = [random.randint(0,255),random.randint(0,255),random.randint(0,255)]

running = True
while running:
  x,y = NeueKoordinatenBestimmen(x,y)
  screen.set_at((x, y), zufall)
  pygame.display.flip()
  #   clock.tick(speed)
  if (x < 0) or (x >= MaxX-1) or y < 0 or y >= MaxY-1:
    x,y = StartPunkt()
    zufall = [random.randint(0,255),random.randint(0,255),random.randint(0,255)]
  for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            running = False
            break # break out of the for loop
    elif event.type == pygame.QUIT:
        running = False
        break # break out of the for loop

pygame.quit()
sys.exit() 

Vorherige Einheit: 10 OOP
Nächste Einheit: 12 Was es noch zu sagen gibt ...