class FlappyBird(object): init() fps_clock = time.Clock() screen_width = 288 screen_height = 512 # os.environ["SDL_VIDEODRIVER"] = "dummy" screen = display.set_mode((screen_width, screen_height)) # screen = None display.set_caption('Deep Q-Network Flappy Bird') base_image = load('assets/sprites/base.png').convert_alpha() background_image = load('assets/sprites/background-black.png').convert() pipe_images = [rotate(load('assets/sprites/pipe-green.png').convert_alpha(), 180), load('assets/sprites/pipe-green.png').convert_alpha()] bird_images = [load('assets/sprites/redbird-upflap.png').convert_alpha(), load('assets/sprites/redbird-midflap.png').convert_alpha(), load('assets/sprites/redbird-downflap.png').convert_alpha()] # number_images = [load('assets/sprites/{}.png'.format(i)).convert_alpha() for i in range(10)] bird_hitmask = [pixels_alpha(image).astype(bool) for image in bird_images] pipe_hitmask = [pixels_alpha(image).astype(bool) for image in pipe_images] fps = 30 pipe_gap_size = 100 pipe_velocity_x = -4 # parameters for bird min_velocity_y = -8 max_velocity_y = 10 downward_speed = 1 upward_speed = -9 bird_index_generator = cycle([0, 1, 2, 1]) def __init__(self): self.iter = self.bird_index = self.score = 0 self.bird_width = self.bird_images[0].get_width() self.bird_height = self.bird_images[0].get_height() self.pipe_width = self.pipe_images[0].get_width() self.pipe_height = self.pipe_images[0].get_height() self.bird_x = int(self.screen_width / 5) self.bird_y = int((self.screen_height - self.bird_height) / 2) self.base_x = 0 self.base_y = self.screen_height * 0.79 self.base_shift = self.base_image.get_width() - self.background_image.get_width() pipes = [self.generate_pipe(), self.generate_pipe()] pipes[0]["x_upper"] = pipes[0]["x_lower"] = self.screen_width pipes[1]["x_upper"] = pipes[1]["x_lower"] = self.screen_width * 1.5 self.pipes = pipes self.current_velocity_y = 0 self.is_flapped = False def generate_pipe(self): x = self.screen_width + 10 gap_y = randint(2, 10) * 10 + int(self.base_y / 5) return {"x_upper": x, "y_upper": gap_y - self.pipe_height, "x_lower": x, "y_lower": gap_y + self.pipe_gap_size} def is_collided(self): # Check if the bird touch ground if self.bird_height + self.bird_y + 1 >= self.base_y: return True bird_bbox = Rect(self.bird_x, self.bird_y, self.bird_width, self.bird_height) pipe_boxes = [] for pipe in self.pipes: pipe_boxes.append(Rect(pipe["x_upper"], pipe["y_upper"], self.pipe_width, self.pipe_height)) pipe_boxes.append(Rect(pipe["x_lower"], pipe["y_lower"], self.pipe_width, self.pipe_height)) # Check if the bird's bounding box overlaps to the bounding box of any pipe if bird_bbox.collidelist(pipe_boxes) == -1: return False for i in range(2): cropped_bbox = bird_bbox.clip(pipe_boxes[i]) min_x1 = cropped_bbox.x - bird_bbox.x min_y1 = cropped_bbox.y - bird_bbox.y min_x2 = cropped_bbox.x - pipe_boxes[i].x min_y2 = cropped_bbox.y - pipe_boxes[i].y if np.any(self.bird_hitmask[self.bird_index][min_x1:min_x1 + cropped_bbox.width, min_y1:min_y1 + cropped_bbox.height] * self.pipe_hitmask[i][ min_x2:min_x2 + cropped_bbox.width, min_y2:min_y2 + cropped_bbox.height]): return True return False def next_frame(self, action): pump() reward = 0.1 terminal = False # Check input action if action == 1: self.current_velocity_y = self.upward_speed self.is_flapped = True # Update score bird_center_x = self.bird_x + self.bird_width / 2 for pipe in self.pipes: pipe_center_x = pipe["x_upper"] + self.pipe_width / 2 if pipe_center_x < bird_center_x < pipe_center_x + 5: self.score += 1 reward = 1 break # Update index and iteration if (self.iter + 1) % 3 == 0: self.bird_index = next(self.bird_index_generator) self.iter = 0 self.base_x = -((-self.base_x + 100) % self.base_shift) # Update bird's position if self.current_velocity_y < self.max_velocity_y and not self.is_flapped: self.current_velocity_y += self.downward_speed if self.is_flapped: self.is_flapped = False self.bird_y += min(self.current_velocity_y, self.bird_y - self.current_velocity_y - self.bird_height) if self.bird_y < 0: self.bird_y = 0 # Update pipes' position for pipe in self.pipes: pipe["x_upper"] += self.pipe_velocity_x pipe["x_lower"] += self.pipe_velocity_x # Update pipes if 0 < self.pipes[0]["x_lower"] < 5: self.pipes.append(self.generate_pipe()) if self.pipes[0]["x_lower"] < -self.pipe_width: del self.pipes[0] if self.is_collided(): terminal = True reward = -1 self.__init__() # Draw everything if self.screen is not None: self.screen.blit(self.background_image, (0, 0)) self.screen.blit(self.base_image, (self.base_x, self.base_y)) self.screen.blit(self.bird_images[self.bird_index], (self.bird_x, self.bird_y)) for pipe in self.pipes: self.screen.blit(self.pipe_images[0], (pipe["x_upper"], pipe["y_upper"])) self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"])) image = array3d(display.get_surface()) display.update() self.fps_clock.tick(self.fps) return image, reward, terminal
self.draw_level() self.draw_help() @staticmethod def get_file_num(): _, _, files = os.walk(Renderer.path).__next__() return len(files) if __name__ == '__main__': pygame.init() screen = display.set_mode(Renderer.size) screen.fill((255, 255, 255)) display.flip() renderer = Renderer(screen) clk = time.Clock() while True: clk.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: renderer.on_space() elif event.key == pygame.K_LEFT: renderer.on_left() elif event.key == pygame.K_RIGHT: renderer.on_right() elif event.key == pygame.K_ESCAPE: pygame.quit()
from pygame import time,event,mouse,MOUSEBUTTONDOWN,MOUSEBUTTONUP,NOEVENT _Clic = [0,0,0,0,0,0] _Ticks = [time.Clock(),time.Clock(),time.Clock(),time.Clock(),time.Clock(),time.Clock()] LAPS = 200 _NoEvent_Clock = time.Clock() _Inactiv = 0 ButtonDelay = 500 ButtonRepeat = 100 _ButtonTick = ButtonDelay def wait(): ev=event.wait() _foo(ev) return ev def poll(): ev=event.poll() _foo(ev) return ev def get(evs=range(50)): ev=event.get(evs) for e in ev: _foo(e) return ev def _foo(e): global _Clic,_Ticks,_Inactiv,_ButtonTick if e.type==NOEVENT: _Inactiv+=_NoEvent_Clock.tick()
import Game.settings as Settings import Game.ecs as ECS import Game.controlls import pygame.time as time game_clock = time.Clock() def tick(): dt = game_clock.tick(0) Game.controlls.doKeys() doMovement(dt) # moves all entities by their velocity def doMovement(dt): for entity in ECS.Entity.moveable_list: PosX = getattr(entity, ECS.ComponentNames.POS_X.value) PosY = getattr(entity, ECS.ComponentNames.POS_Y.value) VelocityX = getattr(entity, ECS.ComponentNames.VELOCITY_X.value) VelocityY = getattr(entity, ECS.ComponentNames.VELOCITY_Y.value) setattr(entity, ECS.ComponentNames.POS_X.value, PosX + VelocityX * dt) setattr(entity, ECS.ComponentNames.POS_Y.value, PosY + VelocityY * dt) entity.setDirty()
def _play(self, screen) -> State: """Play the game. screen: pygame display""" self._set_screen(self._score, self._highscore, self._hostile, self._exploding) size = ENEMY_STARTING_SIZE n = 3 speed = ENEMY_STARTING_SPEED # setup sounds shot_sound = mixer.Sound(GUNSHOOT) shot_sound.set_volume(0.25) # mute background music mixer.music.fadeout(500) while True: time.Clock().tick(SLOWMO if self._player.is_exploding else FPS) screen.fill(BLACK) # listen for user actions for event in pygame.event.get(): if event.type == QUIT: # exit by closing the window return State.QUIT if event.type == KEYDOWN: if event.key == K_ESCAPE: # exit by pressing escape button return State.QUIT if event.type == MOUSEBUTTONDOWN: self._player.fires = True # open fire if event.type == MOUSEBUTTONUP: self._player.fires = False # cease fire # setup enemy wave if not bool(self._hostile): self._hostile.reset_level() self._hostile_fire.reset() size += ENEMY_SIZE_DECREMENT n += 1 speed += ENEMY_SPEED_INCREMENT for i in range(n): x = random.randrange(0, SCREEN_WIDTH, 1) y = random.randrange(0, SCREEN_HEIGHT // 2, 1) angle = math.radians(random.randrange(315, 345, 1)) self._hostile.add(Enemy(size, n, (x, y), speed, angle)) self._onscreen.add(self._hostile) # shoot player projectiles if self._player.fire_rate_timer.is_ready() and self._player.fires: self._fire.add( Projectile(self._player, PLAYER_PROJECTILE_SPEED)) self._onscreen.add(self._fire) self._player.fire_rate_timer.reset() shot_sound.play() # shoot enemy projectiles if self._hostile.fire_rate_timer.is_ready() and bool( self._hostile): enemy = random.choice(list( self._hostile)) # choose a random member from the wave self._hostile_fire.add( Projectile(enemy, ENEMY_PROJECTILE_STARTING_SPEED, self._player)) self._onscreen.add(self._hostile_fire) self._hostile.fire_rate_timer.cooldown -= ENEMY_WAVE_FIRE_COOLDOWN_DECREMENT self._hostile.fire_rate_timer.reset() # check whether player's projectile hits an enemy self._fire.hit(self._hostile) # check whether player's projectile hits an enemy projectile self._fire.contact(self._hostile_fire) # check whether hostile fire hits player self._hostile_fire.harm(self._player) # check player collisions with enemy craft self._hostile.contact(self._player) # check destroyed starhips for ship in self._hostile: if ship.is_destroyed: self._hostile.remove(ship) self._exploding.add(ship) if self._player.is_destroyed: self._exploding.add(self._player) # check exploding ships's state for ship in self._exploding: if ship.explosion_timer.is_ready(): ship.explode() if ship.exploded: ship.kill() self._ship_destroyed_sound.play() # check if player is still alive if not self._player.alive(): return State.GAME_OVER # update sprites changed = self._onscreen.update( screen=screen, state=State.PLAY, score=self._hostile.score, hiscore=max(self._hostile.score + self._hostile_fire.score, self._hiscore)) pygame.display.update(changed)
def main(): os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50, 30) pygame.init() display = pygame.display.set_mode((1500, 1000)) display.fill((0, 128, 255)) run = True clock = time.Clock() number = 1000 dot = [] for i in range(number): dot.append(Dot()) dot[i].set_axon_koef() counter = 1 csX, csY, ceX, ceY, cwX, cwY, cX, cY, cW = 0., 0., 0., 0., 0., 0., 0., 0., 0. while (run): counter += 1 success = 0 parents = [] for i in range(len(dot) - 1, -1, -1): dot[i].update() if dot[i].success: parents.append(dot[i]) if dot[i].random_coef <= 0.01: success += 1 del dot[i] continue if dot[i].dead: del dot[i] if len(dot) == 0: # Якщо всі вимруть то появляться нові жертви for i in range(number): dot.append(Dot()) dot[i].set_axon_koef() for i in range(len(parents)): for j in range( int(5000 / len(dot) * parents[i].chaild_coef + 2) - 1): dot.append( Dot(0, 0, csX=parents[i].get_csX(), csY=parents[i].get_csY(), ceX=parents[i].get_ceX(), ceY=parents[i].get_ceY(), cwX=parents[i].get_cwX(), cwY=parents[i].get_cwY(), cX=parents[i].get_cX(), cY=parents[i].get_cY(), cW=parents[i].get_cW(), random_coef=parents[i].random_coef)) parents[i].set_position() parents[i].color[2] = max(0, parents[i].color[2] - 1) for j in range(int(5000 / len(dot) + 2) + 1): dot_random = Dot() dot_random.set_axon_koef() dot_random.color = [0, 0, 0] dot.append(dot_random) if (len(parents) > 0): csX = parents[0].get_csX() csY = parents[0].get_csY() ceX = parents[0].get_ceX() ceY = parents[0].get_ceY() cwX = parents[0].get_cwX() cwY = parents[0].get_cwY() cX = parents[0].get_cX() cY = parents[0].get_cY() cW = parents[0].get_cW() pygame.display.set_caption("counter: " + str(counter) + " осіб: " + str(success) + "/" + str(len(dot)) + " csX: %+1.3f" % csX + " csY: %+1.3f" % csY + " ceX: %+1.3f" % ceX + " ceY: %+1.3f" % ceY + " cwX: %+1.3f" % cwX + " cwY: %+1.3f" % cwY + " cX: %+1.3f" % cX + " cY: %+1.3f" % cY + " cW: %+1.3f" % cW) display.fill((0, 180, 200)) for i in range(len(dot)): pygame.draw.line(display, dot[i].color, dot[i].get_pos_start(), dot[i].get_pos_end(), 2) pygame.draw.circle(display, dot[i].color, dot[i].get_pos_start(), 4) pygame.draw.circle(display, (4, 5, 5), dot[i].goal, 8) pygame.display.flip() clock.tick(30) pygame.quit()
class NS_SHAFT(object): init() fps_clock = time.Clock() screen_width = 288 screen_height = 512 screen = display.set_mode((screen_width, screen_height)) display.set_caption('Deep Q-Network NS-SH') base_image = load('assets/sprites/base.png').convert_alpha() background_image = load('assets/sprites/background-black.png').convert() floor_images = [load('assets/sprites/floors.PNG').convert_alpha()] man_images = [load('assets/sprites/man.PNG').convert_alpha()] # number_images = [load('assets/sprites/{}.png'.format(i)).convert_alpha() for i in range(10)] man_hitmask = [pixels_alpha(image).astype(bool) for image in man_images] floor_hitmask = [pixels_alpha(image).astype(bool) for image in floor_images] fps = 30 #pipe_gap_size = 100 floor_velocity_y = 4 # parameters for man min_velocity_y = -4 max_velocity_y = 10 downward_speed = 1 upward_speed = -9 man_index_generator = cycle([0, 1, 2, 1]) state = 0 # 0 falling, 1 stand on floor state2_counter = 0 def __init__(self): self.iter = self.man_index = self.score = 0 self.man_width = self.man_images[0].get_width() self.man_height = self.man_images[0].get_height() self.floor_width = self.floor_images[0].get_width() self.floor_height = self.floor_images[0].get_height() self.man_x = int((self.screen_width- self.man_width)/2) #self.man_y = int((self.screen_height - self.man_height) / 2) self.man_y = int(self.screen_height*0.25)-50 #self.base_x = 0 #self.base_y = self.screen_height * 0.79 #self.base_shift = self.base_image.get_width() - self.background_image.get_width() floors = [{'x':self.man_x,'y':self.man_y+self.man_height+3},{'x':30,'y':250},{'x':100,'y':400}] #floors[0]["x_upper"] = pipes[0]["x_lower"] = self.screen_width #floors[1]["x_upper"] = pipes[1]["x_lower"] = self.screen_width * 1.5 self.floors = floors self.current_velocity_y = 0 self.is_flapped = False def generate_floor(self): y = self.screen_height f = [randint(10,210),randint(0,75),randint(150,220)] x = f[randint(0,2)] #gap_y = randint(2, 10) * 10 + int(self.base_y / 5) return {'x' : x,'y' : y} def is_collided(self): man_bbox = Rect(self.man_x, self.man_y, self.man_width, self.man_height) collided_floor = {'x': 0,'y':0} is_collided = False for floor in self.floors: floor_box = Rect(floor["x"], floor["y"], self.floor_width, self.floor_height) if Rect.colliderect(man_bbox, floor_box): collided_floor['x'] = floor['x'] collided_floor['y'] = floor['y'] is_collided = True return is_collided, collided_floor def next_frame(self, action): pump() reward = 0.01 terminal = False # Check input action self.current_velocity_x = action if self.is_flapped: self.is_flapped = False if self.state == 1: self.current_velocity_y = self.floor_velocity_y elif self.state == 2: self.current_velocity_y = -4 else: self.current_velocity_y = max(min(-1,self.current_velocity_y-1),self.min_velocity_y) #print(self.state,self.current_velocity_y) self.man_y -= self.current_velocity_y self.man_x = min(max(0,self.man_x+self.current_velocity_x),self.screen_width-self.man_width) if(self.man_x == 0 or self.man_x == self.screen_width-self.man_width): reward -=1 # Update pipes' position for floor in self.floors: #print(floor["y"],self.floor_velocity_y) floor["y"] -= self.floor_velocity_y # Update pipes if self.floors[0]["y"] < 0: self.floors.append(self.generate_floor()) del self.floors[0] is_collided, floor = self.is_collided() if (self.state2_counter==0): if self.man_y >=self.screen_height: self.state = 3 terminal = True reward = -1 self.__init__() elif self.man_y <=0: self.state = 2 self.state2_counter = 10 reward = -0.2 elif is_collided: self.man_y = floor['y']-28 self.state = 1 reward = 0.4 else: self.state = 0 #reward = -1 else: self.state2_counter = max(0,self.state2_counter-1) # Draw everything self.screen.blit(self.background_image, (0, 0)) #self.screen.blit(self.base_image, (self.base_x, self.base_y)) self.screen.blit(self.man_images[0], (self.man_x, self.man_y)) for floor in self.floors: self.screen.blit(self.floor_images[0], (floor["x"], floor["y"])) #self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"])) image = array3d(display.get_surface()) display.update() self.fps_clock.tick(self.fps) return image, reward, terminal
def show(self, name, client, order): init() self.background = image.load('background.png') self.background = transform.scale(self.background, (1000, 800)) self.window_width, self.window_height = 1000, 800 self.main_window = display.set_mode( (self.window_width, self.window_height)) self.clock = time.Clock() self.black = (0, 0, 0) self.red = (255, 0, 0) self.gray = (100, 100, 100) self.white = (255, 255, 255) self.who_go = 0 # even means red goes first, old means black goes first self.first_click_coor = [] self.start = False self.load = False self.first_click = True self.mouse_up = False self.hui_yi_bu = False self.temp = Setting.coors_plate self.coors_chess = Setting.coors_chess self.legal_move = Setting.legal_move self.coors_plate = [] self.c_coors_plate = [] self.jiang_shuai = [] self.chess = 0 self.over = 0 self.record = [0, 0, 0, 0] self.mouse1 = [] self.mouse2 = [] self.name = name self.client = client self.order = order self.new_game(self.order) while True: self.main_window.blit(self.background, (0, 0)) self.Mouse = mouse.get_pos() self.click = mouse.get_pressed() self.coors = [0, 32, 0, 0, 0] self.coors_all = [[], []] self.non_chess_coors = [] for i, row in enumerate(self.coors_plate): self.coors[0] = 37 for ii, col in enumerate(row): self.coors[2], self.coors[3] = i, ii # red if col == 1010 or col == 1011 or col == 1020 or col == 1021: self.blit_chess('red', 'ju', self.coors) elif col == col == 2010 or col == 2011 or col == 2020 or col == 2021: self.blit_chess('red', 'ma', self.coors) elif col == 3010 or col == 3011 or col == 3020 or col == 3021: self.blit_chess('red', 'xiang', self.coors) elif col == col == 4010 or col == 4011 or col == 4020 or col == 4021: self.blit_chess('red', 'shi', self.coors) elif col == 5000 or col == 5001: self.blit_chess('red', 'shuai', self.coors) elif col == col == 6010 or col == 6011 or col == 6020 or col == 6021: self.blit_chess('red', 'pao', self.coors) elif col == 7010 or col == 7011 or col == 7020 or col == 7021 or col == 7030\ or col == 7031 or col == 7040 or col == 7041 or col == 7050 or col == 7051: self.blit_chess('red', 'bing', self.coors) # black elif col == 1110 or col == 1111 or col == 1120 or col == 1121: self.blit_chess('black', 'ju', self.coors) elif col == 2110 or col == 2111 or col == 2120 or col == 2121: self.blit_chess('black', 'ma', self.coors) elif col == 3110 or col == 3111 or col == 3120 or col == 3121: self.blit_chess('black', 'xiang', self.coors) elif col == 4110 or col == 4111 or col == 4120 or col == 4121: self.blit_chess('black', 'shi', self.coors) elif col == 5100 or col == 5101: self.blit_chess('black', 'jiang', self.coors) elif col == 6110 or col == 6111 or col == 6120 or col == 6121: self.blit_chess('black', 'pao', self.coors) elif col == 7110 or col == 7111 or col == 7120 or col == 7121 or col == 7130 \ or col == 7131 or col == 7140 or col == 7141 or col == 7150 or col == 7151: self.blit_chess('black', 'bing', self.coors) else: self.non_chess_coors.append(self.coors.copy()) self.coors[0] += 84 self.coors[1] += 75 self.show_all_selected() # 新游戏 self.display_button(900, 90, '新游戏', 30, 'new_game') # 储存游戏 self.display_button(900, 172, '存档', 30, 'save_game') # 加载游戏 self.display_button(900, 633, '读档', 30, 'load_game') # 悔一步 self.display_button(900, 407, '悔一步', 30, 'hui_qi') # 显示回合 if self.start or self.load: if self.who_go % 2 == 0: self.text_display(self.main_window, self.red, '对方回合', 30, [900, 717], 'simhei') else: self.text_display(self.main_window, self.black, '您的回合', 30, [900, 717], 'simhei') if self.start or self.load: self.over = self.game_over() if self.over == 1: self.text_display( self.main_window, self.black, '游戏结束', 100, [self.window_width // 2, self.window_height // 2], 'simhei') self.mouse_up = False for Event in event.get(): if Event.type == QUIT: if self.over == 1: send_msg = {'type': 'exit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break else: send_msg = {'type': 'quit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break if Event.type == MOUSEBUTTONUP: self.mouse_up = True if 385 > self.Mouse[ 1] or 425 < self.Mouse[1] and self.Mouse[0] < 800: if self.who_go % 2 == 1 and self.over != 1: self.click_chess( 1 ) # eg. chess = [709, 707, 9, 8] - x, y, row, col if Event.type == USEREVENT + 1: if self.who_go % 2 == 1 and self.over != 1: self.voice_control( 1) # eg. chess = [709, 707, 9, 8] - x, y, row, col if Event.type == USEREVENT + 2: if self.over == 1: send_msg = {'type': 'exit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break else: send_msg = {'type': 'quit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break if Event.type == USEREVENT + 7: self.voice_control(0) if Event.type == USEREVENT + 8: quit() break if Event.type == USEREVENT + 9: self.Mouse = self.mouse1 self.click_chess(0) self.Mouse = self.mouse2 self.click_chess(0) else: display.update() self.clock.tick() continue break
from pygame import time, event, MOUSEBUTTONDOWN, MOUSEBUTTONUP _Clic = [0, 0, 0, 0, 0, 0] _Ticks = [0, 0, 0, 0, 0, 0] LAPS = 200 time.Clock() def wait(): ev = event.wait() _foo(ev) return ev def poll(): ev = event.poll() _foo(ev) return ev def get(): ev = event.get() for e in ev: _foo(e) return ev def _foo(e): global _Clic, _Ticks if e.type == MOUSEBUTTONDOWN: t = time.get_ticks()
import pygame from pygame import time, event, MOUSEBUTTONDOWN, MOUSEBUTTONUP, NOEVENT, QUIT ### writen by josmiley #### _Clic = [0, 0, 0, 0, 0, 0] _Ticks = [ time.Clock(), time.Clock(), time.Clock(), time.Clock(), time.Clock(), time.Clock() ] LAPS = 200 _NoEvent_Clock = time.Clock() _Inactiv = 0 def wait(): ev = event.wait() _foo(ev) return ev def poll(): ev = event.poll() _foo(ev) return ev
TIME_BETWEEN_FISHES_O = 5000 DIFFICULTY = 0.97 # The near to 1 the easier. It will multiply to time_between_fishes every time a new fish is created MIN_TIME_BETWEEN_FISHES = 1000 POSX_SCORE = 100 POSY_SCORE = 100 # OBJECTS wormSelect = worm.worm('sel', POS_SEL, pygame) # PYGAME OBJECTS pygame.display.init() surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT),pygame.RESIZABLE) pygame.display.set_caption('HOOK') clock = GAME_TIME.Clock() pygame.font.init() textFont = pygame.font.Font("assets/fonts/Jelly Crazies.ttf", 20) # LOAD IMAGES imagesBackground = [ pygame.image.load("assets/images/background/background1.png"), pygame.image.load("assets/images/background/background2.png"), pygame.image.load("assets/images/background/background3.png"), pygame.image.load("assets/images/background/background4.png"), pygame.image.load("assets/images/background/background5.png"), pygame.image.load("assets/images/background/background4.png"), pygame.image.load("assets/images/background/background3.png"), pygame.image.load("assets/images/background/background2.png") ]
screen.blit(bulletImg, (x + 16, y + 10)) def isCollision(enemyX, enemyY, bulletX, bulletY): distance = math.sqrt( math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2))) if distance < 27: return True else: return False # In[] import pygame.time as pgTime ryClock = pgTime.Clock() ryLoopRate = 30 # loop/sec recProbToConfirm = 0.2 # Game Loop running = True while running: # 掌握一下這個 while 迴圈的 循環速度 fps= frames (loops) per sec dt = ryClock.tick(ryLoopRate) fps = ryClock.get_fps() #print(f'dt= {dt:.2f}, fps= {fps:.0f}') #< 語音辨識在此執行 ...., #y, prob= ryGet1secSpeechAndRecogItWithProb()
def main(): os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50, 30) pygame.init() display = pygame.display.set_mode((1000, 1000)) display.fill((0, 128, 255)) run = True clock = time.Clock() number = 100 dot = [] for i in range(number): dot.append(Dot()) counter = 1 while (run): counter += 1 if counter < 1000: if counter % 2 == 0: best = 0 for i in range(1, number): if dot[i].result > dot[best].result: best = i dot[0] = dot[best] for i in range(1, number): dot[i] = Dot(0, 0, dot[0].get_cXX(), dot[0].get_cXY(), dot[0].get_cYX(), dot[0].get_cYY(), dot[0].get_cXW(), dot[0].get_cYW()) else: for i in range(number): dot[i].update() pygame.display.set_caption(str(counter)) else: if counter % 100 == 0: best = 0 for i in range(1, number): if dot[i].result > dot[best].result: best = i dot[0] = dot[best] for i in range(1, number): dot[i] = Dot(0, 0, dot[0].get_cXX(), dot[0].get_cXY(), dot[0].get_cYX(), dot[0].get_cYY(), dot[0].get_cXW(), dot[0].get_cYW()) else: for i in range(number): dot[i].update() pygame.display.set_caption(" XX: " + str(dot[0].cXX) + " XY: " + str(dot[0].cXY) + " YX: " + str(dot[0].cYX) + " YY: " + str(dot[0].cYY) + " XW: " + str(dot[0].cXW) + " YW: " + str(dot[0].cYW)) display.fill((0, 180, 200)) for i in range(number): pygame.draw.circle(display, (255, 255, 255), dot[i].get_pos(), 2) pygame.draw.circle(display, (4, 5, 5), dot[i].goal, 7) pygame.display.flip() clock.tick(100) pygame.quit()
#end my import #from gui import Viewport from gui import Viewport from water import Graph libaudioverse.initialize() server = libaudioverse.Server() server.set_output_device("default") bgMusic = soundutil.SoundPlayer(server) bgAmbience = soundutil.SoundPlayer(server) bgmPath = "assets\\waterbending.wav" bgaPath = "assets\\underwater.wav" display.init() x, y = 1000, 800 screen = display.set_mode((x, y)) clock = time.Clock() v_graph = Graph(screen) keys = set() game_over = False bgMusic.play(bgmPath, True) bgAmbience.play(bgaPath, True) while not game_over: elapsed = clock.tick() / 1000 events = event.get() for curr_event in events: if curr_event.type == pygame.QUIT: game_over = True elif curr_event.type == pygame.KEYDOWN: if curr_event.key == pygame.K_ESCAPE:
def main(): """ The __main__ class utilizes a finite state machine structure to manage the overall flow of the game from start up to game ending. **States** There are five states that the game undergoes. The states and their interactions summarized: *Start*: The default state when the game is first run. This state creates the StartScreen, which asks players what board size they perfer and the number of mines on the board. This state will end either when the player quits the game with a state *Exit* or generates a game with a state *Minesweeper*. *Minesweeper*: This state runs when the player is actually playing minesweeper. This state monitors how the game is progressing. Once the player wins or loses, this state will record the outcome then change state. There are only two ways to change state - when the game is won or lost with a state *End* or when the player quits the game with a state *Exit*. *End*: This state throws up the appropirate end screen depending on whether or not the player won or lost. Then, awaits whether or not the player quits the game with a state *Exit* or starts a new game with state *Start*. *Exit*: This state exits out of the finite state machine and terminates the application. *CheatMode*: This state runs when the player enters cheat mode. This state shows the location of the mines and the number of the spaces with adjacent mines. When the user exits cheat mode it goes back to Minesweeper state **Args**: None. **Preconditions**: None. **Postconditions**: None. **Returns**: None. """ clock = time.Clock() State = Enum('State', 'Start Minesweeper End Exit CheatMode') currentState = State.Start startScreen = None minesweeper = None endScreen = None cheatMode = None x, y, mines = 0, 0, 0 while currentState != State.Exit: # Start mode if (currentState == State.Start): if startScreen is None: if minesweeper is None: startScreen = StartScreen() else: startScreen = StartScreen(x, y, mines) for newEvent in event.get(): if newEvent.type == constants.QUIT: currentState = State.Exit startScreen.render() clock.tick(60) if startScreen.gameReady: currentState = State.Minesweeper x, y, mines = startScreen.x_size, startScreen.y_size, startScreen.numMines minesweeper = Minesweeper(x, y, mines) startScreen = None ## Minesweeper game mode elif currentState == State.Minesweeper: for newEvent in event.get(): ## Change to Exit Mode if newEvent.type == constants.QUIT: currentState = State.Exit elif newEvent.type == constants.MOUSEBUTTONDOWN: (end, win) = minesweeper.onClick(newEvent) if end: ## Change to Start Mode if win is None: currentState = State.Start ## Change to End Mode else: currentState = State.End if not win: minesweeper.onLose() endScreen = EndScreen(win) ## Change to Cheat Mode elif win is None: pygame.mixer.stop() cheatGame = pygame.mixer.Sound("sounds/cheatmode.wav") cheatGame.play() minesweeper.cheatFlags() cheatMode = CheatMode() currentState = State.CheatMode minesweeper.render() clock.tick(60) ## End Mode elif currentState == State.End: endScreen.render() clock.tick(60) for newEvent in event.get(): if newEvent.type == constants.QUIT: currentState = State.Exit elif newEvent.type == constants.MOUSEBUTTONDOWN: currentState = State.Start endScreen = None ## Cheat Mode elif currentState == State.CheatMode: cheatMode.render() for newEvent in event.get(): if newEvent.type == constants.QUIT: currentState = State.Exit elif newEvent.type == constants.MOUSEBUTTONDOWN: minesweeper.undoCheatFlags() currentState = State.Minesweeper cheatMode = None else: currentState = State.Start print('Error: This really should never happen, resetting game...')
""" For using Pygame library and must be added before any other pygame function, else an initialization error may occur. There are a couple of additional imports (random, time) that are used in Game.py """ import sys import pygame from pygame import sprite, display, time, font, event from pygame.locals import * # pylint: disable=wildcard-import, unused-wildcard-import from gamemodels import Player, Goalkeeper, Ball from utility import load_image, position_from_center from constants import SCREEN_HEIGHT, SCREEN_WIDTH, WHITE, BLACK, BALL_SPEED, SCORE, counter pygame.init() FRAME_PER_SEC = time.Clock() # Setting up Fonts FONT = font.SysFont("Verdana", 60) FONT_SMALL = font.SysFont("Verdana", 20) GAME_OVER = FONT.render("Game Over", True, BLACK) BACKGROUND = load_image("pitch640x484.png") # Create a white screen DISPLAYSURF = display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) DISPLAYSURF.fill(WHITE) display.set_caption("Game") # Setting up Sprites P1 = Player()
nextLevelTS = 0 leftOverBullets = [] enemyShips = [] ship.health = ship.maxHealth ship.shields = ship.maxShields ship.bullets = [] def quitGame(): pygame.quit() sys.exit() # 'main' loop while True: GAME_TIME.Clock().tick(30) timeTick = GAME_TIME.get_ticks() mousePosition = pygame.mouse.get_pos() mouseStates = pygame.mouse.get_pressed() if gameStarted is True and gameOver is False: updateGame() drawGame() elif gameStarted is False and gameOver is False: surface.blit(startScreen, (0, 0)) if mouseStates[0] is 1: if mousePosition[0] > 445 and mousePosition[
if col == "t": target = Target(x, y-167) sprite_group.add(target) x += PLATFORM_SIZE y += PLATFORM_SIZE x = 0 # Настройка звука mixer.pre_init(44100, -16, 1, 512) mixer.init() sound = mixer.Sound('sounds/back.ogg') sound.play(-1) # Главный цикл main_loop = True timer = time.Clock() # Создаем меню clauses = [(270, 210, u'Game', (250, 250, 30), (250, 30, 250), 0), (270, 280, u'Quit', (250, 250, 30), (250, 30, 250), 1)] game = Menu(clauses) game.menu(window, screen, info_string) # Камера def camera_func(camera, target_rect): l = -target_rect.x + DISPLAY[0]/2
def withspeech(): playerX = 370 playerY = 480 playerX_change = 0 playerY_change = 0 bulletX = 0 bulletY = 480 bulletX_change = 0 bulletY_change = 10 bullet_state = "ready" textX = 10 testY = 10 global history history = [] global ttl_history ttl_history = " " global score_value ryClock = pgTime.Clock() ryLoopRate = 30 # loop/sec recProbToConfirm = 0.2 running = True while running: # 掌握一下這個 while 迴圈的 循環速度 fps= frames (loops) per sec dt = ryClock.tick(ryLoopRate) fps = ryClock.get_fps() #print(f'dt= {dt:.2f}, fps= {fps:.0f}') #< 語音辨識在此執行 ...., # #y, prob= ryGet1secSpeechAndRecogItWithProb() # #'ryQ', 'ryRecogQGet' yL = ryRecogQGet(ryQ) #print(yL) recResult = y = '' prob = 0.0 for y, prob in yL: recResult = y if prob > recProbToConfirm: if y == 'left': playerX_change = -1 ck_history(y) elif y == 'right': playerX_change = +1 ck_history(y) elif y == 'up': playerY_change = -1 ck_history(y) elif y == 'down': playerY_change = +1 ck_history(y) elif y in ['yes', 'on', 'go']: ck_history(y) if bullet_state == "ready": bulletSound = mixer.Sound(dataBasePath + "laser.wav") bulletSound.play() # Get the current x cordinate of the spaceship bulletX = playerX bulletY = playerY fire_bullet(bulletX, bulletY) elif y in ['no', 'off', 'stop']: ck_history(y) playerX_change = 0 playerY_change = 0 else: pass #> 語音辨識在此執行 .... # RGB = Red, Green, Blue win.fill((0, 0, 0)) # Background Image win.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if keystroke is pressed check whether its right or left if event.type == pygame.KEYDOWN: playerY_change = -5 if event.key == pygame.K_LEFT: playerX_change = -5 playerImg = pygame.image.load('player_l.png') if event.key == pygame.K_RIGHT: playerX_change = 5 playerImg = pygame.image.load('player_r.png') if event.key == pygame.K_SPACE: if bullet_state == "ready": bulletSound = mixer.Sound("laser.wav") bulletSound.play() # Get the current x cordinate of the spaceship bulletX = playerX fire_bullet(bulletX, bulletY) if event.type == pygame.KEYUP: playerY_change = 5 # 5 = 5 + -0.1 -> 5 = 5 - 0.1 # 5 = 5 + 0.1 playerX += playerX_change if playerX <= 0: playerX = 0 elif playerX >= 736: playerX = 736 playerY += playerY_change if playerY <= 0: playerY = 0 elif playerY >= 480: playerY = 480 # Apple Movement for i in range(num_of_apples): # Game Over if appleY[i] > 440: for j in range(num_of_apples): appleY[j] = 2000 game_over_text() break appleX[i] += appleX_change[i] if appleX[i] <= 0: appleX_change[i] = 4 appleY[i] += appleY_change[i] elif appleX[i] >= 736: appleX_change[i] = -4 appleY[i] += appleY_change[i] # Collision collision = isCollision(appleX[i], appleY[i], bulletX, bulletY) if collision: explosionSound = mixer.Sound("coin.wav") explosionSound.play() score_value += 1 appleX[i] = random.randint(0, 736) appleY[i] = random.randint(50, 150) apple(appleX[i], appleY[i], i) # Bullet Movement if bulletY <= 0: bulletY = 480 bullet_state = "ready" if bullet_state == "fire": fire_bullet(bulletX, bulletY) bulletY -= bulletY_change history_label = font.render(ttl_history, True, (30, 30, 255)) win.blit(history_label, (10, 550)) player(playerX, playerY) show_score(textX, testY) ryShow_recognition(playerX, playerY, recResult=recResult) pygame.display.update() pygame.quit() ryStream.stop() ryStream.close()