def __init__(self, health, mana, name="Baron", title="Dragonslayer", mana_regeneration_rate=2): Man.__init__(health, mana) self.__mana_regeneration_rate = mana_regeneration_rate self.__name = name self.__title = title self.__weapon = None self.__spell = None
def run_game(): pg.init() gallow = Gallow() man = Man() settings = Settings() screen = pg.display.set_mode( (settings.screen_width, settings.screen_height)) pg.display.set_caption("Hangman") while True: for event in pg.event.get(): gf.check_events(event) screen.fill(settings.screen_color) answer = "HELLO" string = "" gf.print_empty_game_board(screen) man.draw_entire_man(screen) gallow.draw_structure(screen) pg.display.flip()
def test_1(self): with patch('man.Watch') as mock_watch: mock_dt = MagicMock() mock_dt.strftime.return_value = '01:05 pm' mock_watch.return_value.get_time.return_value = mock_dt man = Man() self.assertEqual(man.tell_time(), 'It is now 01:05 pm') mock_dt.strftime.assert_called_once_with('%I:%M %p')
def test_1(self, mock_watch): # Create a fake datetime object mock_dt = MagicMock() mock_dt.strftime.return_value = '01:05 pm' # Have watch always return that fake object mock_watch.return_value.get_time.return_value = mock_dt man = Man() self.assertEquals(man.tell_time(), 'It is now 01:05 pm') mock_dt.strftime.assert_called_once_with('%I:%M %p')
def __init__(self, w=WIDTH, h=HEIGHT): self.w = w self.h = h self.display = pygame.display.set_mode((self.w, self.h)) pygame.display.set_caption('BLOCKS_AI') self.drone = Drone(20, RED) self.man = Man(20, BLUE1) self.reset() self.clock = pygame.time.Clock() self.time = 0
def __init__(self,player_name,baoku_name): self.player_name = player_name self.baoku_name = baoku_name # 创建一个game用户 self.player = Man(self.player_name) # 创建一个宝库 self.baoku = Baoku(self.baoku_name) self.baoku_list = [] # 填充宝库 self.baoku_list = self.baoku.baoku_tianchong() # 创建一个商店 self.shangdian = Shop() self.cjks = Cj(self.player.money) str_ = '%s开启了%s之旅'%(self.player_name,self.baoku_name) flush_str(str_,0.02)
def run_game(): #Initialize the game and create a screen object pygame.init() game_settings = Settings() screen = pygame.display.set_mode( (game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption('Letters Killer') #Intialize the statistics stats = Stats(game_settings) #Initialize all the sounds in need sounds = Sound(game_settings) #Initialize the falling targets targets = Group() #Initialize an aim aim = Aim(screen, game_settings) #Initialize a button button = Button(screen, game_settings) #Initialize the title title = Title(screen, game_settings) #Initialize the big man man = Man(screen, game_settings) while True: #Create a target with random value gf.create_targets(screen, game_settings, targets) #Check the events and responds gf.check_events(targets, game_settings, stats, button, aim, sounds, title) #Update the screen gf.update_screen(screen, game_settings, stats, button, targets, aim, title)
class GameAI: def __init__(self, w=WIDTH, h=HEIGHT): self.w = w self.h = h self.display = pygame.display.set_mode((self.w, self.h)) pygame.display.set_caption('BLOCKS_AI') self.drone = Drone(20, RED) self.man = Man(20, BLUE1) self.reset() self.clock = pygame.time.Clock() self.time = 0 def reset(self): self.drone_x, self.drone_y = self.drone.place_drone(self.h, self.w) self.man_x, self.man_y = self.man.place_man(self.drone_x, self.drone_y, self.h, self.w) self.frame_iteration = 0 #print(self.drone_x, self.drone_y, self.man_x, self.man_y) # return drone_x, drone_y, man_x, man_y def play_step(self, action): self.frame_iteration += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() #print(self.drone_x, self.drone_y) self.drone_x, self.drone_y = self.drone.drone_move(self.drone_x, self.drone_y, move_distace=20, choice=action) #print(self.drone_x, self.drone_y) # TODO move man game_over = False self.reward, game_over = self.get_reward(game_over) self.update_ui() self.clock.tick(60) return self.reward, game_over def is_drone_outside(self, drone_x, drone_y): if drone_x > self.w - BLOCK_SIZE or drone_x < 0 or drone_y > self.h - BLOCK_SIZE or drone_y < 0: return True return False def is_man_outside(self, man_x, man_y): if man_x > self.w - BLOCK_SIZE or man_x < 0 or man_y > self.h - BLOCK_SIZE or man_y < 0: return True return False def get_reward(self, game_over): # print(self.drone_x, self.drone_y, self.man_x, # self.man_y, self.frame_iteration, game_over) if self.is_drone_outside( self.drone_x, self.drone_y) or self.is_man_outside( self.man_x, self.man_y) or self.frame_iteration > 200: game_over = True self.reward = -300 return self.reward, game_over elif self.drone_x == self.man_x and self.drone_y == self.man_y: game_over = True self.reward = 1000 return self.reward, game_over else: game_over = False self.reward = -1 return self.reward, game_over def update_ui(self): self.clock.tick(10) self.display.fill(BLACK) pygame.draw.rect( self.display, self.man.color, pygame.Rect(self.man_x, self.man_y, self.man.size, self.man.size)) pygame.draw.rect( self.display, self.drone.color, pygame.Rect(self.drone_x, self.drone_y, self.drone.size, self.drone.size)) pygame.display.flip()
def __init__(self): self.ManList = [Man('Tom'), Man('Jack')] self.DogList = [Dog('Alice'), Dog('Black'), Dog('Jerry')] self.Flag = 0 self.ROUND = 1
def GetMan(): if 'man' not in g: g.man = Man() return g.man
def editMan(self, id, age, name): return Man.update({ Man.age: age, Man.name: name }).where(Man.id == id).execute() != 1
def removeMan(self, id): entity = Man.get(Man.id == id) entity.delete_instance()
def run_game(): ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) # 设置屏幕长宽 monster_image = IMAGESDICT['monster_im'] monster_rect = monster_image.get_rect() # 获取monster的矩形 monster_rect.bottom = 500 # 设置monster初始位置 monster_rect.right = 50 # 设置monster初始位置 speed = [1, 1] # monster的速度:水平速度为1,竖直速度为1 # 用不同的名词替代class定义的类 man = Man(screen) man_2 = Man_2(screen) initial_ordinary = Initial_Ordinary(ai_settings, screen, man) ordinary_1 = Ordinary_1(screen) ordinary_2 = Ordinary_2(screen) ordinary_3 = Ordinary_3(screen) macadam_2 = Macadam_2s(screen) conveyer = Conveyers(screen) stick = Stick(screen) # 两个玩家的初始成绩为0 score_1 = 0 score_2 = 0 pygame.mixer.music.play(-1, 0.0) while True: monster_rect = monster_rect.move(speed) # 让monster的位置根据speed移动 if (monster_rect.left < 0) or (monster_rect.right > 400): # 如果monster在水平位置上超出屏幕范围,那么monster的运动方向相反 speed[0] = -speed[0] if (monster_rect.bottom > 600) or (monster_rect.top < 0): # 如果monster在竖直方向上超出了屏幕范围,那么monster的运动方向相反 speed[1] = -speed[1] screen.blit(monster_image, monster_rect) # 让屏幕更新monster的状态 if man.rect.y < 600 or man_2.rect.y < 600: # 如果玩家1和玩家2还没有触碰到屏幕顶端,则游戏继续 if man.rect.y < 600 and man_2.rect.y < 600: score_1 += 0.01 * PARAMETER['coefficient'] score_2 += 0.01 * PARAMETER['coefficient'] elif man.rect.y < 600 and man_2.rect.y > 600: # 如果玩家2触及屏幕顶端,则玩家2死亡,玩家1继续 score_1 += 0.01 * PARAMETER['coefficient'] score_2 += 0 elif man.rect.y > 600 and man_2.rect.y < 600: # 如果玩家1触碰到屏幕顶端,则玩家1死亡,玩家2继续 score_1 += 0 score_2 += 0.01 * PARAMETER['coefficient'] gf.check_events(ai_settings, screen, man, man_2, score_1, score_2) man.update_wid() # 更新玩家1的左右位置 man_2.update_wid() # 更新玩家2的左右位置 man.update_hei(initial_ordinary) # 更新玩家1在初始障碍上运动的竖直位置 man_2.update_hei(initial_ordinary) # 更新玩家2在初始障碍上运动的竖直位置 initial_ordinary.update_hei() # 更新初始障碍的位置 ordinary_1.update_hei(screen) # 更新第一个普通障碍的位置 ordinary_2.update_hei(screen) # 更新第二个普通障碍的位置 ordinary_3.update_hei(screen) # 更新第三个普通障碍的位置 macadam_2.update_hei(screen) # 更新碎石障碍的位置 conveyer.update_hei(screen) # 更新传送带的位置 man_2.update_hei_1(initial_ordinary, ordinary_1, ordinary_2, ordinary_3, macadam_2, conveyer, monster_rect) # 更新玩家2与普通障碍、碎石、传送带上运动的竖直位置 man_2.update_stick(stick) # 更新玩家2与刺的相对位置 man.update_hei_1(initial_ordinary, ordinary_1, ordinary_2, ordinary_3, macadam_2, conveyer, monster_rect) # 更新玩家1与普通障碍、碎石、传送带上运动的竖直位置 man.update_stick(stick) # 更新玩家1与刺的相对位置 macadam_2.check_collide(screen, man, man_2) # 检查玩家与碎石是否碰撞 gf.update_screen(ai_settings, screen, man, man_2, initial_ordinary, ordinary_1, ordinary_2, ordinary_3, macadam_2, conveyer, stick) else: # 如果玩家1和玩家2都死亡,则出现GAME OVER字样 score_1 += 0 score_2 += 0 gf.check_events(ai_settings, screen, man, man_2, score_1, score_2) gf.drawText_1('GAME OVER', font, screen, (ai_settings.screen_width / 3), (ai_settings.screen_height / 3)) pygame.display.update() pygame.mixer.music.stop() gameOverSound.play() time.sleep(3) score_1 = int(score_1) score_2 = int(score_2) Scorewinwid = 500 Scorewinhei = 150 TEXTCOLOR = (255, 255, 255) BACKGROUNDCOLOR = (0, 0, 0) pygame.init() # 固定屏幕位置 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ( (SCREENWIDTH - Scorewinwid) / 2, (SCREENHEIGHT - Scorewinhei) / 2) ScoreWindow = pygame.display.set_mode((Scorewinwid, Scorewinhei)) pygame.display.set_caption('Score Save') BASICFONT = pygame.font.Font('Comici.ttf', 20) gf.drawText_1("Do you want to save this score?", BASICFONT, ScoreWindow, (Scorewinwid / 3), (Scorewinhei / 3) - 10) gf.drawText_1("If yes, please press Y !", BASICFONT, ScoreWindow, (Scorewinwid / 3), (Scorewinhei / 3 + 15)) gf.drawText_1("If no, please press N !", BASICFONT, ScoreWindow, (Scorewinwid / 3), (Scorewinhei / 3 + 40)) pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_n: sys.exit() elif event.key == pygame.K_y: score_1 = int(score_1) stu1 = ["a", score_1] out_1 = open('Stu1_csv.csv', 'a', newline="") csv_write = csv.writer(out_1, dialect='excel') csv_write.writerow(stu1) print("write over") filename = 'Stu1_csv.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) print(header_row) for index, column_header in enumerate(header_row): print(index, column_header) scores_1 = [score_1] for row in reader: new_score = int(row[1]) scores_1.append(new_score) scores_1.remove(score_1) scores_1.append(score_1) print(scores_1) score_2 = int(score_2) stu2 = ["b", score_2] out_2 = open('Stu2_csv.csv', 'a', newline="") csv_write = csv.writer(out_2, dialect='excel') csv_write.writerow(stu2) print("write over") filename_2 = 'Stu2_csv.csv' with open(filename_2) as f: reader = csv.reader(f) header_row = next(reader) print(header_row) for index, column_header in enumerate(header_row): print(index, column_header) scores_2 = [score_2] for row in reader: new_score_2 = int(row[1]) scores_2.append(new_score_2) scores_2.remove(score_2) scores_2.append(score_2) print(scores_2) from matplotlib import pyplot as plt fig = plt.figure(dpi=128, figsize=(3, 2)) plt.plot(scores_1, c='red', label="score 1") plt.plot(scores_2, c='gray', label="score 1") plt.title("Score", fontsize=18) plt.xlabel = ('') plt.ylabel = ('score') plt.tick_params(axis='both', which='major', labelsize=16) plt.legend(loc=9) plt.savefig('scoreshow.png', bbox_inches='tight') top_score_1 = max(scores_1) top_score_2 = max(scores_2) if top_score_1 > top_score_2: winner = 'Player 1' elif top_score_1 < top_score_2: winner = 'Player 2' else: winner = 'Player 1 and Player 2' WINDOWWIDTH = 800 WINDOWHEIGHT = 600 pygame.init() # 固定屏幕位置 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ( (SCREENWIDTH - WINDOWWIDTH) / 2, (SCREENHEIGHT - WINDOWHEIGHT) / 2) windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Score Show') DISPLAYSURF.fill(BGCOLOR) BASICFONT_1 = pygame.font.Font('Comici.ttf', 38) BASICFONT_2 = pygame.font.Font('Comici.ttf', 28) gf.drawText_2(winner, BASICFONT_1, windowSurface, 330, 130) gf.drawText_2("Player 1's current score is " + str(score_1), BASICFONT_2, windowSurface, 225, 200) gf.drawText_2("Player 2's current score is " + str(score_2), BASICFONT_2, windowSurface, 225, 250) Scoreimage = {'show': pygame.image.load('scoreshow.png'), 'top': pygame.image.load('huizhang.jpg'), 'title': pygame.image.load('winner.png')} SHRect_1 = Scoreimage['show'].get_rect() image_position = 300 SHRect_1.top = image_position SHRect_1.centerx = HALF_WINWIDTH image_position += SHRect_1.height windowSurface.blit(Scoreimage['show'], SHRect_1) SHRect_2 = Scoreimage['title'].get_rect() image_position = 50 SHRect_2.top = image_position SHRect_2.centerx = HALF_WINWIDTH image_position += SHRect_2.height windowSurface.blit(Scoreimage['title'], SHRect_2) SHRect_3 = Scoreimage['top'].get_rect() image_position = 46 SHRect_3.top = image_position SHRect_3.centerx = 346 image_position += SHRect_3.height windowSurface.blit(Scoreimage['top'], SHRect_3) pygame.display.flip() time.sleep(10) return break gf.update_screen(ai_settings, screen, man, man_2, initial_ordinary, ordinary_1, ordinary_2, ordinary_3, macadam_2, conveyer, stick)
from man import Man from boy import Boy from kid import Kid def atThePark(man): print("In the park") man.play() man = Man() boy = Boy() kid = Kid() boy.play() boy.walk() boy.eat() kid.play() atThePark(man) atThePark(kid) atThePark(boy)
class Foo(unittest.TestCase): def test_1(self): self.man = Man() print self.man.tell_time()
def test_1(self): self.man = Man() print self.man.tell_time()
def createNewMan(self, name, age): return Man.create(name=name, age=age)
def getPeople(self, min, max, pattern): peopleData = Man.select().where( Man.age.between(min, max) & (pattern == '' or Man.name.contains(pattern))) return [{"name": m.name, "age": m.age, "id": m.id} for m in peopleData]
self._many = 2 self._last_many = self._many def move_left(self): if self._manx >= 2: self._manx -= 2 def gravity(self): if self._many < 45: self._last_many = self._many - 6 self._many += 1 if self._last_many < 2: self._last_many = 2 obj1 = Pxl("dawn.jpg") pixel_values = obj1.getpx() obj2 = Man() mtr = obj2.getman() obj3 = Board(pixel_values, mtr, 3, 45) grid = obj3.Binit() obj3.obstacles() obj3.coins() obj3.stick_life() # manx=3 # many=45 # thread1=threading.Thread(target=printBoard,daemon=True,args=) flag = 0 flag1 = 0 if (flag == 0 and flag1 == 0): while True:
class Wabao_chushihua(): def __init__(self,player_name,baoku_name): self.player_name = player_name self.baoku_name = baoku_name # 创建一个game用户 self.player = Man(self.player_name) # 创建一个宝库 self.baoku = Baoku(self.baoku_name) self.baoku_list = [] # 填充宝库 self.baoku_list = self.baoku.baoku_tianchong() # 创建一个商店 self.shangdian = Shop() self.cjks = Cj(self.player.money) str_ = '%s开启了%s之旅'%(self.player_name,self.baoku_name) flush_str(str_,0.02) def game_main(self): '''游戏主程序''' try : while True: # 挖宝主体程序 time.sleep(0.8) os.system('cls') # ctrl + c f = self.player.dig(self.baoku_list) # 如果宝库空了,游戏推出 if len(self.baoku_list) == 0: print('宝库被你挖空了') break self.player.cangku = f[0] self.player.tili = f[1] print("|>> 当前剩余体力为%d"%self.player.tili) # 是否出售宝物 if len(self.player.cangku) > 0: choice_baowu = input('|是否出售物件:(y/n)') if choice_baowu == 'y': c = self.shangdian.man_sale(self.player.cangku,self.player.money) self.player.money = c[1] self.player.cangku = c[0] else: print('下次再来') # 是否购买体力 if self.player.money>=10 and self.player.tili <= 20: choice_tili = input('|是否购买体力?(y/n)') if choice_tili == 'y': d = self.shangdian.man_buy(self.player.money,self.player.tili) self.player.money = d[1] self.player.tili = d[0] else : print('你的余额不足,再见') # 如果体力为空,游戏结束 if self.player.tili == 0: print('体力耗尽,游戏结束了') break # 是否抽奖 if self.player.money >=5: self.player.money = self.cjks.begin_cj() except KeyboardInterrupt: self.save_gamedate() def save_gamedate(self): '''存档''' Now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) game_data = json.dumps({"player":[self.player_name,self.player.tili,self.player.money,self.player.cangku], "baoku":[self.baoku_name,self.baoku_list],"time":Now_time}) game_data_addr = ".\\game_data\\"+self.player_name+".json" with open(game_data_addr, 'a', encoding='utf-8') as f: f.write(game_data) f.write("\n") flush_str('\n| --正在存档中🛀-- |',0.1) print("*---游戏结束,正在退出。。。---*") time.sleep(1) print('>>>下次再来>>>') def load_cundang(self,player_info,baoku_info): self.player_info = player_info self.baoku_info = baoku_info self.player_name = self.player_info[0] self.player.tili = self.player_info[1] self.player.money = self.player_info[2] self.player.cangku = self.player_info[3] self.baoku_list = self.baoku_info[1] return self.player_name
def __init__(self, health=100, mana=100, damage=20): Man.__init__(self, health, mana) self.__damage = damage def attack(self): return self.__damage