コード例 #1
0
def run_game():

	# Initialize game and create a screen object.

	pygame.init()
	ai_settings = Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
	
	pygame.display.set_caption("Zombie Tower Ultimate Sonic The Next Generation Super EX")
	play_button = Button(ai_settings, screen, "Play")
	# Set the background color
	ship = Ship(screen, ai_settings)
	bullets = Group()
	bomb = Group()
	lasercheat = Group()
	nuke = Nuke(ai_settings, screen, ship)
	block = Block(ai_settings, screen, nuke)
	wall = Wall(ai_settings, screen, ship)
	lift = Lift(ai_settings, screen, nuke)
	aliens = Group()
	alien = Alien(ai_settings, screen)
	# Start the main loop for the game.
	stats = GameStats(ai_settings, bomb, aliens, bullets)
	sb = Scoreboard(ai_settings, screen, stats)
	gf.create_fleet(ai_settings, screen, ship, aliens)

	while True:

		# Watch for keyboard and mouse events.
		gf.check_events(ai_settings, screen, stats, ship, bullets, lasercheat, aliens, nuke, play_button, bomb, wall, lift)
		if stats.game_active:
			ship.update()
			gf.update_aliens(ai_settings, stats, screen, ship, aliens, bomb, wall)
			ai_settings.counterpnts -= 1
			if ai_settings.counterpnts <=0:
				ai_settings.counterpnts = 60
				stats.score += 1
				sb.prep_score()
			bullets.update()
			bomb.update(aliens, ai_settings, screen)
		gf.update_screen(ai_settings, screen, stats, sb, ship, bullets, lasercheat, aliens, nuke, play_button, wall, bomb, lift, block)
		# Get rid of bullets that have disappeared.

		for bullet in bullets.copy():
			if bullet.rect.right >= 1200:
				bullets.remove(bullet)
		print(len(bullets))
コード例 #2
0
ファイル: pong.py プロジェクト: progworkshop/pong
    def __init__(self, width=640, height=480, title="Prog Workshop - Pong!"):
        pygame.init()

        # Sets key repeat to a max of once every 5 ms
        #pygame.key.set_repeat(5, 5)
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption(title)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self._running = True
        
        self.player1 = Paddle(0,0,20,100,self)
        self.player2 = Paddle(width-20,0,20,100,self)
        
        self.ball = Ball(width/2,height/2,20,20,self)
        self.ball.setSpeed(random.random()*14-7, random.random()*14-7)

        self.balls = []

        self.score = Scoreboard(self, 36)
コード例 #3
0
 def __init__(self, x, y, game):
     Window.__init__( self, x, y, 200, 2) 
     
     Visettings.Speed = -1
     
     if Visettings.AutoEnd :
         Visettings.CurrentMode = VISMODE.PLAY
     else:
         Visettings.CurrentMode = VISMODE.PAUSE
     
     Visettings.MaxX = game.states[0].boardX-1
     Visettings.MaxY = game.states[0].boardY-1
     
     Visettings.Player1Name = game.getName(0)
     Visettings.Player2Name = game.getName(0)
     
     Visettings.Game = game
     
     self.Window.erase()
     self.Window.refresh()
     
     self.moveWindow( x, Visettings.MaxY*2+4 )
     
     self.score = Scoreboard( x+Visettings.MaxX*2+5, y, 31, Visettings.MaxY*2+4 )
     self.gameboard = Gameboard( x, y, Visettings.MaxX*2+4, Visettings.MaxY*2+4 )
     self.plantInfo = Plantinfo( x+Visettings.MaxX*2+5+31, y, 32, Visettings.MaxY+1 )
     self.minimap = Minimap( \
     x+Visettings.MaxX*2+5+31+30/2 - Visettings.MaxX/2, \
     Visettings.MaxY+1, \
     Visettings.MaxX+3, \
     Visettings.MaxY+3 )
     
     Visettings.CurX = 0
     Visettings.CurY = 0
     
     self.Window.erase()
コード例 #4
0
ファイル: main.py プロジェクト: sfranz2422/snake
from turtle import Screen
from snake import *
import time
from food import Food
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True

while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    #detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
コード例 #5
0
ファイル: Main.py プロジェクト: 0giru/python_practice
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import random
import time

screen = Screen()
paddle = Paddle()
ball = Ball()
scoreboard = Scoreboard()

# index 0 paddle on the right
paddle.create_paddle(-350)
paddle.create_paddle(350)
ball.create_ball()

screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("My PingPong Game")
screen.listen()

screen.onkey(paddle.go_up1, "w")
screen.onkey(paddle.go_down1, "s")
screen.onkey(paddle.go_up2, "p")
screen.onkey(paddle.go_down2, ";")

screen.tracer(0)

Game_On = True
コード例 #6
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

player = Player()
scoreboard = Scoreboard()
car_manager = CarManager()

