Python入門経典練習問題の戦車大戦(簡略化版)
2718 ワード
# -*- coding: utf-8 -*-
"""
=================================
Author: keen
Created on: 2019/5/18
E-mail:[email protected]
=================================
"""
import random
class BaseTank(object):
# ,
def __init__(self):
self.live = 1
self.position = random.randint(1, 10)
self.HP = 1
self.attck_position = random.randint(1, 10)
def hit(self, other):
if self.attck_position == other.position:
other.HP -= 1
if other.HP == 0:
other.live = 0
class MyTank(BaseTank):
def move(self):
while True:
try:
#
self.position = int(input(" 【1-10】:"))
# ,
if self.position not in range(1, 11):
ex = Exception(" 1-10 ")
raise ex
else:
return self.position
#
except ValueError:
print(" !")
#
except Exception as res:
print(res)
def Bullet_launch(self):
while True:
try:
self.attck_position = int(input(" 【1-10】:"))
if self.attck_position not in range(1, 11):
ex = Exception(" 1-10 ")
raise ex
else:
return self.attck_position
except ValueError:
print(" !")
except Exception as res:
print(res)
class PcTank(BaseTank):
def move(self):
# ,
self.position = random.randint(1, 10)
def Bullet_launch(self):
self.attck_position = random.randint(1, 10)
def main():
my = MyTank()
pc = PcTank()
while True:
#
my.Bullet_launch()
pc.Bullet_launch()
# ,
my.hit(pc)
print(" => %s, %s, %s"
% (pc.position, my.attck_position, pc.HP))
if pc.live == 0:
print(" , !")
break
pc.hit(my)
print(" => %s, %s, %s"
% (my.position, pc.attck_position, my.HP))
# , 0 ,
if my.live == 0:
print(" , !")
break
my.move()
pc.move()
if __name__ == '__main__':
main()
Python自動化試験研究院:560151970(q群)
B局ホームページ:https://space.bilibili.com/403609135