私は Python (3) を学ぼうとしていますが、OOP を試してみたかったのです。私はこのプログラムを書きました。このプログラムでは、2 人のコンピュータ「プレイヤー」が「じゃんけん」をします。それはうまくいきますが、誰かが見て、私がばかげた間違いを犯したかどうか教えてくれたらいいのにと思います!
# rock.py
# example of OOP
import random
class Rock:
def main(self):
self.Make_players()
print("Best of Five - Let's play!\n")
done = False
while done == False:
self.p1.go_player()
self.p2.go_player()
print()
if self.p2.go == self.p1.go:
print("No winner!\n")
continue
else:
temp = self.check(self.p1, self.p2)
if temp == False:
temp = self.check(self.p2, self.p1)
print(self.message, end = " ")
print(temp.name + " won this round.")
temp.scored()
print(self.p1.name + ": " + str(self.p1.score))
print(self.p2.name + ": " + str(self.p2.score))
if self.p1.score == 3:
self.winner = self.p1
done = True
elif self.p2.score == 3:
self.winner = self.p2
done = True
else:
done = False
input()
print("The winner was " + self.winner.name + "!")
def __init__(self):
print("**** Welcome to Rock, Paper, Scissors!****\n")
self.winner = False
self.main()
def Make_players(self):
temp = (input("What shall we call Player 1? "))
self.p1 = Player(temp)
temp = (input("What shall we call Player 2? "))
self.p2 = Player(temp)
def check(self, p_a, p_b):
if p_a.go == "rock" and p_b.go == "scissors":
self.message = "Rock breaks scissors."
return p_a
elif p_a.go == "paper" and p_b.go == "rock":
self.message = "Paper wraps stone."
return p_a
elif p_a.go == "scissors" and p_b.go == "paper":
self.message = "Scissors cut paper."
return p_a
else:
return False
class Player:
def __init__(self, name):
self.choices = ["rock", "paper", "scissors"]
self.score = 0
self.name = name
print("Player:", self.name, "created!\n")
def go_player(self):
self.go = random.choice(self.choices)
print(self.name + " chose " + self.go, end = ". ")
return self.go
def scored(self):
self.score += 1
# Main
game = Rock()