screen.listen()
screen.onkey(player.move, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()

    car_manager.create_car()
    car_manager.move_cars(scoreboard.get_level())
    if car_manager.detect_collision(player):
        scoreboard.game_over()
        game_is_on = False

    if player.has_cleared_level():
        scoreboard.increase_level()
コード例 #7
0
ファイル: main.py プロジェクト: Vai2021/100daysofCode
from paddle import Paddle
from ball import Ball
import time
from scoreboard import Scoreboard

screen = Screen()
screen.setup(800, 600)
screen.bgcolor("Black")
screen.title("Pong")
screen.tracer(
    0)  # turn off the animation , now we have to update our screen manually

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    # detect the collision with wall
    if ball.ycor() > 280 or ball.ycor() < -280:
コード例 #8
0
class AlienInvasion:
    """Common class to manage game assets and behavior"""
    def __init__(self):
        """Initialize game and create game resources."""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        # self.screen = pygame.display.set_mode(
        #     (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Вторжение инопланетян")
        # Create an instance to store game statistics,
        #   and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        # Play Button
        self.play_button = Button(self, "Играть")

    def run_game(self):
        """Start main loop for the game"""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update_status()
                self.bullets.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _check_events(self):
        """Respond to keypress and mouse movements"""
        # Watch for keyboard and mouse movements
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)

        if button_clicked and not self.stats.game_active:
            self._start_game()

    def _start_game(self):
        # Reset stats
        self.settings.difficulty(1)  # available diff levels : 3
        self.stats.reset_stats()
        self.stats.game_active = True
        self.sb.prep_score()
        self.sb.prep_level()
        self.sb.prep_ships()

        self.aliens.empty()
        self.bullets.empty()

        self._create_fleet()
        self.ship.center_ship()
        # Hide mouse
        pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Respond to keypress"""
        # If the player presses both keys at once, two separate events will be detected.
        # We can use elif blocks here because each event is connected to only one key.
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        # Enable and disable fullscreen mode
        elif event.key == pygame.K_p:
            self._start_game()
        elif event.key == pygame.K_f:
            if self.screen.get_flags() and pygame.FULLSCREEN:
                self.screen = pygame.display.set_mode(
                    (self.settings.screen_width, self.settings.screen_height))
            else:
                self.screen = pygame.display.set_mode((0, 0),
                                                      pygame.FULLSCREEN)
                self.settings.screen_width = self.screen.get_rect().width
                self.settings.screen_height = self.screen.get_rect().height

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        # Upd bullet positions
        self.bullets.update()
        # Remove bullets that have disappeared
        for bullet in self.bullets.copy():
            if bullet in self.bullets.copy():
                if bullet.rect.bottom <= 0:
                    self.bullets.remove(bullet)
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
                self.sb.prep_score()
                self.sb.check_high_score()
        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            # Increase level
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        self._check_aliens_bottom()

    def _ship_hit(self):
        if self.stats.ships_left > 0:
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            self.aliens.empty()
            self.bullets.empty()
            # Create new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()
            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_screen(self):
        """Upd images on the screen, and flip to the new screen"""
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        self.sb.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible. This will update the contents of the entire display.
        pygame.display.flip()
コード例 #9
0
class AlienInvasion:

    #init game resources
    def __init__(self):
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        #create an instance to store game stats and scoreboard
        self.stats = GameStats(self)
        self.scoreboard = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        #Make play button
        self.play_button = Button(self, "Play")

    #game loop
    def run_game(self):
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    #update bullets helper
    def _update_bullets(self):
        self.bullets.update()

        #Eradicate bulets after they've left the screen
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    #Respond to collisions between aliens and bullets
    def _check_bullet_alien_collisions(self):
        #If a bullet hits an alien remove the alien and the bullet
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points
            self.scoreboard.prep_score()
            self.scoreboard.check_high_score()

        #when the fleet is dead get rid of bullets and regenerate fleet
        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            #increase level
            self.stats.level += 1
            self.scoreboard.prep_level()

    #update aliens helper
    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        #handle alien and ship collision
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        self._check_aliens_bottom()

    #Respond if ship is hit by alien
    def _ship_hit(self):
        if self.stats.ships_left > 0:
            #decrement ships_left
            self.stats.ships_left -= 1
            self.scoreboard.prep_ships()

            #get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    #handle event input
    def _check_events(self):
        #user input
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                self._check_keydown_event(event)

            elif event.type == pygame.KEYUP:
                self._check_keyup_event(event)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    #handle keydown events
    def _check_keydown_event(self, event):
        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
            self.ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        elif event.key == pygame.K_q:
            sys.exit()

    #handle keyup events
    def _check_keyup_event(self, event):
        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
            self.ship.moving_left = False

    #Start new game when player presses play
    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            #reset game settings
            self.settings.init_dynamic_settings()

            #reset game stats
            self.stats.reset_stats()
            self.stats.game_active = True
            self.scoreboard.prep_score()
            self.scoreboard.prep_level()
            self.scoreboard.prep_ships()

            #get rid of remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #hide mouse
            pygame.mouse.set_visible(False)

    #create new bullet and add it to group
    def _fire_bullet(self):
        if len(self.bullets) < self.settings.bullet_capactiy:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    #create fleet of aliens
    def _create_fleet(self):
        #create an alien and find the number of aliens in a row
        #spacing between each alien is equal to one alien width
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        #determine number of rows of aliens that fit on screen
        ship_height = self.ship.rect.height
        available_space_y = self.settings.screen_height - (
            3 * alien_height) - ship_height
        number_rows = available_space_y // (2 * alien_height)

        #create fleets of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    #create a single alien and place it accordingly
    def _create_alien(self, alien_number, row_number):
        #Create alien and place it the row
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    #Check if aliens have reached bottom of the screen
    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    #change direction if aliens have reached edge
    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    #change fleet direction and drop them down
    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_screen(self):
        #redraw screen
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

        #draw bullets
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        #draw score inforation
        self.scoreboard.show_score()

        #draw play button when game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()

        #draw new screen
        pygame.display.flip()
コード例 #10
0
ファイル: main.py プロジェクト: Gyorgy1988/100-Days-of-Code
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(height=600, width=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
score = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")


game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food.
    if snake.head.distance(food) < 15:
コード例 #11
0
ファイル: main.py プロジェクト: Galtron-OpenSource/Galtron-1
def runGame():
    #Initialize game and create a window
    pg.init()
    #create a new object using the settings class
    setting = Settings()
    #creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))
    #set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    playBtn = Button(setting, screen, "PLAY", 200)
    menuBtn = Button(setting, screen, "MENU", 250)
    twoPlayBtn = Button(setting, screen, "2PVS", 250)
    setBtnbtn = Button(setting, screen, "SETTING", 400)
    aboutBtn = Button(setting, screen, "ABOUT", 300)
    quitBtn = Button(setting, screen, "QUIT", 350)
    #make slector for buttons
    sel = Selector(setting, screen)
    sel.rect.x = playBtn.rect.x + playBtn.width + 10
    sel.rect.centery = playBtn.rect.centery

    #Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    #Make a ship
    ship = Ship(setting, screen)
    #Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    #make a group of bullets to store
    bullets = Group()
    eBullets = Group()

    #Make an alien
    aliens = Group()
    gf.createFleet(setting, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    runGame = True

    #Set the two while loops to start mainMenu first
    while runGame:
        #Set to true to run main game loop
        while stats.mainMenu:
            mm.checkEvents(setting, screen, stats, sb, playBtn, twoPlayBtn,
                           aboutBtn, quitBtn, menuBtn, sel, ship, aliens,
                           bullets, eBullets)
            mm.drawMenu(setting, screen, sb, playBtn, menuBtn, twoPlayBtn,
                        aboutBtn, quitBtn, sel)

        while stats.mainGame:
            #Game functions
            gf.checkEvents(setting, screen, stats, sb, playBtn, quitBtn, sel,
                           ship, aliens, bullets, eBullets)  #Check for events
            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship, aliens,
                                bullets, eBullets)  #Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens,
                                 bullets, eBullets)  #Update collisions
                ship.update()  #update the ship
            gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets,
                            eBullets, playBtn, menuBtn, quitBtn,
                            sel)  #Update the screen

        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb, playBtn, quitBtn,
                              menuBtn, sel, ship, aliens, bullets, eBullets)
            About.drawMenu(setting, screen, sb, menuBtn, quitBtn, sel)

        while stats.twoPlayer:
            """
			tp.checkEvents(setting, screen, stats, playBtn, quitBtn, sel, bullets, eBullets, ship1, ship2)
			if stats.gameActive:
				ship1.update()
				tp.updateBullets(setting, screen, stats, ship1, ship2, bullets, eBullets)
			tp.updateScreen(setting, screen, stats, bullets, eBullets, playBtn, menuBtn, quitBtn, sel, ship1, ship2)
			"""
        while stats.mainGame:
            if runGame == True:
                print("test")
コード例 #12
0
ファイル: main.py プロジェクト: alexanderejohnson/pong_game
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)

user_paddle = Paddle((350, 0))
comp_paddle = Paddle((-350, 0))
# TODO: Add comp_paddle automation
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(user_paddle.up, "Up")
screen.onkey(user_paddle.down, "Down")

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.movement()

    # Detect collision with top and bottom wall
    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce_y()
コード例 #13
0
class AlienInvasion:
    '''Overall class to manage game assets and behavior'''

    def __init__(self):
        '''Initialize the game, and create game resources'''
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        #create an instance to store game statistics
        # and create a scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self.play_button = Button(self,"Play")

    def run_game(self):
        '''Start the main loop for the game'''
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()
    
    def _check_events(self):
        """Respond to keypresses and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)                
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    
    def _check_play_button(self, mouse_pos):
        """start a new game when the player clicks play"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:

            #reset the game settings
            self.settings.initialize_dynamic_settings()

            # reset the game statistics
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            #get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #hide the mouse cursor
            pygame.mouse.set_visible(False)

    
    def _check_keydown_events(self,event):
        """Respond to keypresses"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    
    def _check_keyup_events(self,event):
        """Respond to key releases"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
                    
    
    def _create_fleet(self):
        """Create the fleet of aliens"""
        # make an alien
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # create the first row of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)
            


    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """respond appropriately if any aliens have reached an edge"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """drop the entire fleet and change the fleet's direction"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    
    def _ship_hit(self):
        """respond to the ship being hit by an alien"""
        if self.stats.ships_left > 0:
            #decrement ships left and update scoreboard
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            #get rid of any remaining aliens and bullets
            self.aliens.empty()
            self.bullets.empty()

            #create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            #pause
            sleep(0.5)
        
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
        

    def _update_aliens(self):
        """update the positions of all aliens in the fleet"""
        self._check_fleet_edges()
        self.aliens.update()

        # look for alien - ship collisions
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # look for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _fire_bullet(self):
        """Create new bullet and add it to the bullets group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    
    def _update_bullets(self):
        """Update the positions of bullets and get rid of old bullets"""
        #Update bullet positions
        self.bullets.update()

            #Get rid of bullets that have dissapeared
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet alien collisions"""
        #check for bullets that have hit aliens
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score
        
        if not self.aliens:
            #destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # increase level
            self.stats.level += 1
            self.sb.prep_level()

    
    def _check_aliens_bottom(self):
        """check if any aliens have reached the bottom of the screen"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                #treat this the  same as if the ship was hit
                self._ship_hit()
                break


    def _update_screen(self):
        """Update on images on the screen, and flip to next screen"""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)

        #draw the score information
        self.sb.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

         # make the most recently drawn screen visible
        pygame.display.flip()
コード例 #14
0
ファイル: space_pew.py プロジェクト: Tepah/Space_Pew
class SpacePew:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initialize the game, and game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height)
        )
        pygame.display.set_caption("Space Pew")

        # Create an instance to store game stats and create a scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.wind = pygame.sprite.Group()
        self.drops = pygame.sprite.Group()
        self.projectiles = pygame.sprite.Group()
        self.clock = self.settings.clock

        # Make the Play button.
        self.play_button = Button(self, "Play")

        # Make the Normal and Hard Difficulty buttons.
        self.normal_button = Button(self, "Peewee")
        self.hard_button = Button(self, "REAL PP")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self.clock.tick(self.settings.fps)
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._fire_bullet()
                if self.bullets:
                    self._update_bullets()
                if self.drops:
                    self._update_drops()
                if self.projectiles:
                    self._update_projectiles()
                self._update_aliens()
                if self.settings.spawn_ship:
                    self.ship.ship_spawn()
                    self.settings.spawn_ship = False

            self._blow_wind()
            self._update_wind()
            self._update_screen()

    def _check_events(self):
        """Responds to keypresses and mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                if not self.stats.game_active \
                        and not self.stats.difficulty_menu:
                    self._check_play_button(mouse_pos)
                elif self.stats.difficulty_menu:
                    self._check_difficulty_menu(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when a player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked:
            # Shows the difficulty buttons
            self.stats.difficulty_menu = True

    def _check_difficulty_menu(self, mouse_pos):
        if self.normal_button.rect.collidepoint(mouse_pos):
            # Reset the game settings.
            self.settings.initialize_dynamic_settings()
            self._start_game()
            self.stats.difficulty_menu = False
        elif self.hard_button.rect.collidepoint(mouse_pos):
            # Starts game in HARD MODE
            self.settings.initialize_dynamic_settings()
            self.settings.hard_mode_settings()
            self._start_game()
            self.stats.difficulty_menu = False

    def _start_game(self):
        # Reset the game statistics.
        self.stats.reset_stats()
        self.stats.game_active = True

        self._clean_slate()
        self.ship.ship_spawn()

        self.sb.prep_score()
        self.sb.prep_level()
        self.sb.prep_ships()

        # Hide the mouse cursor.
        pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Responds to keypresses"""
        if event.key == pygame.K_d:
            self.ship.moving_right = True
        elif event.key == pygame.K_a:
            self.ship.moving_left = True
        elif event.key == pygame.K_w:
            self.ship.moving_up = True
        elif event.key == pygame.K_s:
            self.ship.moving_down = True
        elif event.key == pygame.K_ESCAPE:
            sys.exit()
        elif event.key == pygame.K_k:
            self._continue_shooting()
        elif event.key == pygame.K_EQUALS:
            self.settings.switch_god_bullet()
        elif event.key == pygame.K_p:
            if not self.stats.game_active:
                self._start_game()

    def _continue_shooting(self):
        if not self.ship.is_shooting:
            self.ship.is_shooting = True
        else:
            self.ship.is_shooting = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed and \
                self.ship.is_shooting and self.settings.bullet_counter % 5 == 0:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)
        self.settings.bullet_counter += 1

    def _blow_wind(self):
        if len(self.wind) < self.settings.wind_limit and \
                self.settings.wind_counter % 200 == 0:
            new_wind = Wind(self)
            self.wind.add(new_wind)
        self.settings.wind_counter += 1

    def _check_keyup_events(self, event):
        """Responds to Key releasing"""
        if event.key == pygame.K_d:
            self.ship.moving_right = False
        elif event.key == pygame.K_a:
            self.ship.moving_left = False
        elif event.key == pygame.K_w:
            self.ship.moving_up = False
        elif event.key == pygame.K_s:
            self.ship.moving_down = False

    def _update_bullets(self):
        """Update position of bullets and get rid of old bullets."""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _update_drops(self):
        """Update the position of the drops and get rid of old drops"""
        # update drop position
        self.drops.update()

        collided_drops = pygame.sprite.spritecollide(self.ship, self.drops, False
                                                     )

        for drop in collided_drops:
            self._check_drop(drop)

        # Get rid of drops that are gone
        for drop in self.drops.copy():
            if drop.rect.top >= self.settings.screen_height:
                self.drops.remove(drop)

    def _check_drop(self, drop):
        if drop.type == 'upgrade':
            self.ship.upgrade_bullet()
        elif drop.type == 'pierce':
            self.ship.upgrade_pierce()
        elif drop.type == 'bigger':
            self.ship.upgrade_bigger()
        elif drop.type == 'smaller':
            self.ship.upgrade_smaller()
        elif drop.type == 'more':
            self.ship.upgrade_amount()
        self.drops.remove(drop)

    def _update_projectiles(self):
        """Moves the bullets down and deletes any that fall out"""
        self.projectiles.update()

        # Deletes the projectiles that fall out of screen
        for projectile in self.projectiles.copy():
            if projectile.rect.top >= self.settings.screen_height:
                self.projectiles.remove(projectile)

        if pygame.sprite.spritecollideany(self.ship, self.projectiles):
            self._ship_hit()

    def _check_bullet_alien_collisions(self):
        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien.
        collisions = pygame.sprite.groupcollide(
            self.bullets, self.aliens, False, False)
        drop_determine = -1

        if collisions:
            for bullets, aliens in collisions.items():
                self._health_deplete(aliens, bullets, drop_determine)
            self.sb.prep_score()
            self.sb.check_high_score()

        # Checks if aliens are all dead
        if not self.aliens and self.ship.rect.y >= 600:
            self._respawn_aliens()

    def _health_deplete(self, aliens, bullets, drop_determine):
        """
        Checks if the alien health is depleted and deletes
        if health reaches 0
        """
        for alien in aliens:
            # Checks if the bullet has hit this alien before.
            if bullets.prev_alien != alien:
                if alien.health - \
                        bullets.settings.bullet_damage <= 0:
                    self.aliens.remove(alien)
                    self.stats.score += self.settings.alien_points \
                        * len(aliens)
                    drop_determine = randint(1, 100)
                else:
                    # Lowers the health if not quite at 0
                    alien.health -= \
                        bullets.settings.bullet_damage
                # Checks if bullets have pierce
                # and how many times it can pierce
                if bullets.pierce > 0:
                    bullets.pierce -= 1
                    bullets.set_pierced_alien(alien)
                else:
                    # Deletes the bullet if it hits an alien with no pierce
                    self.bullets.remove(bullets)
                if drop_determine > 0:
                    self._determine_drop(alien, drop_determine)

    def _determine_drop(self, alien, drop_determine):
        # Determines the drop rate for each item.
        if drop_determine <= 15:
            new_drop = Drops(self, alien)
            if drop_determine <= 4:
                # Drops the damage increase drop
                new_drop.upgrade_drop()
            elif drop_determine <= 6:
                # Drops the pierce increase drop
                new_drop.pierce_drop()
            elif drop_determine <= 9:
                # Drops the increasing size drop
                new_drop.bigger_drop()
            elif drop_determine <= 12:
                # Drops the decreasing size drop
                new_drop.smaller_drop()
            elif drop_determine <= 15:
                # Drop the increasing amount drop""
                new_drop.more_drop()
            self.drops.add(new_drop)

    def _respawn_aliens(self):
        """Destroy existing bul/proj/drops and create a new fleet."""
        self._clean_slate()

        # Increase level and difficulty
        self.stats.level += 1
        self.settings.increase_difficulty(self.stats.level)
        self.sb.prep_level()

    def _update_aliens(self):
        """Check if the fleet is at the edge, then
        Update the position of the aliens in the fleet"""
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Random variable shooter
        for alien in self.aliens:
            if len(self.projectiles) < self.settings.alien_projectile_limit:
                determine_num = randint(1, 100)
                if determine_num < 10 and\
                        self.settings.alien_projectile_counter %\
                        self.settings.alien_projectile_shoot == 0:
                    new_projectile = AlienProjectile(self, alien)
                    self.projectiles.add(new_projectile)
                self.settings.alien_projectile_counter += 1

        # Look for aliens hitting the bottom of the screen.
        self._check_alien_bottom()

    def _update_wind(self):
        """Update the position of the wind particles and gets rid of them"""
        self.wind.update()

        # Get rid of the wind that disappear
        for air in self.wind.copy():
            if air.rect.top > self.settings.screen_height:
                self.wind.remove(air)

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""

        if self.stats.ships_left > 0:
            # Decrement ships_left
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            self._clean_slate()

            # Pause.
            sleep(0.5)
            self.settings.spawn_ship = True
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        """Create a fleet of aliens"""
        # Make an Alien.
        # Spacing between each alien is equal to one alien width.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - \
            (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height -
                             (3 * alien_height) - ship_height)
        number_rows = available_space_y // (3 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height \
            * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """Respond appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _check_alien_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom > screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _clean_slate(self):
        """Resets all aspects to reset positioning"""
        # Get rid of any remaining aliens, bullets, projectiles, and drops
        self.aliens.empty()
        self.bullets.empty()
        self.projectiles.empty()
        self.drops.empty()

        # Create a new fleet and center the ship.
        self._create_fleet()

    def _update_screen(self):
        """Update images on screen and flips to new screen"""
        self.screen.fill(self.settings.bg_color)
        for air in self.wind.sprites():
            air.draw_wind()
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        for drop in self.drops.sprites():
            drop.draw_drop()
        for projectile in self.projectiles.sprites():
            projectile.draw_projectile()
        self.aliens.draw(self.screen)

        # Draw the score information.
        self.sb.show_score()

        # Draw the play button if the game is inactive.
        if not self.stats.game_active and not self.stats.difficulty_menu:
            self.play_button.draw_play_button()
        elif self.stats.difficulty_menu and not self.stats.game_active:
            # Draws the difficulty buttons
            self.normal_button.draw_button(0, -60)
            self.hard_button.draw_button(0, 60)

        pygame.display.flip()
コード例 #15
0
from paddle import Paddle
from ball import Ball
from brick_manager import BrickManager
from scoreboard import Scoreboard
import time

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=800)
screen.title("Breakout")
screen.tracer(0)

