def __init__(self, screen, gameSelection=False): self.screen = screen self.gameSelection = gameSelection self.font = load.load_font("Nexa Light", 40) self.timer = pygame.time.Clock() self.selection = 0 self.bg = Surface((32, 32)) self.titleImg = load.load_image("title") self.offset = 175 self.mouse = pygame.mouse s = random.choice("01") self.snowing = int(s) if not self.snowing: r = random.choice("00000001") self.raining = int(r) else: self.raining = False self.rain = Rain() self.snow = Snow() # random trees self.numTrees = random.randint(10, 15) self.trees = pygame.sprite.Group() increment = SCREEN_WIDTH // self.numTrees for t in range(self.numTrees): # better random distribution x = random.randint(t * increment - 5, (t + 1) * increment + 5) img = int(random.choice("111223")) y = SCREEN_HEIGHT + random.randint(10, 60) tree = Tree(x, y, img) self.trees.add(tree)
def checkForRain(self): if abs(self.rainStart - self.bgTime) <= 1: # it started raining self.rain = Rain() self.rainStartColor = self.getTimeColor() self.darkening = True if self.rainStart < self.bgTime < self.rainEnd: # it is raining self.raining = True self.rain.draw(self.screen) else: # it's not raining self.raining = False if abs(self.bgTime - (self.rainStart + self.darkenTime)) <= 1: # sky is done darkening self.darkening = False if abs(self.bgTime - (self.rainStart + self.lightenTime)) <= 1: # 2/3 of rain is done, start lightening sky self.rainEndColor = self.getTimeColor( self.rainEnd + 40) # anticipated color self.lightening = True if abs(self.bgTime - self.rainEnd - 40) <= 1: self.lightening = False
def create_rain(settings, screen, rains, col_number, row_number): rain = Rain(settings, screen) rain_width = rain.rect.width rain.x = rain_width + 2 * rain_width * col_number rain.rect.x = rain.x # rect存放整数 rain.y = rain.rect.y + 2 * rain.rect.height * row_number rain.rect.y = rain.y rains.add(rain)
def create_rain(settings, screen, rains, rain_number, row_number): """创建一个雨滴并将其放在当前行""" rain = Rain(settings, screen) rain_width = rain.rect.width rain.x = rain_width + 2 * rain_width * rain_number rain.rect.x = rain.x rain.rect.y = rain.rect.y + 2 * rain.rect.height * row_number rains.add(rain)
def draw_rain(screen): # if direction than RAIN(direction) if Rain.direction == 'down': Rain(screen) elif Rain.direction == 'left': Rain(screen, 'go_left') else: Rain(screen, 'go_right')
def main(): # first thing: backup old log files backupOldLogs() # now we can print an initial message printLogMessage("Starting irrigazione.py") def closingMsg(): printLogMessage("Closing irrigazione.py") def stopIrrigazione(*args): sys.exit(0) atexit.register(closingMsg) signal.signal(signal.SIGTERM, stopIrrigazione) signal.signal(signal.SIGINT, stopIrrigazione) # initialize class to get the weather forecast for next day forecast = Rain() # ========================================================================= # now, infinite loop with: # 1) at 1.00 at night, prepare the scheduling for the day # 2) run scheduling, till the 1.00 of the next day # when the service is started, the first scheduling can happen # anytime in the day, for this reason only events which are # supposed to happen in the future will be actually scheduled while True: printLogMessage("scheduling events for today") # get amount of rain that is predicted for today todaystr, rainamount = forecast.getamount() logmessage = "Predicting {0} mm of rain for today ({1})".format(rainamount, todaystr) printLogMessage(logmessage) # read list of events from configuration file with open("/home/pi/irrigazione/triggers.dat") as fconfig: todayevents = readConfiguration(fconfig) # initialize the schedule s = sched.scheduler() # if the predicted rain is not much, schedule events stored in the dictionary if rainamount < _RAINTHRESHOLD: for tm, evnt in todayevents.items(): scheduleTriggerToday(s, evnt, tm) else: logmessage = "No irrigation will be scheduled for today!" printLogMessage(logmessage) # if heavy rain is predicted, only the waiting time will be scheduled # schedule waiting till next scheduling time scheduleWaitingTomorrow(s, (1, 0)) # now execute the scheduler s.run()
def _create_rain(self): """判断行列有多少元素,设置间距,生产雨添加到Group组""" new_rain = Rain(self) self.rain_height = new_rain.rect_height m = 0 for x in range(4): m += 250 new_rain = Rain(self) random_number = randint(-100, 100) new_rain.rect.x = m + random_number self.rains.add(new_rain)
def create_rain(settings, screen, rains, rain_number): """创建雨滴""" rain = Rain(settings, screen) r_width = settings.rain_width r_height = settings.rain_max_height rain.r_x = r_width + int((rain_number * r_width * randint(1, 3))) rain.r_y = r_height + r_height * randint(-10, r_height) rain.rect.x = rain.r_x rain.rect.y = rain.r_y rains.add(rain)
def create_rain(r_settings, screen, rains, rain_number): """ 创建一个雨滴并将其放在第一行 :param r_settings: 设置 :param screen: 屏幕 :param rains: 雨滴的group :param num_rains_x: 每行雨滴的数量 :return: None """ rain = Rain(r_settings, screen) rain_width = rain.rect.width rain.x = rain_width + rain_width * rain_number rain.rect.x = rain.x rain.rect.y = rain.rect.height rains.add(rain)
def create_fleet(rain_settings, screen, rains): rain = Rain(rain_settings, screen) rain_numbers_x = get_numbers_x(rain_settings, rain) rain_numbers_y = get_numbers_y(rain_settings, rain) for number_y in range(rain_numbers_y): for number_x in range(rain_numbers_x): create_rain(rain_settings, screen, number_x, number_y, rains)
def continue_rains(settings, screen, rains): for rain in rains.sprites(): if rain.check_edges(): new_rain = Rain(settings, screen) new_rain.rect.x = rain.rect.x rains.remove(rain) rains.add(new_rain)
def run_game(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption('narue game') bg_color = (30, 30, 30) COUNT = pygame.USEREVENT + 1 pygame.time.set_timer(COUNT, 1000) star = Star(screen) rains = Group() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == COUNT: new_rain = Rain(screen, star.rect.centerx, star.rect.centery) rains.add(new_rain) screen.fill(bg_color) star.blitme() star.update() for rain in rains: rain.update() rain.draw() pygame.display.flip()
def create_rains(settings, screen, rains): rain = Rain(settings, screen) # 这句是要写的,不写的话get_col_numbers()中的rain将出现NameError col_numbers = get_col_numbers(settings, rain) row_numbers = get_row_numbers(settings, rain) for row_number in range(row_numbers): for col_number in range(col_numbers): create_rain(settings, screen, rains, col_number, row_number)
def rain_get(al_setting,screen,rains): """生成雨滴""" rain = Rain(al_setting,screen) rain_rows = int(al_setting.screen_height / (2 * rain.rect.height)) for rain_row in range(rain_rows): for rain_number in range(rain_numbers(al_setting,screen)): creat_rain(al_setting,screen,rain_number,rain_row,rains)
def add_rain(self): temperature = input("I see it's windy but what is the temperature? ") sky = input("How is the sky looking? ") is_thunder_storm = input( "Is there a thunderstorm outside? (True or False) ") flood_level = input('Out of 10, what is the flood level? ') new_rain = Rain(temperature, is_thunder_storm, sky, flood_level) self.daily_forecast.append(new_rain)
def update_rains(settings, screen, rains): """如果一个雨滴到底部了, 新建一个雨滴, 把 x 左标赋值给它, 再把自己删除添加新雨滴""" for rain in rains.sprites(): if rain.check_edges(): new_rain = Rain(settings, screen) new_rain.rect.x = rain.rect.x rains.remove(rain) rains.add(new_rain) print(len(rains))
def create_fleet(settings, screen, rains): """创建雨滴群""" # 创建一个雨滴,并计算一行可容纳多少个雨滴 rain = Rain(settings, screen) number_rains_x = get_number_rains_x(settings, rain.rect.width) number_rows = get_number_rows(settings, rain.rect.height) for row_number in range(number_rows): for rain_number in range(number_rains_x): create_rain(settings, screen, rains, rain_number, row_number)
def change_rain(total_frames, FPS, screen): # if enough time than BLITZ(), CHANGE_RAIN() if (total_frames + FPS * 2) % ( FPS * 4) == 0: #(FPS*randint(5)) == 0: #direction blitz blitz(screen, [0, 0, 0]) Rain.change_direction() text_to_screen(screen, 'changed direction', 250, 300, 50) pygame.display.flip() pygame.time.delay(800) if total_frames % ( FPS * 4) == 0: #(FPS*randint(8)) == 0: #intensity blitz blitz(screen, [0, 0, 0]) Rain.change_intensity() text_to_screen(screen, 'changed intensity', 250, 300, 50) pygame.display.flip() pygame.time.delay(800)
def create_fleet(r_settings, screen, rains): """ 创建一行雨滴 :param r_settings: 设置 :param screen: 屏幕 :param rains: 雨滴group :return: None """ # 计算一行能够容纳多少滴雨 rain = Rain(r_settings, screen) number_rains_x = get_num_rains_x(r_settings, rain.rect.width) # 创建一行雨滴 for rain_number in range(number_rains_x): create_rain(r_settings, screen, rains, rain_number)
def creat_rain(al_setting,screen,rain_number,rain_row,rains): """创建(随机)一个雨滴""" a = randint(0,1) if a: rain = Rain(al_setting,screen) rain.width = rain.rect.width rain.height = rain.rect.height rain.x = rain.width + 2 * rain.width * rain_number rain.rect.x = rain.x rain.y = rain.height + 2 * rain.height * rain_row rain.rect.y = rain.y rains.add(rain)
def __init__(self, width=64, height=64): self.width = width self.height = height self.frame = 0 self.starttime = time.time() self.im = Image.new("RGBA", (width,height), "black") self.im_draw = ImageDraw.Draw(self.im) self.bg = Image.open("images/bg_normal_big.png") self.bgofs = 0 self.font = ImageFont.truetype("fonts/spincycle.ttf", 18) self.font_sm = ImageFont.truetype("fonts/pf_tempesta_seven.ttf", 8) self.clouds = Cloud.create(20) self.weather = Weather() self.rain = Rain() self.conditions = ""
def run_game(): #初始化 pygame.init() al_setting = Settings() #初始化屏幕 screen = pygame.display.set_mode((al_setting.screen_width, al_setting.screen_height)) pygame.display.set_caption("rains") #创建雨滴实例和组 rain = Rain(al_setting,screen) rains = Group() #获得雨滴组 gf.rain_get(al_setting,screen,rains) while True: #鼠标键盘点击事件 gf.check_event() #更新雨滴组 gf.rain_update(al_setting,screen,rains) #更新屏幕 gf.screen_update(al_setting,screen,rains)
def run_game(): pygame.init() rain_settings = Settings() screen = pygame.display.set_mode( (rain_settings.screen_width, rain_settings.screen_height)) pygame.display.set_caption("Rain Drop Game") rain = Rain(rain_settings, screen) rains = Group() gf.create_fleet(rain_settings, screen, rains) # Start main loop while True: # Check keyboard and mouse events gf.check_events() # Update screen gf.update_screen(rain_settings, screen, rains) # Update rains gf.update_rains(rain_settings, rains)
import sys __project_path = os.path.dirname(os.getcwd()) if __project_path not in sys.path: sys.path.insert(0, __project_path) from rain import Rain app = Rain( view_paths=[ { 'path': './views', 'name': 'default' } ], port=8080, debug=True, # mysql_host='192.168.0.101', # mysql_database='mysql', # mysql_user='******', # mysql_password='******', # redis_host='192.168.0.101', # redis_db=1 ) @app.before_request def permission_check(req): # todo permission check pass
def create_rain(rain_settings, screen, number_x, number_y, rains): rain = Rain(rain_settings, screen) rain.x = rain.rect.width + 2 * number_x * rain.rect.width rain.rect.x = rain.x rain.rect.y = rain.rect.height + 2 * number_y * rain.rect.height rains.add(rain)
def create_fleet(rain_setting, screen, rains): rain = Rain(rain_setting, screen) number_rain_x = get_number_rain_x(rain_setting, rain) for rain_number in range(number_rain_x): create_rain(rain_setting, screen, rains, rain_number)
class Game(object): bgColor = [208, 229, 246] textColor = (236, 247, 255) def __init__(self, screen, timer, custom=False): self.screen = screen self.timer = timer '''Game Mode''' if custom != False: # 0, if no platforms are drawn self.custom = True if isinstance(custom, list): self.customPlatTypes = custom self.customNumPlatforms = None else: self.customNumPlatforms = custom self.customPlatTypes = None else: self.custom = False '''Game Mechanics''' self.totalGameTime = 1000 self.gameover = False self.gameover_image = None self.gameover_rect = None self.pause = False self.done = False font = load.load_font("OpenSans-Semibold", 40) self.pause_image = font.render("Paused", True, (236, 247, 255)) self.pause_rect = self.pause_image.get_rect() self.pause_rect.center = self.screen.get_rect().center self.exit = True self.showFPS = False self.noCrashes = False '''Background''' self.bg = Surface((32, 32)) self.bgTime = 0 self.bgColor = Game.bgColor self.sundownTime = 0 self.rainStart = random.randint(0, self.totalGameTime) self.rainEnd = self.rainStart + random.randint(150, 500) self.rainEndColor = None self.darkenTime = (self.rainEnd - self.rainStart) / 3 self.lightenTime = 2 * (self.rainEnd - self.rainStart) / 3 self.raining = self.darkening = self.lightening = False self.snowing = False self.snow = Snow() '''Game entities''' self.entities = pygame.sprite.Group() self.rocks = pygame.sprite.Group() self.trees = pygame.sprite.Group() self.birds = pygame.sprite.Group() self.coins = pygame.sprite.Group() self.ice = pygame.sprite.Group() self.player = Player() self.entities.add(self.player) self.coinCount = 0 self.flyingBirds = [] self.collectedCoins = [] self.clouds = None '''Score''' self.score = Score() self.scoreSprite = pygame.sprite.Group() self.scoreSprite.add(self.score) '''Platforms''' self.platforms = [] self.numPlatforms = 30 self.generatePlatforms() self.createPlatforms() '''Camera''' self.totalWidth = 1024 * len(self.platformTypes) self.totalHeight = 800 self.camera = Camera(complex_camera, self.totalWidth, self.totalHeight) '''Generating obstacles''' self.iceCoords = makeIce(self.platforms) rockInfo = makeRock(self.platforms) self.treeDict = makeTrees(self.platforms) self.birdDict = generateBirds(self.platforms) self.coinDict = makeCoins(self.platforms) (self.rockRects, self.rockCoords, self.rockAngles) = \ (rockInfo[0], rockInfo[1], rockInfo[2]) # ROCKS offset = 1024 for item in range(1, len(self.rockRects)): currentPlatform = self.platforms[item] x = self.rockRects[currentPlatform][0] + offset y = self.rockRects[currentPlatform][1] angle = self.rockAngles[currentPlatform] obstacle = random.choice("001") rock = Rock(x, y, angle) if obstacle == "0" else Penguin( x, y, angle) self.rocks.add(rock) offset += 1024 # ICE iceOffset = 0 for item in range(self.numPlatforms): currentPlatform = self.platforms[item] x = iceOffset ice = Ice(x, 299, currentPlatform, self.iceCoords) self.ice.add(ice) iceOffset += 1024 # TREES offset = 0 for item in range(len(self.treeDict)): currentPlatform = self.platforms[item] treeCoords = self.treeDict[currentPlatform] for tree in treeCoords: x = offset + tree[0] yOffset = random.randint(5, 20) y = tree[1] + 300 + yOffset tree = Tree(x, y) self.trees.add(tree) offset += 1024 # BIRBS & COINS offset = 0 for item in range(self.numPlatforms): currentPlatform = self.platforms[item] coords = self.birdDict[currentPlatform] coinCoords = self.coinDict[currentPlatform] if coords != None: for point in coords: x = offset + point[0] y = point[1] bird = Bird(x, y, 0) self.birds.add(bird) if coinCoords != None: for coin in coinCoords: x = offset + coin[0] y = coin[1] coin = Coin(x, y) self.coins.add(coin) offset += 1024 def run(self): while not self.done: if not self.pause: # update all game entities self.camera.update(self.player) self.groundSpeed = \ self.player.update( self.platforms, self.iceCoords, self.rocks) clouds.update(self.bgTime, self.totalGameTime, self.raining) for bird in self.birds: if pixelPerfectCollision(self.player, bird) != None: birds.update(bird) self.flyingBirds.append(bird) if self.flyingBirds != []: # bird animation for bird in self.flyingBirds: if bird.rect.top >= 0: birds.update(bird) else: self.flyingBirds.remove(bird) self.birds.remove(bird) for c in self.coins: if pixelPerfectCollision(self.player, c) != None: self.bgTime -= 1 coin.update(c) self.collectedCoins.append([c, 0]) if self.collectedCoins != []: # coin animation existCoins = False for i in range(len(self.collectedCoins)): c, num = self.collectedCoins[i] if c != None and num != None: existCoins = True if num <= 20: coin.update(c) num += 1 self.collectedCoins[i] = [c, num] else: self.collectedCoins[i] = [None, None] self.coins.remove(c) if not existCoins: self.collectedCoins = [] # no coins to update if self.raining: self.rain.update() if self.snowing: self.snow.update() particles.update(self.player.rect.centerx, self.player.rect.centery, self.player.angle, self.groundSpeed) if self.player.crashed and not self.noCrashes: self.exit = False self.setGameOver("You crashed! Press ENTER to exit.") elif self.player.crashed and self.noCrashes: self.player.crashed = False elif self.player.tooSteep and self.custom: self.exit = False self.setGameOver( "The slopes are too steep! Press ENTER to exit.") self.score.add(self.player.getScore()) self.draw() self.handleEvents() return self.score.getScore() def draw(self): self.bg.convert() if not self.pause: self.bgTime += 1 if self.bgTime + 1 == self.totalGameTime: print(self.player.rect.right // 1024) self.exit = False self.bgTime += 1 # avoid an endless loop self.setGameOver("Time's Up! Press ENTER to exit.") if self.bgTime % 5 == 0: if self.darkening or self.lightening or self.raining: self.bgColor = self.rainSky() else: self.bgColor = self.getTimeColor() color = (self.bgColor[0], self.bgColor[1], self.bgColor[2]) try: self.bg.fill(color) except: self.bg.fill((59, 82, 119)) # blit the background for y in range(32): for x in range(32): self.screen.blit(self.bg, (x * 32, y * 32)) # draw the sun based on "time of day" sun = pygame.transform.scale(load.load_image("sun"), (150, 150)) if 50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime) <= 400: self.screen.blit(sun, (SCREEN_WIDTH - 150 - 50 * (self.bgTime / self.totalGameTime), 50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime))) if abs((50 + (SCREEN_HEIGHT) * (self.bgTime / self.totalGameTime)) - 250) <= 2: self.sundownTime = self.bgTime # draw game entities for tree in self.trees: self.screen.blit(tree.image, self.camera.apply(tree)) for e in self.entities: self.screen.blit(e.image, self.camera.apply(e)) for ice in self.ice: self.screen.blit(ice.image, self.camera.apply(ice)) for rock in self.rocks: self.screen.blit(rock.image, self.camera.apply(rock)) for bird in self.birds: self.screen.blit(bird.image, self.camera.apply(bird)) for coin in self.coins: self.screen.blit(coin.image, self.camera.apply(coin)) self.scoreSprite.draw(self.screen) clouds.draw(self.screen) player.drawMessage(self.screen) if self.snowing: self.snow.draw(self.screen) self.checkForRain() particles.draw(self.screen, self.camera) # Draw game info font = load.load_font("Nexa Light", 30) fps = font.render("FPS: " + str(int(self.timer.get_fps())), True, Game.textColor) speed = font.render("Speed: " + str(int(self.groundSpeed)), True, Game.textColor) if self.showFPS: self.screen.blit(fps, (50, 60)) self.screen.blit(speed, (SCREEN_WIDTH - 200, 30)) timeLeft = "Time Left: " timer = font.render(timeLeft, True, Game.textColor) rect = timer.get_rect() rect.right = int(self.screen.get_rect().centerx) rect.top = 30 self.screen.blit(timer, rect) time = font.render(str(self.totalGameTime - self.bgTime), True, Game.textColor) rect = time.get_rect() rect.left = int(self.screen.get_rect().centerx) rect.top = 30 self.screen.blit(time, rect) if self.gameover: if self.exit == False: # when time runs out self.pause = True self.screen.blit(self.gameover_image, self.gameover_rect) else: self.done = True pygame.display.update() def handleEvents(self): self.timer.tick(60) for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): self.done = True pygame.quit() sys.exit() elif e.type == KEYDOWN: if not self.pause: if e.key == K_UP: self.player.moveUp(True) if e.key == K_SPACE: self.player.rotate(True) # cheat: make it rain if e.key == K_r: self.bgTime = self.rainStart # cheat: make it snow if e.key == K_s: self.snowing = not self.snowing # cheat: show FPS if e.key == K_f: self.showFPS = not self.showFPS # cheat: approach end of game if e.key == K_e: self.bgTime = self.totalGameTime - 50 self.rainStartColor = 0 if self.sundownTime == 0: self.sundownTime = 1 # cheat: alter player speeds if e.key == K_z: self.player.groundSpeed += 1 elif e.key == K_x: self.player.groundSpeed -= 1 # cheat: no crashing! if e.key == K_c: self.noCrashes = not self.noCrashes if e.key == K_p: self.pause = not self.pause if self.gameover and e.key == K_RETURN: self.exit = True elif e.type == KEYUP: if e.key == K_UP: self.player.moveUp(False) if e.key == K_SPACE: self.player.rotate(False) def createPlatforms(self, start=0): x = start y = 300 for c in self.platformTypes: platformTypes = str(c) p = Platform(x, y, platformTypes) self.platforms.append(p) self.entities.add(p) x += p.width def generatePlatforms(self): self.platformTypes = ["start"] for i in range(self.numPlatforms): if self.custom: if self.customPlatTypes != None: selections = "".join(self.customPlatTypes) r = random.choice(selections) platform = str(int(r) * 100) self.platformTypes.append(platform) else: self.platformTypes.append(str(random.randint(1, self.customNumPlatforms) * 100)) else: # randomly chooses platforms; weighted probability self.platformTypes.append(random.choice("911223344556")) return self.platformTypes def checkForRain(self): if abs(self.rainStart - self.bgTime) <= 1: # it started raining self.rain = Rain() self.rainStartColor = self.getTimeColor() self.darkening = True if self.rainStart < self.bgTime < self.rainEnd: # it is raining self.raining = True self.rain.draw(self.screen) else: # it's not raining self.raining = False if abs(self.bgTime - (self.rainStart + self.darkenTime)) <= 1: # sky is done darkening self.darkening = False if abs(self.bgTime - (self.rainStart + self.lightenTime)) <= 1: # 2/3 of rain is done, start lightening sky self.rainEndColor = self.getTimeColor( self.rainEnd + 40) # anticipated color self.lightening = True if abs(self.bgTime - self.rainEnd - 40) <= 1: self.lightening = False def getTimeColor(self, time=None): # throwback to rgb color blender if time != None: bgTime = time else: bgTime = self.bgTime if self.sundownTime != 0: # fraction of time elapsed r = 208 - ((208 - 59) * ((bgTime - self.sundownTime) / self.totalGameTime)) g = 229 - ((229 - 82) * ((bgTime - self.sundownTime) / self.totalGameTime)) b = 246 - ((246 - 119) * ((bgTime - self.sundownTime) / self.totalGameTime)) if r < 59: r = 59 if g < 82: g = 82 if b < 119: b = 119 return [int(r), int(g), int(b)] else: return Game.bgColor def rainSky(self): if self.darkening: if self.bgTime <= self.rainStart + self.darkenTime: timeElapsed = (self.bgTime - self.rainStart) r = (self.rainStartColor[0] - ((self.rainStartColor[0] - 135) * timeElapsed / self.darkenTime)) g = (self.rainStartColor[1] - ((self.rainStartColor[1] - 156) * timeElapsed / self.darkenTime)) b = (self.rainStartColor[2] - ((self.rainStartColor[2] - 183) * timeElapsed / self.darkenTime)) return [int(r), int(g), int(b)] else: return [135, 156, 183] elif self.lightening: secondsElapsed = self.bgTime - (self.rainEnd - self.darkenTime) if abs(secondsElapsed - (self.rainEnd - self.darkenTime + 40)) <= 5: self.raining = self.lightening = self.darkening = False # rain effects are over return self.rainEndColor else: a = self.rainEnd - self.darkenTime + 40 color = self.rainEndColor r, g, b = color[0], color[1], color[2] newR = int(135 - (135 - r) * (secondsElapsed / a)) newG = int(156 - (156 - g) * (secondsElapsed / a)) newB = int(183 - (183 - g) * (secondsElapsed / a)) return [int(newR), int(newG), int(newB)] else: # just raining return [135, 156, 183] def setGameOver(self, message="Game Over"): # sets game over, shows a message depending on cause of death self.gameover = True images = [] font = load.load_font("Nexa Light", 30) height = 0 width = 0 for text in message.split("\n"): images.append(font.render(text, True, (25, 51, 71))) height += images[-1].get_height() width = images[-1].get_width() self.gameover_image = pygame.Surface((width, height), SRCALPHA, 32) self.gameover_image.fill((0, 0, 0, 0)) for i in range(len(images)): rect = images[i].get_rect() rect.top = i * images[i].get_height() rect.centerx = width / 2 self.gameover_image.blit(images[i], rect) self.gameover_rect = self.gameover_image.get_rect() self.gameover_rect.center = self.screen.get_rect().center
#Lists that will contain all rain / cloud sprites raindrops = pygame.sprite.Group() clouds = pygame.sprite.Group() # This loop will continue until the user exits the game carryOn = True # The clock will be used to control how fast the screen updates clock = pygame.time.Clock() background_image = pygame.image.load("background.png") #http://davidgmiller.typepad.com/lovelandmagazine/2014/01/montessori-school-holds-winter-performance.html #Making the rain drops for i in range(100): drop = Rain(BLUE, 3, 7) raindrops.add(drop) #Making the clouds for i in range(7): cloud = Cloud(GREY, 50, 35) clouds.add(cloud) #---------Main Program Loop---------- while carryOn: # --- Main event loop --- for event in pygame.event.get(): if event.type == pygame.QUIT: # Player clicked close button carryOn = False if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: #Player clicked space bar carryOn = False
def run(tk): s = Canvas(tk, width = 800, height = 800, background = "blue") s.grid(row = 0, column = 0) pond = PhotoImage(file = "pond.gif") pondO = None queue = Queue() shared = Array('i', [0, 0, 0]) paused = Array('i', [1, 1, 0, 1]) stars = Stars(queue, shared, paused) stars.start() sleep(0.01) main = MainThread(queue, shared, paused) main.start() sleep(0.01) rain = Rain(queue, shared, paused) rain.start() sleep(0.01) clouds = Clouds(queue, shared, paused) clouds.start() while True: contA = [] while len(contA) < 4: try: task = queue.get(block = False) except: pass else: try: if task.oper == "create": object = s._create(task.object, task.coords, task.kw) task.pipeSend.send(object) elif task.oper == "config": s.config(task.kw) elif task.oper == "coords": s.coords(task.object, task.coords) elif task.oper == "itemconfig": s.itemconfig(task.object, task.kw) elif task.oper == "cont": contA.append(1) except: break if pondO == None: pondO = s.create_image(150, 700, image = pond) try: s.update() except: break paused[0] = 0 paused[1] = 0 paused[2] = 0 paused[3] = 0
class Menu(object): # Home Screen NEWGAME = 0 HELP = 1 QUIT = 2 # Game Selection Screen GAME = 0 DRAW = 1 BACK = 2 def __init__(self, screen, gameSelection=False): self.screen = screen self.gameSelection = gameSelection self.font = load.load_font("Nexa Light", 40) self.timer = pygame.time.Clock() self.selection = 0 self.bg = Surface((32, 32)) self.titleImg = load.load_image("title") self.offset = 175 self.mouse = pygame.mouse s = random.choice("01") self.snowing = int(s) if not self.snowing: r = random.choice("00000001") self.raining = int(r) else: self.raining = False self.rain = Rain() self.snow = Snow() # random trees self.numTrees = random.randint(10, 15) self.trees = pygame.sprite.Group() increment = SCREEN_WIDTH // self.numTrees for t in range(self.numTrees): # better random distribution x = random.randint(t * increment - 5, (t + 1) * increment + 5) img = int(random.choice("111223")) y = SCREEN_HEIGHT + random.randint(10, 60) tree = Tree(x, y, img) self.trees.add(tree) def run(self): self.done = False while not self.done: self.bg.convert() if not self.raining: self.bg.fill(Color(208, 229, 246)) else: self.bg.fill((135, 156, 183)) for y in range(32): for x in range(32): self.screen.blit(self.bg, (x * 32, y * 32)) for tree in self.trees: self.screen.blit(tree.image, tree.rect) if self.raining: self.rain.update() self.rain.draw(self.screen) if self.snowing: self.snow.update() self.snow.draw(self.screen) if not self.gameSelection: self.render("PLAY", Menu.NEWGAME) self.render("HELP", Menu.HELP) self.render("QUIT", Menu.QUIT) else: self.render("BEGIN GAME", Menu.GAME) self.render("DRAWING MODE", Menu.DRAW) self.render("BACK", Menu.BACK) rect = self.titleImg.get_rect() rect.centerx = self.screen.get_rect().centerx rect.centery = self.offset self.screen.blit(self.titleImg, rect) pygame.display.flip() self.timer.tick(60) for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): self.done = True pygame.quit() sys.exit() elif e.type == KEYDOWN: if e.key == K_UP: self.selection -= 1 if self.selection < 0: self.selection = 0 if e.key == K_DOWN: self.selection += 1 if not self.gameSelection: if self.selection > Menu.QUIT: self.selection = Menu.QUIT else: if self.selection > Menu.BACK: self.selection = Menu.BACK if self.selection < 0: self.selction = 0 if e.key == K_RETURN: self.done = True return self.selection def render(self, text, num): # draws buttons textColor = (255, 255, 255) if self.selection == num: textColor = (50, 150, 225) image = self.font.render(text, True, textColor) rect = image.get_rect() rect.centerx = self.screen.get_rect().centerx rect.top = self.titleImg.get_height() + num * rect.height * 1.4 + 20 self.screen.blit(image, rect)
def create_rain(rain_setting, screen, rains, rain_number): rain = Rain(rain_setting, screen) rain_width = rain.rect.width rain.x = rain_width + 2 * rain_width * rain_number rain.rect.x = rain.x rains.add(rain)
class Visualization(object): def __init__(self, width=64, height=64): self.width = width self.height = height self.frame = 0 self.starttime = time.time() self.im = Image.new("RGBA", (width,height), "black") self.im_draw = ImageDraw.Draw(self.im) self.bg = Image.open("images/bg_normal_big.png") self.bgofs = 0 self.font = ImageFont.truetype("fonts/spincycle.ttf", 18) self.font_sm = ImageFont.truetype("fonts/pf_tempesta_seven.ttf", 8) self.clouds = Cloud.create(20) self.weather = Weather() self.rain = Rain() self.conditions = "" def drawtime(self): now = datetime.datetime.now() t = now.strftime("%I:%M") size = self.im_draw.textsize(t, font=self.font) x = self.width / 2 - size[0] / 2 self.im_draw.text((x,0), t, (16,16,16) ,font=self.font) def updateweather(self): self.weather.update() clouds = int(self.weather.cover * 20) if (self.weather.wind == 0): cloudspeed = 0 elif (self.weather.windbearing <= 90 or self.weather.windbearing >= 270): cloudspeed = float(self.weather.wind)/-30.0 else: cloudspeed = float(self.weather.wind)/30.0 for i in xrange(clouds,20): if self.clouds[i].active: self.clouds[i].deactivate() for i in xrange(clouds): self.clouds[i].activate(cloudspeed) if (self.weather.conditions == 'snow' or self.weather.conditions == 'hail' or self.weather.conditions == 'sleet'): self.bg = Image.open('images/bg_icy_normal.png') elif (time.time() > self.weather.sunset + 1800 and time.time() < self.weather.sunrise): self.bg = Image.open('images/bg_night.png') elif (self.weather.cover > 0.75): self.bg = Image.open('images/bg_dark.png') elif (time.time() >= self.weather.sunset and time.time() <= self.weather.sunset + 1800): self.bg = Image.open('images/bg_sunset_big.png') elif (time.time() >= self.weather.sunrise and time.time() <= self.weather.sunrise + 1800): self.bg = Image.open('images/bg_sunset_big.png') else: self.bg = Image.open('images/bg_normal_big.png') def drawweather(self): cond = self.weather.conditions if (cond == "rain" or cond == "hail" or cond == "thunderstorm" or cond == "snow" or cond == "sleet"): self.rain.move() self.rain.paint(self.im_draw, (225,225,225) if (cond =="snow" or cond == "sleet") else (96,96,200)) for i in xrange(20): self.clouds[i].move() self.clouds[i].paint(self.im) self.im_draw.text((17,53), "{0}".format(int(float(self.weather.temp))), (0,0,0) ,font=self.font_sm) self.im_draw.point((30,57),(0,0,0)) self.im_draw.point((31,58),(0,0,0)) self.im_draw.point((30,59),(0,0,0)) self.im_draw.point((29,58),(0,0,0)) self.im_draw.text((33,53), "{0}".format(int(float(self.weather.rf))), (0,0,0) ,font=self.font_sm) self.im_draw.point((46,57),(0,0,0)) self.im_draw.point((47,58),(0,0,0)) self.im_draw.point((46,59),(0,0,0)) self.im_draw.point((45,58),(0,0,0)) def drawbg(self): if self.bg.size[0] > self.width: if self.frame % 30 == 0: self.bgofs = self.bgofs + 1 if self.bgofs > self.bg.size[0]: self.bgofs = 0 self.im.paste(self.bg.crop((self.bgofs,0,self.width+self.bgofs,self.height)), (0,0,self.width,self.height)) if self.bgofs > self.bg.size[0]-self.width: o = self.width-(self.bg.size[0]-self.bgofs) self.im.paste(self.bg.crop((0,0,o,self.height)), (self.width-o,0,self.width,self.height)) else: self.im.paste(self.bg, (0,0,self.width,self.height)) def fps(self): return self.frame/(time.time()-self.starttime) def draw(self): if self.frame % 1800 == 0: self.updateweather() self.drawbg() self.drawweather() self.drawtime() self.pixels = self.im.convert("RGB").tostring() self.frame = self.frame + 1
def rain_numbers(al_setting,screen): """计算一行最多能容纳雨滴数""" rain = Rain(al_setting,screen) rain_numbers = int(al_setting.screen_width / (2 * rain.rect.width)) return rain_numbers