bricks = BrickManager()
paddle = Paddle()
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(paddle.move_left, "Left")
screen.onkey(paddle.move_right, "Right")

game_over = False

while not game_over:
    screen.update()
    time.sleep(ball.move_speed)
    ball.move()

    # Detect collision with walls:
    if ball.xcor() >= 380 or ball.xcor() <= -380:
        ball.bounce_x()
コード例 #16
0
ファイル: alien_invasion.py プロジェクト: gitr-hub/alienINV
class AlienInvasion:
    """
    Overall class to manage game assets and behavior.
    """
    def __init__(self):
        """
        Initialize the game, and create class variables.
        :type self: class function accessable across class
        :param self: class namespace
        """
        pygame.init()
        """
        Class dependancy = pygame
        """
        self.settings = Settings()
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.screen = pygame.display.set_mode((self.settings.screen_width,
        #                                       self.settings.screen_height))
        self.screen = pygame.display.set_mode((1200, 800))
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien Invasion")
        """
        Create an instance to store game statistics,
        and create a scoreboard.
        """
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()
        """
        Make the Play button.
        """
        self.play_button = Button(self, "Play")
        """
        Set the background color.
        """
        self.bg_color = (230, 230, 230)
        self.ship.blitme()

    def run_game(self):
        """
        Start the main loop for the game.
        """
        while True:
            self._check_events()
            # print(f"self._check_events() = {self._check_events()}")
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            else:
                self._check_events()
#                pass
#                print("Ships Depleted ---- End Game")
#                sys.exit()
            self._update_screen()

    def _check_events(self):
        """
        EVENT LOOP: Watch for keypresses and mouse events.
        :meta public:
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """
        Start a new game when the player clicks Play.
        :type mouse_pos: 'int'
        :param mouse_pos: the position of the mouse
        :meta public:
        """

        # 3456789012345678901234567890123456789012345678901234567890123456789012345678
        # -------v---------v---------v---------v---------v---------v---------v-------|

        if self.play_button.rect.collidepoint(mouse_pos):
            #            self.stats.game_active = True
            button_clicked = self.play_button.rect.collidepoint(mouse_pos)
            print(f"Button Clicked: {button_clicked}")
            print(f"In condition: if self.play_button.rect.collidepoint \
                                                                (mouse_pos)")
            print(f"Check Play Button State: {self.stats.game_active}")
            if button_clicked and not self.stats.game_active:
                # Reset the game settings.
                self.settings.initialize_dynamic_settings()
                print(f"In condition: if button_clicked and not \
                                                     self.stats.game_active")
                print(f"Check Play Button State: {self.stats.game_active}")
                """
                Reset the game statistics.
                """
                self.stats.reset_stats()
                self.stats.game_active = True
                self.sb.prep_score()
                self.sb.prep_level()
                self.sb.prep_ships()
                """
                Get rid of any remaining aliens and bullets.
                """
                self.bullets.empty()
                """
                Create a new fleet and center the ship.
                """
                self._create_fleet()
                self.ship.center_ship()
                """
                Hide the mouse cursor.
                """
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        # print("Entered _check_keydown_events")
        """
        Respond to keypresses.
        :meta public:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            print("User quit game!!")
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        # print("Entered _check_keyup_events")
        """
        Respond to key releases.
        :meta public:
        """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        # print("Entered _fire_bullet")
        """
        Create a new bullet and add it to the bullets group.
        :meta public:
        """
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        # print("Entered _update_bullets")
        """
        Update position of bullets and get rid of old bullets.
        :meta public:

        Update bullet positions.
        """
        self.bullets.update()
        """
        Get rid of bullets that have disappeared.
        """
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        self._check_bullet_alien_collisions()
        # print(len(self.bullets))  # REVIEW CHECK BULLET REMOVAL AT TOP

    def _check_bullet_alien_collisions(self):
        # print("Entered _check_bullet_alien_collisions")
        """
        Respond to bullet-alien collisions.
        :meta public:

        Remove any bullets and aliens that have collided.
        Check for any bullets that have hit aliens.
        If so, get rid of the bullet and the alien.
        """
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()
        if not self.aliens:
            """
            Destroy existing bullets and create new fleet.
            """
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()
            """
            Increase level
            """
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """
        Check if the fleet is at an edge,
        then update the positions of all aliens in the fleet.
        :meta public:
        """
        self._check_fleet_edges()
        self.aliens.update()
        """
        Look for alien-ship collisions.
        """
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
            # print("Ship Hit")
        """
        Look for aliens hitting the bottom of the screen.
        """
        self._check_aliens_bottom()

    def _create_fleet(self):
        # print("Entered _create_fleet")
        """
        Create the fleet of aliens.
        :meta public:

        Create an alien and find the number of aliens in a row.
        Spacing between each alien is equal to one alien width.

        Make an alien.
        """
        alien = Alien(self)
        self.aliens.add(alien)  #REVIEW
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)
        """
        Determine the number of rows of aliens that fit on the screen.
        """
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - \
                             (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)
        """
        Create the full fleet of aliens.
        """
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        # print("Entered _create_alien")
        """
        Create an alien and place it in the row.
        :meta public:
        """
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        # print("Entered _check_fleet_edges")
        """
        Respond appropriately if any aliens have reached an edge.
        :meta public:
        """
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        # print("Entered _change_fleet_direction")
        """
        Drop the entire fleet and change the fleet's direction.
        :meta public:
        """
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
            self.settings.fleet_direction *= -1

    def _ship_hit(self):
        # print("Entered _ship_hit")
        """
        Respond to the ship being hit by an alien.
        :meta public:
        """
        if self.stats.ships_left > 0:
            """
            Decrement ships_left and update scoreboard.
            """
            self.stats.ships_left -= 1
            self.sb.prep_ships()
            """
            Get rid of any remaining aliens and bullets.
            """
            self.aliens.empty()
            self.bullets.empty()
            """
            Create a new fleet and center the ship.
            """
            self._create_fleet()
            self.ship.center_ship()
            """
            Pause.
            """
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)
            self.settings.increase_speed()

    def _check_aliens_bottom(self):
        # print("Entered _check_aliens_bottom")
        """
        Check if any aliens have reached the bottom of the screen.
        :meta public:
        """
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                """
                Treat this the same as if the ship got hit.
                """
                self._ship_hit()
                break

    def _update_screen(self):
        # print("Entered _update_screen")
        """
        Update images on the screen, and flip to the new screen.
        :meta public:

        Redraw the screen during each pass through the loop.
        """
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        """
        Draw the score information.
        """
        self.sb.show_score()
        """
        Draw the play button if the game is inactive.
        """
        # print(f"Game State: {self.stats.game_active}")
        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()
コード例 #17
0
from turtle import Screen
import time
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

player = Player()
car_manager = CarManager()
scoreboard = Scoreboard()
car_manager.generate_car()

screen.listen()
screen.onkey(key="Up", fun=player.move_forward)
screen.onkey(key="Down", fun=player.move_backward)

while player.alive:
    time.sleep(0.1)
    screen.update()

    car_manager.generate_car()
    car_manager.move_cars(player)

    if player.is_at_finish_line():
        player.go_to_start()
        scoreboard.update_level()
        car_manager.go_faster()
コード例 #18
0
def run_game():
    #Initialize game and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #Turn on music
    pygame.mixer.music.load('sound/Savannah.wav')
    pygame.mixer.music.play(-1)

    #Make the play button
    play_button = Button(ai_settings, screen, "Play")

    #Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #Make a ship,a group of bullets and a group of aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    #Make a group to store bullets in.
    #bullets=Group()

    #Make an alien
    #alien=Alien(ai_settings,screen)

    #Create the fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #set the background color.
    #bg_color=(230,230,230)

    #Start the main loop for the game.
    while True:
        #Watch for keyboard and mouse events.
        #for event in pygame.event.get():
        #   if event.type==pygame.QUIT:
        #      sys.exit()
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        #Redraw the screen during each pass through the loop.
        #screen.fill(ai_settings.bg_color)
        #ship.blitme()

        #make the most recently drawn screen visible.
        #pygame.display.flip()

        if stats.game_active:
            ship.update()
            #bullets.update()

            #Deleting old bullets
            #for bullet in bullets.copy():
            #   if bullet.rect.bottom <= 0:
            #      bullets.remove(bullet)
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
コード例 #19
0
ファイル: pong.py プロジェクト: progworkshop/pong
class Pong:
    def __init__(self, width=640, height=480, title="Prog Workshop - Pong!"):
        pygame.init()

        # Sets key repeat to a max of once every 5 ms
        #pygame.key.set_repeat(5, 5)
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption(title)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self._running = True
        
        self.player1 = Paddle(0,0,20,100,self)
        self.player2 = Paddle(width-20,0,20,100,self)
        
        self.ball = Ball(width/2,height/2,20,20,self)
        self.ball.setSpeed(random.random()*14-7, random.random()*14-7)

        self.balls = []

        self.score = Scoreboard(self, 36)

    def handle_event(self, event):
        if event.type == pygame.QUIT:
            self._running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            ball = Ball(self.screen.get_width()/2,self.screen.get_height()/2,20,20,self)
            ball.setSpeed(random.random()*14-7, random.random()*14-7)
            self.balls.append(ball)
            
    def update_game(self):
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_UP]:
            self.player2.moveUp()
        if keys_pressed[pygame.K_DOWN]:
            self.player2.moveDown()
        if keys_pressed[pygame.K_w]:
            self.player1.moveUp()
        if keys_pressed[pygame.K_s]:
            self.player1.moveDown()
        self.ball.update()
        for ball in self.balls:
            ball.update()
    
    def render(self):
        background = pygame.Surface(self.screen.get_size()).convert()
        background.fill((250, 250, 250))
        self.screen.blit(background, (0,0))

        self.player1.render()
        self.player2.render()
        
        self.ball.render()

        for ball in self.balls:
            ball.render()

        self.score.renderScore()
        
        pygame.display.flip()
    
    def start(self):
        while self._running:
            self.clock.tick(60) # Limit to 60 fps
            
            # Handle events
            for event in pygame.event.get():
                self.handle_event(event)

            # Handle game logic
            self.update_game()

            # Handle rendering
            self.render()
            
        pygame.quit()
コード例 #20
0
from turtle import Screen
from Paddle import Paddle
from ball import Ball
import time
from scoreboard import Scoreboard

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(0)

paddle_right = Paddle((350, 0))
paddle_left = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()


screen.listen()
screen.onkeypress(paddle_right.go_up, "Up")
screen.onkeypress(paddle_right.go_down, "Down")
screen.onkeypress(paddle_left.go_up, "w")
screen.onkeypress(paddle_left.go_down, "s")

game_is_on = True

while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()
コード例 #21
0
import time
from snake import Snake
from food import Food
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")

game_on = True
screen.tracer(0)

snake = Snake(move_speed=20)
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.update()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

while game_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food
    if snake.head.distance(food) < 15:
コード例 #22
0
import time
from snake import Snake
from food import Food
from scoreboard import Scoreboard

# screen setup
screen = t.Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Welcome to Snake Game")
screen.tracer(0)

# snake and Food
snake = Snake()
food = Food()
scoreboard = Scoreboard()

# arrow keys listener
screen.listen()

screen.onkey(fun=snake.turn_west, key="Left")
screen.onkey(fun=snake.turn_north, key="Up")
screen.onkey(fun=snake.turn_east, key="Right")
screen.onkey(fun=snake.turn_south, key="Down")

# moving the snake
game_is_on = True

# todo: make difficulty levels => user enters any number from 1 to 10, and according to this it will give a difficulty

# difficulty_level = screen.numinput(title="Difficulty Levels", prompt="Choose level of difficulties from 1 to 10: ")
コード例 #23
0
class AlienInvasion:
    """ Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""

        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien Invasion")

        # Create an instance to store game statictics
        #      and create a scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the Play Button
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""

        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

    def _create_fleet(self):
        """ Create the fleet of aliens."""
        # Create an alien and find the number of aliens in a row
        # Spacing between each alien is equal to one alien width
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        avilable_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = avilable_space_x // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        # Create an alien and place it in the row
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """ Respond appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """ Drop the entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _update_aliens(self):
        """ Check if the fleet is at an edge,
              then update the positions of all aliens in the fleet. """
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Look for aliens hitting the bottom of the screen.
        self._check_aliens_bottom()

    def _check_aliens_bottom(self):
        """ Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break

    def _update_screen(self):
        """ Update images on the screen, and flip to the new screen."""

        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()

        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        self.aliens.draw(self.screen)

        # Draw the score information
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()
        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _update_bullets(self):
        """ Update position of bullets and get rids of old bullets"""
        # Update bullet positions.
        self.bullets.update()

        # Get rid of bullets that have dissapeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_alien_collisions()

    def _ship_hit(self):
        """Respond to the ship being hit by an alien."""
        if self.stats.ships_left > 0:
            # Decrement ships_left and update scoreboard.
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_bullet_alien_collisions(self):
        """ Respond to bullet-alien collisions."""
        # Remove any bullet and aliens that have collided.
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

        if not self.aliens:
            # Destroy existing bullets and create new fleet.
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level
            self.stats.level += 1
            self.sb.prep_level()

    def _check_events(self):
        """Respond to keypresses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """ Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Reset the game settings
            self.settings.initialize_dynamic_settings()

            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Responds to keypresses."""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        """ Responds to key releases."""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """ Create a new bullet and add it to the bullets group."""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)
コード例 #24
0
ファイル: main.py プロジェクト: jil8885/Galtron
def runGame():
    # Initialize game and create a window
    pg.init()
    # create a new object using the settings class
    setting = Settings()
    # creaete a new object from pygame display
    screen = pg.display.set_mode((setting.screenWidth, setting.screenHeight))

    # intro
    intro.introimages()

    # set window caption using settings obj
    pg.display.set_caption(setting.windowCaption)

    bMenu = ButtonMenu(screen)
    bMenu.addButton("play", "PLAY")
    bMenu.addButton("menu", "MENU")
    bMenu.addButton("twoPlay", "2PVS")
    bMenu.addButton("settings", "SETTINGS")
    bMenu.addButton("invert", "INVERT")
    bMenu.addButton("about", "ABOUT")
    bMenu.addButton("quit", "QUIT")
    bMenu.addButton("grey", "GREY")
    bMenu.addButton("red", "RED")
    bMenu.addButton("blue", "BLUE")
    bMenu.addButton("retry", "RETRY")
    bMenu.addButton("hard", "HARD")
    bMenu.addButton("normal", "NORMAL")

    mainMenuButtons = ["play", "about", "settings", "quit"]  # delete "twoPlay"
    playMenuButtons = ["grey", "red", "blue", "menu", "quit"]
    levelMenuButtons = ["hard", "normal", "quit"]
    mainGameButtons = ["play", "menu", "quit"]
    aboutButtons = ["menu", "quit"]
    settingsMenuButtons = ["menu", "invert", "quit"]

    bgManager = BackgroundManager(screen)
    bgManager.setFillColor((0, 0, 0))
    bgManager.addBackground("universe_1", "gfx/backgrounds/stars_back.png", 0,
                            1)
    bgManager.addBackground("universe_1", "gfx/backgrounds/stars_front.png", 0,
                            1.5)
    bgManager.selectBackground("universe_1")

    # Create an instance to stor game stats
    stats = GameStats(setting)
    sb = Scoreboard(setting, screen, stats)

    # Make a ship
    ship = Ship(setting, screen)
    # Ships for two player
    ship1 = Ship(setting, screen)
    ship2 = Ship(setting, screen)

    #make a group of items to store
    items = Group()

    # make a group of bullets to store
    bullets = Group()
    charged_bullets = Group()
    eBullets = Group()
    setting.explosions = Explosions()

    # Make an alien
    aliens = Group()
    gf.createFleet(setting, stats, screen, ship, aliens)
    pg.display.set_icon(pg.transform.scale(ship.image, (32, 32)))

    bgImage = pg.image.load('gfx/title_c.png')
    bgImage = pg.transform.scale(bgImage,
                                 (setting.screenWidth, setting.screenHeight))
    bgImageRect = bgImage.get_rect()

    aboutImage = pg.image.load('gfx/About_modify2.png')
    aboutImage = pg.transform.scale(
        aboutImage, (setting.screenWidth, setting.screenHeight))
    aboutImageRect = aboutImage.get_rect()

    # plays bgm
    pg.mixer.music.load("sound_bgms/galtron.mp3")
    pg.mixer.music.set_volume(0.25)
    pg.mixer.music.play(-1)

    rungame = True

    # Set the two while loops to start mainMenu first
    while rungame:
        # Set to true to run main game loop
        bMenu.setMenuButtons(mainMenuButtons)
        while stats.mainMenu:
            mm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            mm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(levelMenuButtons)
        while stats.levelMenu:
            lm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            lm.drawMenu(setting, screen, sb, bMenu, bgImage, bgImageRect)

        bMenu.setMenuButtons(playMenuButtons)
        while stats.playMenu:
            pm.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets)
            pm.drawMenu(setting, screen, sb, bMenu)

        bMenu.setMenuButtons(mainGameButtons)

        while stats.mainGame:
            # Game functions
            gf.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                           bullets, eBullets,
                           charged_bullets)  # Check for events
            # Reset Game
            if gf.reset == 1:
                gf.reset = 0
                pg.register_quit(runGame())
            if stats.gameActive:
                gf.updateAliens(setting, stats, sb, screen, ship, aliens,
                                bullets, eBullets)  # Update aliens
                gf.updateBullets(setting, screen, stats, sb, ship, aliens,
                                 bullets, eBullets, charged_bullets,
                                 items)  # Update collisions
                gf.updateItems(setting, screen, stats, sb, ship, aliens,
                               bullets, eBullets, items)
                ship.update(bullets, aliens)  # update the ship
                # Update the screen
            gf.updateScreen(setting, screen, stats, sb, ship, aliens, bullets,
                            eBullets, charged_bullets, bMenu, bgManager, items)

        bMenu.setMenuButtons(aboutButtons)
        bMenu.setPos(None, 500)

        while stats.mainAbout:
            About.checkEvents(setting, screen, stats, sb, bMenu, ship, aliens,
                              bullets, eBullets)
            About.drawMenu(setting, screen, sb, bMenu, aboutImage,
                           aboutImageRect)

        while stats.twoPlayer:
            tp.checkEvents(setting, screen, stats, sb, bMenu, bullets, aliens,
                           eBullets, ship1, ship2)
            if stats.gameActive:
                ship1.update(bullets, aliens)
                ship2.update(bullets, aliens)
                tp.updateBullets(setting, screen, stats, sb, ship1, ship2,
                                 aliens, bullets, eBullets, items)
            tp.updateScreen(setting, screen, stats, sb, ship1, ship2, aliens,
                            bullets, eBullets, bMenu, items)

        bMenu.setMenuButtons(settingsMenuButtons)

        while stats.settingsMenu:
            sm.checkEvents1(setting, screen, stats, sb, bMenu, ship, aliens,
                            bullets, eBullets)
            sm.drawMenu(setting, screen, sb, bMenu)

        while stats.mainGame:
            if rungame == True:
                print("test")
コード例 #25
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snakes on a Flat, Black Plane")
screen.tracer(0)

scoreboard = Scoreboard()

eating = True

snake = Snake()
food = Food()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.right, "Right")
screen.onkey(snake.left, "Left")

while eating:
    screen.update()
    time.sleep(0.1)
    snake.move()
    # Detect food collision
    if snake.head.distance(food) < 15:
コード例 #26
0
class AlienInvasion:
    def __init__(self):
        """Initialize game & resources"""
        pygame.init()  # intializes background settings
        self.settings = Settings()

        # the self.screen obj creates a `surface` that represents game screen where elements can be drawn
        ###  run in 1200 x 800 mode
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))

        ### run in fullscreen mode
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien_Invasion")

        # Create instance of game statistics & scoreboard
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        # the self.ship instance is assigned to give Ship access to all game resourses via self parameter
        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group(
        )  # similar to a list with extra features

        # create instance of alien
        self.aliens = pygame.sprite.Group()
        self._create_fleet()

        # Create a Play button
        self.play_button = Button(self, "Play !")

# # create instance of laser_blast
# self.laser = pygame.sprite.Group()

    def run_game(self):
        """Start main loop in game"""
        while True:
            self._check_events()  # check event listener

            if self.stats.game_active:
                self.ship.update()  # update position
                # self.bullets.update()  # will update each sprite in the group
                self._update_bullets()
                self._update_aliens()

#            self.laser.update()
            self._update_screen()  # refresh screen

    def _check_events(self):
        # create event listener to watch keyboard or mouse events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """ Start a new game when player clicks Play """
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset game settings
            self.settings.initialize_dynamic_settings()

            # Reset game stats
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            # Remove any remaining aliends and bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor when inside of game window
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """ Set directions for current movements """
        # print('key pressed was ', (event))
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True  # move ship to the right
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True  # move ship to the left
        elif event.key == pygame.K_q:  # quit is Q is pressed
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
# elif event.key == pygame.K_l:
#     self._fire_laser()

    def _check_keyup_events(self, event):
        """ respond to changes in direction """
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False  # moving right key released, stop moving
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False  # moving left key released, stop moving

    def _fire_bullet(self):
        """ Create a new bullet and add it to the bullets group """
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _fire_laser(self):
        print("LASER FIRED")
# print(self.settings.laser_fire_allowed)
# if self.settings.laser_fire_allowed:
#     #laser_blast = LaserBlast(self)
#     laser_blast = Bullet(self)

#     laser_blast.color = self.settings.laser_color
#     self.bullets.add(laser_blast)

    def _update_bullets(self):
        """  Update position of bullets to get rid of bullets that have exited screen """
        # Remove bullets that have reached top of screen
        self.bullets.update()  ## MOVED HERE !!!!!!

        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
            # print(len(self.bullets))

        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """ Handles hits to fleet """
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)

        if collisions:
            for aliens in collisions.values():
                # print(f' Collision values() is {aliens}')
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

            # print out collisions dictionary
            for key, value in collisions.items():
                print(f' key: {key} value: {value}')

        if not self.aliens:
            # Destroy bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

            # Increase level
            self.stats.level += 1
            self.sb.prep_level()

    def _update_aliens(self):
        """ Verify if fleet at edges. if so, change position of fleet """
        self._check_fleet_edges()

        self.aliens.update()
        if pygame.sprite.spritecollideany(self.ship, self.aliens) != None:
            print("SHIP Hit !")
            self._ship_hit()

        # Verify if aliens reach the bottom of the screen
        self._check_aliens_bottom()

    def _ship_hit(self):
        """ Respond to ship being hit by alien """
        if self.stats.ships_left > 0:
            # Decrement ships_left
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            # Remove remianing aliens & bullets
            self.aliens.empty()
            self.bullets.empty()

            # Create new fleet and ship at start location
            self._create_fleet()
            self.ship.center_ship()

            # pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _create_fleet(self):
        """ Create a fleet of aliens """
        alien = Alien(self)  # used for calculations, NOT part of fleet
        # <Alien sprite(in 0 groups)>

        # Get dimensions for ship & alien
        ship_height = self.ship.rect.height
        alien_width, alien_height = alien.rect.size  # (60, 58)

        # find available space for aliens to fit on screen
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        available_space_x = self.settings.screen_width - (2 * alien_width)
        # available_space_y = (800) - (3 * 58) - 48    = 578
        # available_space_x = 1200 - (2 * 60)    = 1080

        # determine total number of aliens per row & total number of rows
        number_aliens_x = available_space_x // (2 * alien_width)
        number_rows = available_space_y // (2 * alien_height)
        # number_aliens_x = 1080 // (2 * 60)   = 9
        # number_rows = 578 // (2 * 58)  = 4

        # Create rows of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_aliens_x):
                # Fill row with aliens
                self._create_alien(alien_number, row_number)

        # rect = <rect(x, y, width, height)>       <rect(180, 58, 60, 58)>
    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)
        alien_width, height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        # alien.x = 60 + (2 * 60 * 0..9)   alien.x = 60.0, 180.0, 300.0, 420.0, ...
        alien.rect.x = alien.x
        # Each alien row starts below at twice the height of an alien ship
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        # alien.rect.y =   58 + (2 * 58 * 0..4)                     58, 174, 290
        self.aliens.add(alien)

    def _check_fleet_edges(self):
        """ Determine if fleet hits edge of screen and respond  """
        for alien in self.aliens.sprites():
            #  if self.rect.right >= screen_rect.right or self.rect.left <= 0:
            if alien.check_edges():
                print("alien.rect BEFORE",
                      alien.rect)  # rect = <rect(x, y, width, height)>
                print("direction BEFORE ", self.settings.fleet_direction)
                self._change_fleet_direction()
                print("direction AFTER ", self.settings.fleet_direction)
                print("Change in y is ", alien.rect.y)
                break

    def _change_fleet_direction(self):
        """ Drop the entire fleet and change direction """
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _check_aliens_bottom(self):
        """ Verify if aliends reach bottom od screen """
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _update_screen(self):
        """ Update images """
        # Redraw screen during each pass through the loop
        # a surface obj is created via self.screen
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        # call draw method to render alien
        self.aliens.draw(self.screen)

        # Draw scoreboard info
        self.sb.show_score()

        # Draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()


# for blast in self.laser.sprites():
#     blast.draw_laser()

# make most recent screen drawn visible
# updates entire display
        pygame.display.flip()
コード例 #27
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
car_manager = CarManager()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(player.move_up, "Up")
screen.onkey(player.move_down, "Down")

game_is_on = True
while game_is_on:
    car_manager.move_cars()
    if player.border_check():
        player.staring_position()
        car_manager.speed_up()
        scoreboard.increase_score()

    for car in car_manager.cars:
        if car.distance(player) < 20:
            scoreboard.game_over()
            game_is_on = False

    time.sleep(0.1)
コード例 #28
0
ファイル: main_screen.py プロジェクト: echoshihab/PyGameSims
import time
from turtle import Screen
from player import Player
import random
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
car_manager = CarManager()
scoreboard = Scoreboard(winning_score=5, player_lives=3)

screen.onkey(player.up, "Up")

screen.listen()

game_is_on = True

starting_cars_list = []
cars_till_finish_list = []

starting_speed = 5

while game_is_on:

    if len(starting_cars_list) < 1:
        car = car_manager.initiate_car()
        starting_cars_list.append(car)
コード例 #29
0
ファイル: main.py プロジェクト: risand/pong
from turtle import Screen, Turtle
from scoreboard import Scoreboard
from paddle import Paddle
from ball import Ball
import time

line = Turtle()
screen = Screen()
scoreboard = Scoreboard()
ball = Ball()

screen.setup(width=1200, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)

right_paddle = Paddle((560, 0))
left_paddle = Paddle((-560, 0))

screen.listen()
screen.onkey(right_paddle.go_up, "Up")
screen.onkey(right_paddle.go_down, "Down")
screen.onkey(left_paddle.go_up, "w")
screen.onkey(left_paddle.go_down, "s")

line.hideturtle()
line.pensize(5)
line.pencolor("white")
line.penup()
line.goto(0, 285)
line.setheading(270)
コード例 #30
0
class AlienInvasion:
    def __init__(self):
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("NEVER LET THEM LIVE")
        self.ship = Ships(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.stats = GameStats(self)
        self._create_fleet()
        self.play_button = Button(self, "Play")
        self.sb = Scoreboard(self)

    def run_game(self):
        while True:
            self._check_events()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        ship_height = self.ship.rect.height

        available_space = self.settings.screen_width - 2 * alien_width
        number_of_aliens = available_space // (2 * alien_width)

        available_space_y = self.settings.screen_height - (
            3 * alien_height) - (2 * ship_height)
        number_of_rows = available_space_y // (2 * alien_height)

        for number_row in range(number_of_rows):
            for number_alien in range(number_of_aliens):
                self._create_aliens(number_row, number_alien)

    def _create_aliens(self, number_row, number_alien):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + (2 * alien_width * number_alien)
        alien.rect.x = alien.x

        alien.y = alien_height + (2 * alien_height * number_row)
        alien.rect.y = alien.y
        self.aliens.add(alien)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullets()

    def _fire_bullets(self):
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _check_play_button(self, mouse_pos):
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self.settings.initialize_dynamic_settings()
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_level()
            self.sb.prep_ships()

            self.bullets.empty()
            self.aliens.empty()

            self._create_fleet()
            self.ship.centre_ship()

            pygame.mouse.set_visible(False)

    def _update_bullets(self):
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        self._check_bullet_alien_collision()

    def _check_bullet_alien_collision(self):
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True)
        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
                self.sb.prep_score()
                self.sb.check_high_score()

        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.stats.level += 1
            self.sb.prep_level()
            self.settings.increase_speed()

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_directions()
                break

    def _change_fleet_directions(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        if self.stats.ships_left > 1:
            self.stats.ships_left -= 1
            self.sb.prep_ships()

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.ship.centre_ship()

            sleep(2)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _update_screen(self):
        self.screen.fill(self.settings.bgcolor)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        self.sb.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()
        pygame.display.flip()
コード例 #31
0
ファイル: main.py プロジェクト: Ciwonie/Python_Days_of_Code
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

player = Player()
car_manager = CarManager()
scoreboard = Scoreboard()

# instantiate screen event listeners
screen.listen()
screen.onkey(player.go_up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()

    car_manager.create_car()
    car_manager.move_cars()

    # detect collision with car
    for car in car_manager.all_cars:
        if car.distance(player) < 20:
            game_is_on = False
            scoreboard.game_over()
コード例 #32
0
ファイル: yahtzee.py プロジェクト: Maxeonyx/yahtzee
def main():
    """
    the main function. The game logic begins here.
    """

    players = []
    num_players = get_int("Input the number of players or 0 to load a game: ")

    for i in range(num_players):
        player_name = get_string("Input player {}'s name: ".format(i+1), 10)
        players.append(Player(player_name))

    board = Scoreboard(players)
    if num_players == 0:
        succeeded = board.load_game()
        if not succeeded:
            print("There is no savegame. The game will now quit")
            exit()

    last_roll = []
    num_rolls = 0

    board.begin_turn()

    while True:
        params = get_command(': ', last_roll, num_rolls, board)

        command = params[0]
        args = params[1:]

        if command == 'keep':
            last_roll = roll_dice(args)
            print_dice(last_roll)
            num_rolls += 1

        elif command == 'roll':
            last_roll = roll_dice([])
            print_dice(last_roll)
            num_rolls += 1

        elif command in templates.COMBO_COMMANDS:
            score = get_combo_score(command, last_roll)
            board.set(command, score)
            num_rolls = 0
            last_roll = []
            board.next_turn()

        elif command == 'block':
            combo = args[0]
            board.set(combo, "Blocked")
            num_rolls = 0
            last_roll = []
            board.next_turn()

        elif command == 'print':
            board.display()

        elif command == 'save':
            board.save_game()
            print("Saved the game.")

        elif command == 'load':
            board.load_game()
            print("Loaded a game save.")

        elif command == 'help':
            parameter = args[0]
            print(templates.HELP_PARAMETERS[parameter])

        elif command == 'exit':
            y_or_n = input("Save game? (y/n): ")

            while not y_or_n in 'yn':
                y_or_n = input("Save game? (y/n): ")

            if y_or_n == 'y':
                board.save_game()

            exit()

        elif command == 'finish':

            for player in board.players:
                player.sum_sections()

            board.display()

            exit()
コード例 #33
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.title("Turtle Crosser")
player = Player()
car_manager = CarManager()
score_board = Scoreboard()
screen.listen()
screen.onkey(player.go_up, "Up")
game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()
    for car in car_manager.all_cars:
        if car.distance(player) < 20:
            game_is_on = False
            score_board.game_over()
    # Detect successfull crossing
    if player.is_at_finish_line():
        player.go_to_start()
        car_manager.level_up()
        score_board.level_up()
コード例 #34
0
ファイル: rps.py プロジェクト: gfried1/python-lessons
#rps
#ask person choose: rock, paper or scissors
#computer randomly picks something 
#print what computer chooses and what person chooses
#then say winner
#in terminals: cd is choose directory (folder) ls list stuff

import random
from time import sleep
from scoreboard import Scoreboard
#this is making a new scoreboard
my_score = Scoreboard()
	
computer_score = Scoreboard()

print "lets play rock, paper, scissors"

sleep(0.2)


for counter in range(5): 

	my_list = ["rock", "paper", "scissors"]

	good_choice = False
	while not good_choice:
		#ask player for their choice
		print "choose rock, paper or scissors:"
		player = raw_input()
		if player in my_list:
			good_choice = True
コード例 #35
0
class Viscontrol( Window ):
    score = 0
    gameboard = 0
    plantInfo = 0
    minimap = 0
    
    def __init__(self, x, y, game):
        Window.__init__( self, x, y, 200, 2) 
        
        Visettings.Speed = -1
        
        if Visettings.AutoEnd :
            Visettings.CurrentMode = VISMODE.PLAY
        else:
            Visettings.CurrentMode = VISMODE.PAUSE
        
        Visettings.MaxX = game.states[0].boardX-1
        Visettings.MaxY = game.states[0].boardY-1
        
        Visettings.Player1Name = game.getName(0)
        Visettings.Player2Name = game.getName(0)
        
        Visettings.Game = game
        
        self.Window.erase()
        self.Window.refresh()
        
        self.moveWindow( x, Visettings.MaxY*2+4 )
        
        self.score = Scoreboard( x+Visettings.MaxX*2+5, y, 31, Visettings.MaxY*2+4 )
        self.gameboard = Gameboard( x, y, Visettings.MaxX*2+4, Visettings.MaxY*2+4 )
        self.plantInfo = Plantinfo( x+Visettings.MaxX*2+5+31, y, 32, Visettings.MaxY+1 )
        self.minimap = Minimap( \
        x+Visettings.MaxX*2+5+31+30/2 - Visettings.MaxX/2, \
        Visettings.MaxY+1, \
        Visettings.MaxX+3, \
        Visettings.MaxY+3 )
        
        Visettings.CurX = 0
        Visettings.CurY = 0
        
        self.Window.erase()
        
    def updateMode(self, mode):
        Visettings.CurrentMode = mode
        if mode == VISMODE.PLAY or mode == VISMODE.REWIND:
            Visettings.Speed = Visettings.PlaySpeed
        elif mode == VISMODE.PAUSE:
            Visettings.Speed = -1
            
    
    def run( self ):
        if Visettings.AutoEnd and Visettings.Done:
            return 0
            
        if Visettings.FirstRun:
            self.update()
            Visettings.FirstRun = 0
            
        
        Visettings.Screen.timeout( Visettings.Speed )
        c = Visettings.Screen.getch()
       
        try:
            ch = curses.keyname( c )
        except:
            ch = c
        
        
        if ch == 'q':
            return 0
        elif ch == ' ' or ch == 'p':
            if Visettings.CurrentMode == VISMODE.PAUSE:
                self.updateMode( VISMODE.PLAY )
            else:
                self.updateMode( VISMODE.PAUSE )
        elif ch == 'r':
            self.updateMode( VISMODE.REWIND )
        elif ch == '.':
            self.updateMode( VISMODE.PAUSE )
            self.nextFrame()
        elif ch == ',':
            self.updateMode( VISMODE.PAUSE )
            self.prevFrame()
        elif ch == '=':
            Visettings.PlaySpeed -= 5
            if Visettings.PlaySpeed < 0:
                Visettings.PlaySpeed = 1
            self.updateMode( Visettings.CurrentMode )
        elif ch == '-':
            Visettings.PlaySpeed += 5
            self.updateMode( Visettings.CurrentMode )
        elif ch == 's':
            Visettings.FrameNumber = 0
        elif ch == 'e':
            Visettings.FrameNumber = len(Visettings.Game.states)-1
        elif c == curses.KEY_LEFT:
            Visettings.CurX -= 1
        elif c == curses.KEY_RIGHT:
            Visettings.CurX += 1
        elif c == curses.KEY_UP:
            Visettings.CurY -= 1
        elif c == curses.KEY_DOWN:
            Visettings.CurY += 1
        elif c == curses.KEY_MOUSE:
            k = 0
            
        if Visettings.CurrentMode == VISMODE.PLAY:
            self.nextFrame()
        elif Visettings.CurrentMode == VISMODE.REWIND:
            self.prevFrame()
            
        self.update()
        
        return 1
            
    def nextFrame( self ):
        Visettings.FrameNumber += 1
        if Visettings.FrameNumber >= len(Visettings.Game.states):
            Visettings.FrameNumber = len(Visettings.Game.states)-1
        
        
    def prevFrame( self ):
        Visettings.FrameNumber -= 1
        if Visettings.FrameNumber < 0:
            Visettings.FrameNumber = 0
        
    def update( self ):
        Window.update(self)
        self.Window.attrset( curses.color_pair( Legend.DEFAULT_COLOR ) )
        
        Visettings.Screen.refresh()
        
        # TODO: A bunch of attribute stuff is missing.
        
        Visettings.State = Visettings.Game.states[Visettings.FrameNumber];
        Visettings.Player1Score = Visettings.Game.states[Visettings.FrameNumber].player0Score
        Visettings.Player2Score = Visettings.Game.states[Visettings.FrameNumber].player1Score
        Visettings.Player1Light = Visettings.Game.states[Visettings.FrameNumber].player0Light
        Visettings.Player2Light = Visettings.Game.states[Visettings.FrameNumber].player1Light
        
        self.score.update()
        self.gameboard.newState()
        self.minimap.newState()
        self.plantInfo.update()
        
        offset = 50
        
        percent = float(Visettings.FrameNumber+1)/len(Visettings.Game.states)
        
        if percent > 1:
            percent = 1
        
        blocks = int((Visettings.MaxX*2+offset-10)*percent)
        
        for i in range(1, blocks+1):
            self.Window.addch( 0, i, curses.ACS_HLINE )
        for i in range( blocks+1, Visettings.MaxX*2+offset-9 ):
            self.Window.addch( 0, i, ' ' )
            
        self.Window.addch( 0, 0, curses.ACS_LLCORNER )
        self.Window.addch( 0, Visettings.MaxX*2+offset-9, curses.ACS_LRCORNER )
        
        if Visettings.CurrentMode == VISMODE.PAUSE:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "PAUSED      " )
        elif Visettings.CurrentMode == VISMODE.PLAY:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "PLAYING     " )
        elif Visettings.CurrentMode == VISMODE.REWIND:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "REWINDING   " )
            
        blue = 0
        red = 0
        width = 93
        
        red = Visettings.Player1Plants
        blue = Visettings.Player2Plants
        
        size = Visettings.MaxX * Visettings.MaxY

        rPercent = float(red)/size
        bPercent = float(blue)/size
        gPercent = float(1 - rPercent - bPercent)

        line = 2

        self.Window.attrset( curses.color_pair( Legend.PLAYER_1_PIECE_COLOR ) )
        self.Window.attron( curses.A_BOLD )
        self.Window.addch( 1, 1, curses.ACS_LLCORNER )
        self.Window.attrset( curses.color_pair( Legend.PLAYER_2_PIECE_COLOR ) )
        self.Window.attron( curses.A_BOLD )
        self.Window.addch( 1, 95, curses.ACS_LRCORNER )

        for i in range(0, width):
            if i+1 < rPercent*width:
                self.Window.attrset( curses.color_pair( Legend.PLAYER_1_PIECE_COLOR ) )
            elif i < (rPercent+gPercent)*width:
                self.Window.attrset( curses.color_pair( Legend.BACKGROUND_COLOR ) )
            else:
                self.Window.attrset( curses.color_pair( Legend.PLAYER_2_PIECE_COLOR ) )
            self.Window.attron( curses.A_BOLD )

            if i == width/2:
                self.Window.addch( 1, 2+i, '|' )
            else:
                self.Window.addch( 1, 2+i, curses.ACS_HLINE )

        self.Window.attroff( curses.A_BOLD )


        
        self.Window.refresh()
        Visettings.Screen.refresh()
コード例 #36
0
ファイル: main.py プロジェクト: Luganda1/turtle-crossing-game
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
cars = CarManager()
score = Scoreboard()
screen.listen()

screen.onkey(player.move_up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    # Creating a random car every after .5 second
    cars.create_car()
    cars.move_cars()

    # Detecting collision with the car
    for car in cars.all_cars:
        if car.distance(player) < 20:
            game_is_on = False
            score.game_over()

    # if player.ycor() >= 290:
コード例 #37
0
ファイル: main.py プロジェクト: jheidel/scrabble-opencv
if len(sys.argv) == 2:
    filename = sys.argv[1]
    (scoreboard, game_board) = pickle.load(open(filename, "rb"))
    print "Game recovered from file"
    voice.say("Resuming game!")
else:
    # Find out our players
    player_count = int(ask("How many players?"))
    player_list = []
    for i in range(1, player_count + 1):
        x = ask("What is Player %d's name?" % i)
        player_list.append(x.strip())

    game_board = board.Board()
    scoreboard = Scoreboard(player_list)

    voice.say("Starting game!")


# Create scorebox
sbox = scorebox.ScoreBox(scoreboard.player_list)
sbox.start()
sbox.set_letters(scoreboard.get_tiles_in_bag())
sbox.set_rnd(scoreboard.turn_round)
sbox.update_scores(scoreboard.points)

# Game clock
clock = gameclock.GameClock(sbox)
clock.start()
コード例 #38
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

tim = Player()
scoreb = Scoreboard()
screen.listen()
cars = CarManager()

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.onkeypress(fun=tim.move, key="Up")
    cars.newCar()

    if tim.ycor() >= 250:
        tim.reset()
        scoreb.increaseLevel()
        cars.increaseSpeed()

    cars.moveCars()
    game_is_on = cars.isSafe(tim)

    screen.update()