Example #1
0
def main():
    pygame.init() # Инициация PyGame, обязательная строчка 
    timer = pygame.time.Clock()
    screen = pygame.display.set_mode(DISPLAY) # Создаем окошко
    pygame.display.set_caption("Tetris") # Пишем в шапку
    bg = Surface(DISPLAY) # Создание видимой поверхности
                                         # будем использовать как фон
    bg.fill(Color(BACKGROUND_COLOR))     # Заливаем поверхность сплошным цветом

    lev = Level(LW, LH)
    fig = Figure()
    dt = 0

    while 1: # Основной цикл программы
        dt =  dt + timer.tick(60)
        for e in pygame.event.get(): # Обрабатываем события
            if e.type == QUIT:
                raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_LEFT:
                fig.move(-1, 0)
            if e.type == KEYDOWN and e.key == K_RIGHT:
                fig.move(1, 0)
            if e.type == KEYDOWN and e.key == K_UP:
                fig.rotate()
        if dt > 1000:
            fig.move(0, 1)
            dt = 0
        screen.blit(bg, (0,0))      # Каждую итерацию необходимо всё перерисовывать 
        if lev.update(fig):
            del fig
            fig = Figure()
        lev.draw(screen)
        fig.draw(screen)
        pygame.display.update()     # обновление и вывод всех изменений на экран
def interact(game):
    # interaction entre l'utilisateur et le menu
    menu = Game.getMenu(game)
    win = Game.getWin(game)
    # deplacement du curseur
    menu['selectedItem'] = -1
    key = win.getch()
    if key == ord('z'):
        if menu['cursor'] != 0:
            menu['cursor'] -= 1
    if key == ord('s'):
        if menu['cursor'] != len(menu['items']) - 1:
            menu['cursor'] += 1
    if key == ord('e'):
        menu['selectedItem'] = menu['cursor']
    # action a effectuer en fonction de l'item selectionne
    if menu['selectedItem'] == 0:
        game = Game.setName(Game.askName(game), game)
    if menu['selectedItem'] == 1:
        game = Game.setDifficulty(Game.askDifficulty(game), game)
    if menu['selectedItem'] == 2:
        newLevel = Level.create(Level.askLevelNumber(game), 'levels.txt')
        logging.info("nouveau niveau : " + str(newLevel))
        game = Game.setLevel(newLevel, game)
    if menu['selectedItem'] == 3:
        HighScores.show(HighScores.get(), win)
    if menu['selectedItem'] == 4:
        Game.setState('game', game)
    if menu['selectedItem'] == 5:
        Game.setState('quitProgram', game)
    return
Example #3
0
    def initWidget(self,master, get_spell_menu =None, negative_target=False) :
        self.widget=tkinter.PanedWindow(master,orient=tkinter.HORIZONTAL)
        self.content=tkinter.StringVar()
        self.content.set(self.__class__.__name__)
        self.content.trace("w", self.isChanged)
        if not(get_spell_menu):
            name_wid=getSpellMenu(master,self.content)
        else:
            name_wid=get_spell_menu(master,self.content)
        #name_wid.pack()
        self.widget.add(name_wid)
        
        self.add_level=tkinter.StringVar()
        self.add_level.set(self.level.__class__.__name__)
        self.level_wid=Level.getLevelMenu(self.widget, self.add_level)
        self.add_level.trace('w', self.modifyLevelType)
        self.widget.add(self.level_wid)
        
        self.value=tkinter.StringVar()
        self.value.set(str(self.level.level))
        value_wid=tkinter.Spinbox(self.widget, from_=0, to=100,textvariable=self.value,
            command=self.modifyLevel )
        value_wid.icursor(5)
        self.widget.add(value_wid)
        
        self.add_level2=tkinter.StringVar()
        self.add_level2.set(self.level.__class__.__name__)
        self.level_wid2=Level.getLevelMenu(self.widget, self.add_level2)
        self.add_level2.trace('w', self.modifyLevel2Type)
        self.widget.add(self.level_wid2)
        
        self.value2=tkinter.StringVar()
        self.value2.set(str(self.level2.level))
        value_wid=tkinter.Spinbox(self.widget, from_=0, to=100,textvariable=self.value2,
            command=self.modifyLevel2 )
        value_wid.icursor(5)
        self.widget.add(value_wid)      
        if self.__class__.has_target:
            #Target selector
            if not(hasattr(self,"target")) and not(negative_target):
                self.target = Target.UneCibleAuChoix()
            elif not(hasattr(self,"target")) or negative_target and self.target.__class__ == Target.UneCibleAuChoix:
                self.target = [Target.MasseAllie,Target.MasseEnnemi][self.positive]()

            self.add_target = tkinter.StringVar(self.widget)
            self.add_target.set(self.target.__class__.__name__) # default value
            if negative_target:
                self.addTarget_wid = getNegativeSpellTargetMenu(self.widget, self.add_target, self.negative)                
            else:
                self.addTarget_wid = getTargetMenu(self.widget, self.add_target)
            self.add_target.trace('w', self.modifyTarget)
            self.widget.add(self.addTarget_wid)
        #-------------
        return self.widget
def show(game):
    win = getWin(game)
    food = getFood(game)
    level = getLevel(game)
    snake = getSnake(game)
    score = getScore(game)
    win.erase()
    Level.show(level, win)
    Snake.show(snake, win)
    showFood(food, win)
    showScore(score, win)
    return
Example #5
0
    def initWidget(self,master) :
        self.monster.parent=self
        self.widget=tkinter.PanedWindow(master,orient=tkinter.HORIZONTAL)
        self.content=tkinter.StringVar()
        self.content.set(self.__class__.__name__)
        self.content.trace("w", self.isChanged)
        name_wid=getSpellMenu(self.widget,self.content)
        #name_wid.pack()
        self.widget.add(name_wid)

        self.add_level=tkinter.StringVar()
        self.add_level.set(self.level.__class__.__name__)
        self.level_wid=Level.getLevelMenu(self.widget, self.add_level)
        self.add_level.trace('w', self.modifyLevelType)
        self.widget.add(self.level_wid)
        
        self.value=tkinter.StringVar()
        self.value.set(str(self.level.level))
        value_wid=tkinter.Spinbox(self.widget, from_=1, to=1000,textvariable=self.value,
            command=self.modifyLevel )
        value_wid.icursor(5)
        self.widget.add(value_wid)

        spell_wid=self.monster.init_as_card(self.widget)
        self.monster.card=self.card

        self.widget.add(spell_wid)
        return self.widget
def Load(iWidth,iHeight):
	#//\==== Load From Application
	print "Loading main"
	#//\==== ReLoad Modules (to make sure they are current when reloading)
	reload(KEYDEFS)
	reload(Level)
	reload(AStar)
	reload(Dijkstras)
	#//\==== Set BG colour and Grid Information
	LMF.FrameworkBGColour(0.1,0.6,0.09,1.)
	global GridDimens
	GridDimens = [40,24,64]
	#//\==== Dijkstras
	global DijkstrasPathing
	DijkstrasPathing = Dijkstras.cDijkstras()
	global AStarPathing
	AStarPathing = AStar.cAStar()
	#//\==== Setup ScreenSize
	global ScreenSize
	ScreenSize[0] = iWidth
	ScreenSize[1] = iHeight
	global Boids
	Boids = []
	Boids.append(boid.cBoid(CameraPos[0]+iWidth *0.5,CameraPos[1]+iHeight *0.5))
	#//\==== Setup the Tile able Level
	global LevelGrid
	LevelGrid = Level.cLevelGrid({'width':GridDimens[0], 'height':GridDimens[1] , 'size':GridDimens[2] })
	#//\==== center the view on the middle of the Grid and update the AIE camera
	CameraPos[0] = -(iWidth *0.5) + ((GridDimens[0]*GridDimens[2])*0.5 ) - (GridDimens[2]*0.5)
	CameraPos[1] =  (iHeight*0.5) + ((GridDimens[1]*GridDimens[2])*0.5 ) - (GridDimens[2]*0.5)
	LMF.CameraMove(-CameraPos[0],-CameraPos[1])
	print "Loaded main"
Example #7
0
	def __init__(self, surface):
		"Initialize variables, load images, set flags, and fonts"
		self.surface = surface
		self.bg = transform.scale(image.load("res/main_bg.jpg").convert(), (surface.get_width(), surface.get_height()))
		self.carImage = image.load("res/front_car.png")
		self.arrow_left = image.load("res/arrow_left.png")
		self.carImageSized = transform.scale(self.carImage, (150, 100))
		self.carX, self.carY = 437,290
		self.width = self.carImageSized.get_width()
		self.height = self.carImageSized.get_height()
		self.logo = image.load("res/logo_perspective.png")
		self.running = True
		self.rightMenu = image.load("res/menu_right.png")
		self.rightMenuX, self.rightMenuY = 1024, 768
		self.menuFont = font.Font("res/fonts/pricedown.ttf", 35)
		#menu options with color, rects, text, and action on click
		self.optionColors = [(255,255,255),(255,255,255),(255,255,255),(255,255,255),(255,255,255)]
		self.optionRects = [Rect(825,455,self.menuFont.size("Start Game")[0]+10,self.menuFont.size("Start Game")[1]),Rect(825,505,self.menuFont.size("Store")[0]+10,self.menuFont.size("Store")[1]),Rect(825,555,self.menuFont.size("Options")[0]+10,self.menuFont.size("Options")[1]),Rect(825,605,self.menuFont.size("Help")[0]+10,self.menuFont.size("Help")[1]),Rect(825,655,self.menuFont.size("About")[0]+10,self.menuFont.size("About")[1])]
		self.options = ["Start Game", "Store", "Help", "About"]
		self.optionResults = [self.levelRunning,self.storeRunning,self.setHelp,self.setAbout]
		self.store = Store(surface)
		self.level = Level(surface)
		self.about = Popup(surface, "About", ["Developed By Rikin Katyal", "ICS3U Final Project 2015", "Made Using Python and Pygame"])
		self.help = Popup(surface, "Help", ["Use arrow keys or WASD to move.", "Press Space for emergency break.", "Earn coins to spend in the store.", "Drive through obstacles and park", "in marked parking spot."])
		self.help.images([image.load("res/arrows.png"), image.load("res/wasd.png"), image.load("res/coin_medium.png")],[(310,456),(470,450),(660,475)])
		self.settings = Popup(surface, "Settings", ["Sound Effects (SFX)", "Music"])
		self.aboutRunning = False
		self.helpRunning = False
		self.settingsRunning = False
Example #8
0
 def initWidget(self,master) :
     self.widget=PanedWindow(master,orient=HORIZONTAL)
     self.content=StringVar()
     self.content.set(self.__class__.__name__)
     self.content.trace("w", self.isChanged)
     
     name_wid=getCostAlteratorMenu(master,self.content)
     
     #name_wid.pack()
     self.widget.add(name_wid)
     
     self.add_level=StringVar()
     self.add_level.set(self.level.__class__.__name__)
     self.level_wid=Level.getLevelMenu(self.widget, self.add_level)
     self.add_level.trace('w', self.modifyLevelType)
     self.widget.add(self.level_wid)
     
     self.value=StringVar()
     self.value.set(str(self.level.level))
     value_wid=Spinbox(self.widget, from_=1, to=1000,textvariable=self.value,
         command=self.modifyLevel )
     value_wid.icursor(5)
     self.widget.add(value_wid)
     
     return self.widget
def show(game):
    # affiche le menu
    level = Game.getLevel(game)
    menu = Game.getMenu(game)
    win = Game.getWin(game)
    win.erase()
    Level.show(level, win)
    for i in range(len(menu['items'])):
        if i == menu['cursor']:
            win.addstr(10 + i, 20, "->" + str(menu['items'][i]), curses.color_pair(1))
        else:
            win.addstr(10 + i, 22, str(menu['items'][i]), curses.color_pair(2))
    win.addstr(2, 2, 'Name : ' + str(Game.getName(game)))
    win.addstr(3, 2, 'Difficulty : ' + str(Game.getDifficulty(game)))
    win.addstr(4, 2, 'Level : ' +
               str(Level.getLevelNumber(Game.getLevel(game))))
    return
def setNewFood(game):
    level = getLevel(game)
    win = getWin(game)
    logging.info('new food : ' + str(game['food']))
    newFoodX = random.randint(1, Level.getWidth(level))
    newFoodY = random.randint(1, Level.getHeight(level))
    logging.info('char : ' + str(win.inch(newFoodY, newFoodX)))
    pos = win.inch(newFoodY, newFoodX)
    while pos != 32:
        logging.warning('food not allowed in tha place')
        newFoodX = random.randint(1, Level.getWidth(level))
        newFoodY = random.randint(1, Level.getHeight(level))
        logging.info('char : ' + str(win.inch(newFoodY, newFoodX)))
        pos = win.inch(newFoodY, newFoodX)
    game['food'] = [newFoodX, newFoodY]
    logging.info('new food coords : ' + str([newFoodX, newFoodY]))
    return game
Example #11
0
    def move(self, direction):
        moved = Level.move(self, direction)
        if moved and self.weapon:
            self.weapon.move(direction)
        if moved:
            State.use_turn()

        return moved
def init():
    # on initialise la fenetre curses
    curses.initscr()
    win = curses.newwin(30, 80, 0, 0)
    curses.noecho()
    curses.curs_set(0)
    win.nodelay(1)

    logging.basicConfig(filename='snake.log', level=logging.INFO)
    # creation du niveau
    level = Level.create(1, 'levels.txt')
    # creation du snake
    snake = Snake.create(35, 15, 1, 2)

    # creation du food
    food = None

    # creation du menu
    menu = Menu.create(
        'Change name',
        'Change difficulty',
        'Select level',
        'Show HighScores',
        'Play',
        'Quit game'
    )

    # definition de l'etat du programme
    state = 'menu'

    # definition du nom du joueur
    name = 'player1'

    # definition de la difficulte
    difficulty = 2

    score = -1

    HighScoreTable = HighScores.get()
    # creation de la variable de type game
    game = Game.create(
        menu,
        level,
        snake,
        food,
        win,
        state,
        name,
        difficulty,
        score,
        HighScoreTable
        )

    return game
def interact(game):
    if Game.getState(game) == 'menu':
        Menu.interact(game)
    elif Game.getState(game) == 'game':
        Game.interact(game)
    elif Game.getState(game) == 'editor':
        editor.start()
        Game.setState('menu', game)
        Game.setLevel(Level.create(1, 'levels.txt'), game)
    elif Game.getState(game) == 'quitGame':
        Game.quitGame(game)
    return
Example #14
0
	def setupScene(self):
		sceneManager = self.root.createSceneManager(ogre.ST_GENERIC, "Default SceneManager")

		level = Level.newLevel(sceneManager)

		self.camera = sceneManager.createCamera("Camera")
		self.camera.position = (0, 150, -500)
		self.camera.lookAt ((0, 0, 0))
		self.camera.nearClipDistance = 5

		Input.onKey('W', self.forward)
		Input.onKey('S', self.back)
				
		viewPort = self.root.getAutoCreatedWindow().addViewport(self.camera)
		self.camera.aspectRatio = float (viewPort.actualWidth) / float (viewPort.actualHeight)
Example #15
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('Game')
    pygame.mouse.set_visible(0)
    clock = pygame.time.Clock()
    level = Level(2000, 8000, 'objects1.ini', DATA_PATH)
    pygame.display.flip()
    screen.blit(level.background, (0, 0))

#Main Loop
    while 1:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
            if event.type > pygame.USEREVENT:
                Timer.handle_event(event.type)
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    level.player.check_interactions()

        if pygame.key.get_pressed()[pygame.K_RETURN]:
            edit_main(screen)
            level.load()
        if pygame.key.get_pressed()[pygame.K_RIGHT]:
            level.player.move_direction(DIR_RIGHT)
        elif pygame.key.get_pressed()[pygame.K_LEFT]:
            level.player.move_direction(DIR_LEFT)
        else:
            level.player.iswalking = False
        if pygame.key.get_pressed()[pygame.K_SPACE]:
            if level.player.jump_state == NOT_JUMPING and level.player.airborne is not True:
                level.player.start_jump()

        level.update()
        level.draw(screen)

        pygame.display.flip()
Example #16
0
    def __init__(self):
        print "INIT GAME"
    #**************************** основное window
        self.win_width = 1024#Ширина создаваемого окна
        self.win_height = 700# Высота
        self.win_display = (self.win_width,self.win_height)# Группируем ширину и высоту в одну переменную
        self.timer = pygame.time.Clock()
        self.online = True
    #**************************** инициализация

        self.left = self.right = self.up = self.down = self.space = False
        self.exit_ = True# флаг для выхода
        self.windows = Windows()# инициализируем Windows
        self.player = Player((100,100))# инициализируем Tank
        #self.bul = self.player.shot_bull()
        self.level1 = Level('level1.txt')#Инициализируем level1
        self.level1.load_level()
        self.platforms = self.level1.ret_tiles()

#******************************* свойства для сетевого взаимодействия
        self.id = None
        self.data = {}
        self.data['type'] = 'game'
        self.data['shoot'] = False
        self.move_coord = (0,0,0,0)
        self.stop_coord = (0,0,0,0)

    #**************************** блоки спрайтов

        self.block_list = pygame.sprite.Group() #Это список спрайтов. Каждый блок добавляется в этот список.
        self.all_sprites_list = pygame.sprite.Group()# # Это список каждого спрайта. Все блоки, а также блок игрока.
        self.bullet_list = pygame.sprite.Group()#тес массив спрайтов пули

        self.block_list.add(self.platforms)
        self.all_sprites_list.add(self.player)

        self.cf = ClientConnFactory(self)
        reactor.connectTCP(HOST,PORT,self.cf)
        reactor.run()
def init():

    curses.initscr()
    curses.noecho()
    curses.cbreak()
    logging.basicConfig(filename = 'tower.log', level = logging.INFO)
    # definition de la fenetre
    begin_x = 0
    begin_y = 0
    height = 100
    width = 100
    win = curses.newwin(height, width, begin_y, begin_x)

    win.keypad(1)
    curses.curs_set(0)
    curses.start_color()
    curses.use_default_colors()
    # creation des elements du jeu
    background = Background.create("image.txt")
    player = Player.create(4, 1, 10, [(0, 0)], 200)
    level = Level.create(6, [], background, 5)
    refTime = int(time.time())
    game = Game.create(background, player, level, win, refTime)
    return game
Example #18
0
def init():
    global player


    scrolling_manager = cocos.layer.scrolling.ScrollingManager
    m_layer = cocos.layer.Layer()
    i_layer = _InputLayer()
    a_layer = cocos.layer.ScrollableLayer()
    l_layer = cocos.layer.ScrollableLayer()

    floors = Level.init(Floor.BasicFloor, Floor.BasicWall, l_layer)

    player = Actor.Player(5, 5)
    player.set_weapon(Actor.Sword)
    State.player = player
    a_layer.add(player.weapon)
    a_layer.add(player)

    m_layer.add(i_layer)
    m_layer.add(l_layer)
    m_layer.add(a_layer)
    m_layer.position = (80, 80)

    return m_layer
Example #19
0
def main():
	#Pygame Settings
	pygame.mixer.pre_init(44100, 16, 2, 4096)
	pygame.init()
	pygame.mixer.init()
	clock = pygame.time.Clock()
	screen = pygame.display.set_mode((WIDTH, HEIGHT), FULLSCREEN)
	pygame.display.set_caption("Nahui Tochtli")
	
	#Game Settings
	game_menu = Main_Menu(screen)
	level_number = get_levels()
	current_level = Level(level_number)
	current_status = "mainscreen"
	pause = False
	
	#Media
	music = SFX(pygame.mixer.Sound("audio/music/nahuitochtli.wav"))
	
	
	#Main Loop
	while True:
		time=clock.tick(60)
		KEYS_PRESSED = pygame.key.get_pressed()
		EVENTS = pygame.event.get()
		
		#MAIN MENU
		if current_status == "mainscreen":
			#Play music
			if not music.is_playing():
				music.get_sfx().play(-1)
			opt = game_menu.blit_menu("mainscreen", (0,0), current_level, EVENTS, level_number)
			if opt == -1:
				current_status = "quit"
			elif opt == 0:
				current_status = "newgame"
				#Stop music
				music.get_sfx().fadeout(100)
				#Play intro
				pygame.mixer.quit()
				play_movie("intro", screen)
				pygame.mixer.init()
				#Start level
				current_level = Level()
				level_number = 1
			elif opt == 1:
				current_status = "newgame"
				current_level = Level(level_number)
				#Stop music
				music.get_sfx().fadeout(100)
			elif opt == 2:
				current_status = "codices"
			elif opt == 3:
				current_status = "howtoplay"
			elif opt == 4:
				current_status = "about"
				
		#QUIT				
		if current_status == "quit":
			save_level(level_number)
			sys.exit(0)
		
		#NEW GAME / CONTINUE
		if current_status == "newgame":
			
			if not current_level.completed():
				if pause == False:
					current_level.update(time, KEYS_PRESSED, EVENTS, screen)
					if KEYS_PRESSED[K_p]:
						pause = True
						current_level.stop_music()
				if pause == True:
					opt = game_menu.blit_menu("pause", (0,0), current_level, EVENTS, level_number)
					if opt == 0:
						current_status = "mainscreen"
						pause = False
					elif opt == 1:
						pause = False
			else:
				if current_level.victory():
					#Last level
					if level_number == 11:
						#Play ending video
						pygame.mixer.quit()
						play_movie("end", screen)
						pygame.mixer.init()
						#Return to codices
						current_status = "codices"
						level_number += 1
					#Other levels
					else:
						opt = game_menu.blit_menu("win", (0,0), current_level, EVENTS, level_number)
						if opt == 0:
							level_number += 1
							current_status = "mainscreen"
						elif opt == 2:
							level_number += 1
							current_status = "codices"
						elif opt == 1:
							if level_number < 11:
								level_number += 1
								current_level = Level(level_number)

				elif not current_level.victory():
					opt = game_menu.blit_menu("lose", (0,0), current_level, EVENTS, level_number)
					#Restart this level
					if opt == 1:
						current_level = Level(level_number)
					elif opt == 0:
						current_status = "mainscreen"
		
		#ABOUT
		if current_status == "about":
			#Play music
			if not music.is_playing():
				music.get_sfx().play(-1)
				
			opt = game_menu.blit_menu("about", (0,0), current_level, EVENTS, level_number)
			if opt == 0:
				current_status = "mainscreen"
		
		#HOW TO PLAY
		if current_status == "howtoplay":
			#Play music
			if not music.is_playing():
				music.get_sfx().play(-1)
				
			opt = game_menu.blit_menu("howtoplay", (0,0), current_level, EVENTS, level_number)
			if opt == 0:
				current_status = "mainscreen"
				
		#CODICES
		if current_status == "codices":
			#Play music
			if not music.is_playing():
				music.get_sfx().play(-1)
				
			opt = game_menu.blit_menu("codices", (0,0), current_level, EVENTS, level_number)
			if opt == 0:
				current_status = "mainscreen"
			elif opt == 1:
				current_status = "codex_1"
			elif opt == 2:
				current_status = "codex_2"
			elif opt == 3:
				current_status = "codex_3"
			elif opt == 4:
				current_status = "codex_4"
			elif opt == 5:
				current_status = "codex_5"
			elif opt == 6:
				current_status = "codex_6"
			elif opt == 7:
				current_status = "codex_7"
			elif opt == 8:
				current_status = "codex_8"
			elif opt == 9:
				current_status = "codex_9"
			elif opt == 10:
				current_status = "codex_10"
			elif opt == 11:
				current_status = "codex_11"
		
		#CODEX X
		if current_status.startswith("codex_"):
			#Play music
			if not music.is_playing():
				music.get_sfx().play(-1)
				
			opt = game_menu.blit_menu(current_status, (0,0), current_level, EVENTS, level_number)
			if opt == 0:
				current_status = "codices"
				
		#System Events
		for event in EVENTS:
			if event.type==QUIT:
				save_level(level_number)
				sys.exit(0)
		pygame.display.update()
Example #20
0
class Game():
    def __init__(self):
        print "INIT GAME"
    #**************************** основное window
        self.win_width = 1024#Ширина создаваемого окна
        self.win_height = 700# Высота
        self.win_display = (self.win_width,self.win_height)# Группируем ширину и высоту в одну переменную
        self.timer = pygame.time.Clock()
        self.online = True
    #**************************** инициализация

        self.left = self.right = self.up = self.down = self.space = False
        self.exit_ = True# флаг для выхода
        self.windows = Windows()# инициализируем Windows
        self.player = Player((100,100))# инициализируем Tank
        #self.bul = self.player.shot_bull()
        self.level1 = Level('level1.txt')#Инициализируем level1
        self.level1.load_level()
        self.platforms = self.level1.ret_tiles()

#******************************* свойства для сетевого взаимодействия
        self.id = None
        self.data = {}
        self.data['type'] = 'game'
        self.data['shoot'] = False
        self.move_coord = (0,0,0,0)
        self.stop_coord = (0,0,0,0)

    #**************************** блоки спрайтов

        self.block_list = pygame.sprite.Group() #Это список спрайтов. Каждый блок добавляется в этот список.
        self.all_sprites_list = pygame.sprite.Group()# # Это список каждого спрайта. Все блоки, а также блок игрока.
        self.bullet_list = pygame.sprite.Group()#тес массив спрайтов пули

        self.block_list.add(self.platforms)
        self.all_sprites_list.add(self.player)

        self.cf = ClientConnFactory(self)
        reactor.connectTCP(HOST,PORT,self.cf)
        reactor.run()
    #****************************инициализируем pygame (получаем screen)
    def init_window(self):
        pygame.init()#инициализируем pygame
        self.screen = pygame.display.set_mode(self.win_display)# Создаем окошко
        pygame.display.set_caption('Tanks')#название шапки "капчи"

    #****************************обработка процессов и действий (обработка нажатий (mouse and keyboard и др.))
    def tick(self):
        self.timer.tick(60)
    #****************************обработка
        for event in pygame.event.get():
            if event.type == KEYDOWN and event.key == K_LEFT:
                self.left = True

                #self.sendData("left = True")
                self.data['coordinate'] = (1,0,0,0)
                self.sendData(self.data)
            if event.type == KEYUP and event.key == K_LEFT:
                self.left = False
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)

            if event.type == KEYDOWN and event.key == K_RIGHT:
                self.right = True
                #self.sendData('self.right = True')
                self.data['coordinate'] = (0,1,0,0)
                self.sendData(self.data)

            if event.type == KEYUP and event.key == K_RIGHT:
                self.right = False
                #self.sendData('self.right = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_UP:
                self.up = True
                #self.sendData('self.up = True')
                self.data['coordinate'] = (0,0,1,0)
                self.sendData(self.data)

            if event.type == KEYUP and event.key == K_UP:
                self.up = False
                #self.sendData('self.up = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_DOWN:
                self.down = True
                self.data['coordinate'] = (0,0,0,1)
                self.sendData(self.data)

                #self.sendData('self.down = True')
            if event.type == KEYUP and event.key == K_DOWN:
                self.down = False
                #self.sendData('self.down = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_SPACE:
                self.space = True
                #self.sendData('self.space = True')
                self.data['shoot'] = True
                self.sendData(self.data)
            if event.type == KEYUP and event.key == K_SPACE:
                self.shot_bull_game()
                self.space = False
                self.data['shoot'] = False
                self.sendData(self.data)

            if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE):
                self.sendData("GOODBYE!!!!!!!")
                reactor.stop()
                sys.exit(0)

        self.draw_game()
        self.update_game()


    #****************************отобрыжение процессов
    def draw_game(self):
        self.windows.draw_windows(self.screen)#рисуем окна
        self.all_sprites_list.draw(self.screen)
        self.block_list.draw(self.screen)
        self.bullet_list.draw(self.screen)
        pygame.display.update()# обновление и вывод всех изменений на экран

    #****************************shot
    def shot_bull_game(self):
        self.player.shot_bull()
        self.bullet_list.add(self.player.ret_bull())

    #**************************** при столкновении пули с объектом удаление пули
    def destroy_bull_game(self):

        sprite.groupcollide(self.block_list,self.bullet_list,0,1)

    #**************************** update
    def update_game(self):
        self.player.tank_update(self.left,self.right,self.up,self.down,self.space,self.platforms)
        self.destroy_bull_game()
        self.player.bull_move()

    #****************************удаление данных (destroy data here)
    def end_pygame():
        pygame.quit()

    #****************************ЗАПУСК ИГРЫ
    def play_game(self):
        print 'play_game'
        self.init_window()
        #self.end_pygame()

    #****************************фунция запуска

    def sendData(self, data):
        self.cf.conn.send(data)

    def getData(self, data):
        print "INCOMING: ", data
        self.parseData(data)

    def parseData(self, data):
        print type(data)
        if isinstance(data, dict):
            print "PARSING"
            print data['id']
            if data.get('type') == 'start':
                print 'START  THE GAME'
            for k in data:
                print "KEY: ",k," VALUE: ",data[k]
Example #21
0
def run():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

    # Create the player
    player = pl.Player()

    # All clones
    clones = []

    # Create all the levels
    level_list = []
    level_list.append(lvl.Level01(player))
    level_list.append(lvl.Level02(player))
    level_list.append(lvl.Level03(player))

    # Set the current level
    current_level_number = 0
    current_level = level_list[current_level_number]
    current_level.__init__(player)

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level
    active_sprite_list.add(player)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()


    joysticks = []
    for i in range(0, pygame.joystick.get_count()):
        joysticks.append(pygame.joystick.Joystick(i))
        joysticks[i].init()
        print("Detected joystick '", joysticks[i].get_name(), "'")

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if (event.type == pygame.JOYHATMOTION and joysticks[0].get_hat(0) == (-1, 0)) or (event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT):
                player.go_left()
            if (event.type == pygame.JOYHATMOTION and joysticks[0].get_hat(0) == (1, 0)) or (event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT):
                player.go_right()
            if (event.type == pygame.JOYBUTTONDOWN and joysticks[0].get_button(0)) or (event.type == pygame.JOYHATMOTION and joysticks[0].get_hat(0) == (0, 1)) or (event.type == pygame.KEYDOWN and event.key == pygame.K_UP):
                player.jump()
            if (event.type == pygame.JOYBUTTONDOWN and (joysticks[0].get_button(1) or joysticks[0].get_button(2))) or (event.type == pygame.KEYDOWN and event.key == pygame.K_r):
                right = True
                if player.current_anim != player.right_anim:
                    right = False
                clones.append([player.width(), player.height(), -current_level.world_shift + player.rect.x, player.rect.y, right, player.reverse_gravity])
                player.reverse_gravity = False
                player.set_animation_gravity()
                current_level.reset(clones)
            if (event.type == pygame.JOYBUTTONDOWN and joysticks[0].get_button(6)) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                player.reverse_gravity = False
                player.set_animation_gravity()
                clones.clear()
                current_level.__init__(player)
            if (event.type == pygame.JOYBUTTONDOWN and joysticks[0].get_button(3)) or (event.type == pygame.KEYDOWN and event.key == pygame.K_2):
                if player.reverse_gravity:
                    player.reverse_gravity = False
                    player.set_animation_gravity()
                else:
                    player.reverse_gravity = True
                    player.set_animation_gravity()

            if (event.type == pygame.JOYHATMOTION and joysticks[0].get_hat(0) == (0, 0)) or (event.type == pygame.KEYUP and event.key == pygame.K_LEFT and player.change_x < 0):
                player.stop()
            if (event.type == pygame.JOYHATMOTION and joysticks[0].get_hat(0) == (0, 0)) or (event.type == pygame.KEYUP and event.key == pygame.K_RIGHT and player.change_x > 0):
                player.stop()
            if (event.type == pygame.JOYBUTTONDOWN and joysticks[0].get_button(7)) or (event.type == pygame.KEYUP and event.key == pygame.K_p):
                player.stop()
                done = Pause.run()
        if done:
            continue

        # Update the player.
        active_sprite_list.update()

        spikes = pygame.sprite.spritecollide(player, current_level.spike_list, False)
        if len(spikes) > 0:
            player.reverse_gravity = False
            player.set_animation_gravity()
            clones.clear()
            current_level.__init__(player)

        goals = pygame.sprite.spritecollide(player, current_level.goal_list, False)
        if len(goals) > 0:
            player.reverse_gravity = False
            player.set_animation_gravity()
            clones.clear()
            current_level_number += 1
            if current_level_number >= len(level_list):
                done = True
                continue
            current_level = level_list[current_level_number]
            current_level.__init__(player)
            player.level = current_level
            continue

        # Update items in the level
        current_level.update()

        left_scroll = SCREEN_WIDTH * .4
        right_scroll = SCREEN_WIDTH * .6
        # If the player gets near the right side, shift the world left (-x)
        if player.rect.right >= right_scroll:
            diff = player.rect.right - right_scroll
            player.rect.right = right_scroll
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.left <= left_scroll:
            diff = left_scroll - player.rect.left
            player.rect.left = left_scroll
            current_level.shift_world(diff)

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    Menu.main(pygame.mixer.music.get_volume())
Example #22
0
def dialogueLoop(textList, path):
	q = 1 # this might actually be useless
	font = pygame.font.SysFont('Courier New', 30) #initializes pygame.font
	#font = pygame.font.Font(None, 30)
	dialogueBox = pygame.image.load(os.path.join('conf','TextBox.png')) #loads the image that holds the text
	#print "hero: ",Hero.rect.bottom
	#print "path: ",path
	windowRect = window.get_rect()
	x = (windowRect.right - 800)/2
	yTest = windowRect.bottom - 300
	if Hero.rect.bottom >= yTest - 10: # if the sprite is too close to where the text box would noramlly be, the box is moved to the top
		y = windowRect.top
		#print "True"
	else:
		y = yTest
	level = Level(path, windowRect)
	level.read_map() #redoes the level
	Textbackground = level.render()
	#Textbackground = pygame.Surface(windowRect.bottomright)
	b = 0
	textList_broken = [] #empty set to use for the broken up text
	if len(textList) > 3:
		while len(textList) != 0: #while there are still things in textList
			a = 0
			tripletset = [] #empty set to hold sets of triple lines
			while a < 3 and len(textList) != 0:
				#print "a: ",a
				#print textList
				tripletset.append(textList[0]) #adds first line from textList to tripleset
				textList.pop(0) #removes the line that was just added
				#print "length :",len(textList)
				a += 1
			if len(textList) !=0:
				tripletset.append(u'\u25bc') #if it's not the last line, adds a ▼ to the set to show text continues
			textList_broken.append(tripletset) #adds tripleset to textList_broken
#			a = 0
			#print "broken: ",textList_broken
	#print "lenght", len(textList)
	textList = textList_broken
	#print "list: ",textList
#	while q <= 200:
		#rectCoord = Hero.get_rect()
		#print y
		#Textbackground.blit(background, (0,0))
	for m in range(len(textList)):
		"""This loop here is what puts the text onto the screen. The data structure is set up so that the first
		is a list of 3 line text blocks (pages) then it is a list of those lines. 
		"""
		Textbackground.blit(dialogueBox, (x,y)) #blits the dialogue image onto the level background
		q = 0
		while q == 0:
			for event in pygame.event.get():
				for n in range(len(textList[m])):
					words = font.render(textList[m][n], 1, (0, 0, 0))
					Textbackground.blit(words, (x+20, y+20+n*30))
				char.update(obstacles)
				change_Background(Textbackground, (0,0), True, char)
				pygame.display.flip()
				if event.key == K_RETURN and event.type == KEYDOWN:
					#print "STUFF"
					q = 1
Example #23
0
def main(currentWorld, path, windowRect, level, background, obstacles, teleports, position, Hero, char, attack, defense, Enemy, heroSprite, enemySprites):
	leftcount = 0
	while True:
		fpsClock.tick(45)                                  # max of 45fps
		for event in pygame.event.get():
			#print event
			if event.type == QUIT: #check for quit signal and properly terminate. 
				shutdown()
				return
			if event.type == KEYDOWN: # checks for actions
				#print event.key
				if event.key == K_ESCAPE: #escape key exits
					shutdown()
					return
				elif event.key == K_l:
					Save.saveGame(currentWorld, Hero.getRect().topleft, Hero.health, Enemy.getRect().topleft, Enemy.health, Enemy.world, Enemy.old_state, Enemy.state)
				elif (event.key == K_LEFT) or (event.key == K_RIGHT) or (event.key == K_DOWN) or (event.key == K_UP):
					# Checks for arrow keys and moves the character in that direction
					Hero.start(event.key, obstacles)
					#Enemy.start(event.key, obstacles)
				else:
					k, q = 1,1 #counters
					while k == 1:
						if q == 1: #this is a way to prevent a bug where everything was being done twice causing a crash
							reader = KeyReader(event.key, window, fpsClock.tick(45))
							k, backg, track = reader.testKey(background) # from KeyReader.py
							inventory = InventoryMap(window) #initializes the inventory system
							if track == 'inventory':
								item = inventory.moveCursor(False,track)
								if item != False and item != None:
									Hero.changeSheet(os.path.join('SpriteDev','Sheets',item.rstrip())) #updates the sprite sheet to be of the character holding the weapon
									pygame.display.flip() #updates the screen
									heroSprite = pygame.sprite.RenderPlain(Hero) #renders the sprite
								break
							elif track == 'weapons':
								item = inventory.moveCursor(True,track)
								if item != False and item != None:
									Hero.changeSheet(os.path.join('SpriteDev','Sheets',item.rstrip())) #updates the sprite sheet to be of the character holding the weapon
									pygame.display.flip() #updates the screen
									heroSprite = pygame.sprite.RenderPlain(Hero) #renders the sprite
									#if item.rstrip() == "Sword.png":
									attack, defense = weaponData(item)
								break
							elif track == 'swing':
								kill = swing(Hero, attack, defense, Enemy)
								if kill == True:
									Enemy.kill(True)
									enemycollide = False
								break
							if backg != 1 and track == 'talk': #just a testing thing
								dialogueLoop(k, path) # see documentation there
								level = Level(path, windowRect) #re parses teh backround
								level.read_map() 
								background = level.render() #resets the background
								#if Hero.old_state == None:
								#	print "down"
								#	print attack 
								#elif Hero.state == 'still': #and Hero.state != None:
								#	print Hero.old_state+" old"
								#	print attack
								#else:
								#	print Hero.state+" current"
								#	print attack
							#print isinstance(k, int)
							if k == 42: #42 is the official quit signal for k
								q = 0
							elif isinstance(k, int) != True: # checks to see if k value is a code or string
								#print "break"
								break
							elif event.key == K_ESCAPE:
								shutdown() #makes sure that pressing escape quits the program
								return
							else:
								q +=1 #iterates the main loop if nothing happens
						if backg != 1:
							change_Background(backg, (0,0), True)
						if track == 'quit':
							break
						pygame.display.flip()
			elif event.type == KEYUP: #stops movement when arrow key is released
				#print Hero.state,"hero"
				Hero.stopSimple()
				#Enemy.stopSimple()
				#print Hero.state,"hero"
		herocollide = True
		if Enemy.alive() == True:
			herocollide = Enemy.check_collision(Enemy.getRect(),[Hero.getRect()])
			enemyCollide = Hero.check_collision(Hero.getRect(),[Enemy.getRect()])
		else:
			enemyCollide = False
		if herocollide != True:
			Enemy.AI(Hero.getRect().center, obstacles)
			#Enemy2.AI(Hero.getRect().center, obstacles)
		elif Enemy.alive():
			Enemy.stop(20)
			damage = .25-float(defense)
			if damage < 0:
				damage = 0 
			Hero.health -= damage
			#print "hero: %s" % Hero.health
			#print Hero.rect.size
		if leftcount == 140:
			leftcount = 0
		#if leftcount%10 == 0:
			#print Enemy.rect.center
		char.update(obstacles) #checks for collisions between sprites
		if enemyCollide != False and Enemy.alive() == True:
			#print "Here"
			Hero.stop(5)
		path_2 = Hero.check_teleport(currentWorld, teleports) #checks to see if the character has moved to a different world
		if (path_2 != path) and (path_2 != None): #if path_2 is different than the already existent one, and exists
			path = path_2 #sets path to path_2
			#print "main path:", path
			level = Level(os.path.join('conf',path), windowRect)
			level.read_map()                #redoes the level render
			currentWorld = Hero.getWorld()  #sets the current word to wherever the hero is so that background can be properly rendered
			#print currentWorld
			background = level.render() #makes the background
			char = pygame.sprite.RenderPlain(Hero) 
		teleports = [] # clears the sets
		obstacles = []
		obstacles, teleports = getTiles() # resets the tiles
		if Hero.health <= 0:
			shutdown()
		#Test = Hero.check_collision(Hero.getRect(),[Enemy.getRect()])
		#print Test
		change_Background(background, (0,0), True, char)
		updateHearts(Hero.health)
#		window.blit(background, (0,0))
#		char.draw(window)
#		pygame.display.flip()
		save = [currentWorld, Hero.getRect().topleft, Hero.health, Enemy.getRect().topleft, Enemy.health]
Example #24
0
                level.setCell(x, y, "#")


def insertRandomRoom(level):
    x = Util.getRandom(0, LEVEL_WIDTH - 1)
    y = Util.getRandom(0, LEVEL_HEIGHT - 1)
    width = Util.getRandom(3, 6)
    height = Util.getRandom(3, 6)
    room = Level.MakeRoom(width, height)
    level.applyFeature(room, x, y)


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((300, 300))
    level = Level.Level(LEVEL_WIDTH, LEVEL_HEIGHT)
    # level.style = Tiles.tileStyles[Util.getRandom(1, 15)]
    level.style = Tiles.tileStyles[2]
    # randomizeLevel(level)

    canvas = pygame.Surface(
        (LEVEL_WIDTH * Tiles.TILE_WIDTH, LEVEL_HEIGHT * Tiles.TILE_HEIGHT))

    s_map = ScrollingMap.Scrolling_Map(screen, canvas, Tiles.TILE_HEIGHT,
                                       Tiles.TILE_WIDTH)

    maze = MazeGenerator.Maze(10, 10).getMap()
    level.applyFeature(maze, 10, 10)

    for i in range(100):
        insertRandomRoom(level)
Example #25
0
	ButtonRect3 = Rect((xh*2-i, 2*y+18-j),(130,35))
	pygame.display.flip()
	for event in pygame.event.get():
		if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): #check for quit signal and properly terminate. 
			shutdown()
			exit()
		elif event.type == MOUSEBUTTONDOWN:
			if event.button == 1:
				if ButtonRect1.collidepoint(event.pos) == True:
					attack = 1
					defense = 0
					currentWorld = 'Home'
					path = os.path.join('conf','levelmap')
					itemPath = 'ItemData'
					windowRect = window.get_rect()
					level = Level(path, windowRect)
					level.read_map()
					background = level.render()
					window.blit(background, (0,0))
					obstacles, teleports = getTiles()
					pygame.display.flip()
					position = getCharacter()
					Hero = Sprite.Sprite(position, obstacles, os.path.join('SpriteDev','Sheets','spritesheet1.png'),(os.path.join('SpriteDev','UpStill.png'),os.path.join('SpriteDev','RightStill.png'),os.path.join('SpriteDev','DownStill.png'),os.path.join('SpriteDev','LeftStill.png')), True)
					Enemy = Enemies.Enemy((400,500), obstacles, os.path.join('SpriteDev','Sheets','enemysheet.png'),(os.path.join('SpriteDev','EnemyUpStill.png'),os.path.join('SpriteDev','EnemyRightStill.png'),os.path.join('SpriteDev','EnemyDownStill.png'),os.path.join('SpriteDev','EnemyLeftStill.png')), currentWorld, True)
					char = pygame.sprite.RenderPlain(Hero, Enemy)
					heroSprite = pygame.sprite.RenderPlain(Hero)
					enemySprites = pygame.sprite.RenderPlain(Enemy)
					h = 0
					main(currentWorld, path, windowRect, level, background, obstacles, teleports, position, Hero, char, attack, defense, Enemy, heroSprite, enemySprites)
				if ButtonRect2.collidepoint(event.pos) == True:
					save = []
Example #26
0
def gotoMission(gotoMap, player1, player2):
    Config.mission = True
    # Setup mixer to avoid sound lag
    pygame.mixer.pre_init(44100, -16, 2, 2048)

    # Call this function so the Pygame package can initialize itself
    pygame.init()

    # Sounds
    shootSound = pygame.mixer.Sound(os.path.join('sound','shoot.wav'))
    boomSound = pygame.mixer.Sound(os.path.join('sound','boom.wav'))

    # 48*25
    screen_width = 1200
    # 64*12
    screen_height = 640
    screen = pygame.display.set_mode([screen_width, screen_height])

    # GUI Initialization 
    
    form = gui.Form()
    app = gui.App()
    chatCtrl = ChatControl()
    c = gui.Container(align = -1, valign = -1)
    c.add(chatCtrl, 0, 16*32)
    app.init(c)
    
    # Font
    font  = pygame.font.Font(os.path.join('data', 'freesansbold.ttf'), 17)
    font1 = pygame.font.Font(os.path.join('data', 'freesansbold.ttf'), 18)

    pygame.display.set_caption('Commando Python : Infiltration Zombi')

    # Panel
    image_fnscar = pygame.image.load("images/panel/gun_fnscar.png").convert()
    bar_bottom = pygame.image.load("images/panel/bar_bottom.png").convert()
    bar_right = pygame.image.load("images/panel/bar_right.png").convert()

    # Initialization players

    #player1 = Player("player1")
    #player2 = Player("player2")

    player1MovingSprites = pygame.sprite.RenderPlain()
    player1MovingSprites.add(player1)
    player2MovingSprites = pygame.sprite.RenderPlain()
    player2MovingSprites.add(player2)

    # Initialization zombis
    zombi_list = pygame.sprite.RenderPlain()
    zombiMap = loadZombiMap(gotoMap.mapId, zombi_list)
        
    # Sprites
    all_sprites_list = pygame.sprite.RenderPlain()

    wall_list = pygame.sprite.RenderPlain()

    item_list = pygame.sprite.RenderPlain()

    npc_list = pygame.sprite.RenderPlain()

    ground_list = pygame.sprite.RenderPlain()
     
    # List of each bullet
    bullet_list = pygame.sprite.RenderPlain()

    # Load level (default level)
    way_list = list()
    currentlevel = Level(gotoMap.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)


    clock = pygame.time.Clock()

    gameloop = False

    newLevel = False

    debug = False

    displayPlayer = 1

    displayCharacPlayer1 = False 
    displayCharacPlayer2 = False

    currentMapId = gotoMap.mapId

    guiDisplay = False

    # Main game loop

    while gameloop == False:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameloop = True
            
            if guiDisplay == True:
                app.event(event)
            
            # Left mouse click
            if pygame.mouse.get_pressed()[0] == True:
                mousex = pygame.mouse.get_pos()[0]
                mousey = pygame.mouse.get_pos()[1]
                #print str(mousex) + " " +  str(mousey)
                #print str(player1.rect.x + 24) + " " + str(player1.rect.y + 32)
                for wall in wall_list:
                    #print "wall: " + str(wall.x / 32) + " " + str(wall.y / 32)
                    # Delete wall
                    if( mousex > wall.x and mousex < wall.x + 32 and mousey > wall.y and mousey < wall.y + 32):
                        #print "Delete wall" 
                        wall_list.remove(wall)
                        all_sprites_list.remove(wall)

                if mousex > player1.rect.x and mousex < player1.rect.x + 48 and mousey > player1.rect.y and mousey < player1.rect.y + 64:
                    if displayCharacPlayer1 == False:
                        #print "Display CharacPlayer1"
                        displayCharacPlayer1 = True
                    else:
                        #print "Not Display CharacPlayer1"
                        displayCharacPlayer1 = False
                if mousex > player2.rect.x and mousex < player2.rect.x + 48 and mousey > player2.rect.y and mousey < player2.rect.y + 64:
                    if displayCharacPlayer2 == False:
                        #print "Display CharacPlayer2"
                        displayCharacPlayer2 = True
                    else:
                        #print "Not Display CharacPlayer2"
                        displayCharacPlayer2 = False




            # Right mouse click
            if pygame.mouse.get_pressed()[2] == True:        
                #print "Add wall"
                mousex = pygame.mouse.get_pos()[0]
                mousey = pygame.mouse.get_pos()[1]
                #print str((mousex ) ) + " " + str( (mousey ) ) + " " + str(mousex - (mousex % 32) ) + " " + str( mousey-(mousey % 32) )
                wall = Wall("int_wall_bricks.png", (mousex - (mousex % 32)) / 32, (mousey-(mousey % 32)) / 32, 32, 32)
                wall_list.add(wall)
                all_sprites_list.add(wall)
     
           
            if event.type == pygame.KEYDOWN:
            
                # Enable Gui

                if event.key == pygame.K_F5:
                    print "guiDisplay"         
                    if guiDisplay == True:
                        guiDisplay = False
                    else:
                        guiDisplay = True              
            
                if guiDisplay == False:
                
                    if event.key == pygame.K_q and displayPlayer == 1:
                        gameloop = True
                        Config.mission = False;
                        # Save all
                        savePlayer(player1)
                        savePlayer(player2)

                        saveWallMap(player1.mapId, wall_list)
                        saveItemMap(player1.mapId, item_list)

                    # Music
                    if event.key == pygame.K_m:
                        if pygame.mixer.music.get_busy():
                            pygame.mixer.music.stop()
                        else:
                            pygame.mixer.music.play()
                    # Sound
                    # Silent Cloth
                    if event.key == pygame.K_s:
                        player1.setSilent("Silent Cloth")

                    # Debug
                    if event.key == pygame.K_d:
                        print "Debug:"

                    # Switch between player
                    if event.key == pygame.K_F1 and (player1.mapId != player2.mapId):
                        #print "Komando1"
                        displayPlayer = 1
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player1.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        currentMapId = player1.mapId                 
       
                    if event.key == pygame.K_F2 and (player1.mapId != player2.mapId):
                        #print "Komando2"
                        displayPlayer = 2
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player2.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        currentMapId = player2.mapId

                    # Show current players position
                    if event.key == pygame.K_w:
                        print "Current player1 position: " + str(player1.mapId) + " " + str(player1.rect.x) + " " + str(player1.rect.y)
                        print "Current player2 position: " + str(player2.mapId) + " " + str(player2.rect.x) + " " + str(player2.rect.y)

                    # Change level
                    # Left border
                    if player1.direction == 4 and player1.rect.x <= -(player1.halfWidthPlayer) and newLevel == False:
                        saveWallMap(player1.mapId, wall_list)
                        player1.mapId = player1.mapId - 1
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player1.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player1.rect.x = (32 * 30) - player1.halfWidthPlayer
                        newLevel = True;
                        displayPlayer = 1
                        #print "Left: Move to: " + str(player1.mapId) + " " + str(player1.rect.x) + " " + str(player1.rect.y)
                        currentMapId = player1.mapId
                    
                    # Right Border
                    if player1.direction == 6 and player1.rect.x >= (30 * 32) - player1.halfWidthPlayer and newLevel == False:
                        saveWallMap(player1.mapId, wall_list)
                        player1.mapId = player1.mapId + 1
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player1.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player1.rect.x = -(player1.halfWidthPlayer)
                        newLevel = True;
                        displayPlayer = 1
                        #print "Right: Move to: " + str(player1.mapId) + " " + str(player1.rect.x) + " " + str(player1.rect.y)
                        currentMapId = player1.mapId

                    # Top border
                    if player1.direction == 8 and player1.rect.y <= -(player1.halfHeightPlayer) and newLevel == False :
                        saveWallMap(player1.mapId, wall_list)
                        player1.mapId = player1.mapId - 21 
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player1.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player1.rect.y = (32 * 15) - player1.halfHeightPlayer
                        newLevel = True;
                        displayPlayer = 1
                        #print "Top: Move to: " + str(player1.mapId) + " " + str(player1.rect.x) + " " + str(player1.rect.y)
                        currentMapId = player1.mapId

                    # Bottom Border
                    if player1.direction == 2 and player1.rect.y >= (32 * 15) - player1.halfHeightPlayer and newLevel == False :
                        saveWallMap(player1.mapId, wall_list)
                        player1.mapId = player1.mapId + 21
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player1.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player1.rect.y = -(player1.halfHeightPlayer)
                        newLevel = True;
                        displayPlayer = 1
                        #print "Bottom: Move to: " + str(player1.mapId) + " " + str(player1.rect.x) + " " + str(player1.rect.y)
                        currentMapId = player1.mapId


                    # Left border
                    if player2.direction == 4 and player2.rect.x <= -(player2.halfWidthPlayer) and newLevel == False :
                        saveWallMap(player2.mapId, wall_list)
                        player2.mapId = player2.mapId - 1
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player2.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player2.rect.x = (32 * 30) - player2.halfWidthPlayer
                        newLevel = True;
                        displayPlayer = 2
                        #print "Left: Move to: " + str(player2.mapId) + " " + str(player2.rect.x) + " " + str(player2.rect.y)
                        currentMapId = player2.mapId
                        
                    # Right Border
                    if player2.direction == 6 and player2.rect.x >= (30 * 32) - player2.halfWidthPlayer and newLevel == False :
                        saveWallMap(player2.mapId, wall_list)
                        player2.mapId = player2.mapId + 1
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player2.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player2.rect.x = -(player2.halfWidthPlayer)
                        newLevel = True;
                        displayPlayer = 2
                        #print "Right: Move to: " + str(player2.mapId) + " " + str(player2.rect.x) + " " + str(player2.rect.y)
                        currentMapId = player2.mapId

                    # Top border
                    if player2.direction == 8 and player2.rect.y <= -(player2.halfHeightPlayer) and newLevel == False :
                        saveWallMap(player2.mapId, wall_list)
                        player2.mapId = player2.mapId - 21 
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player2.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player2.rect.y = (32 * 15) - player2.halfHeightPlayer
                        newLevel = True;
                        displayPlayer = 2
                        #print "Top: Move to: " + str(player2.mapId) + " " + str(player2.rect.x) + " " + str(player2.rect.y)
                        currentMapId = player2.mapId

                    # Bottom Border
                    if  player2.direction == 2 and player2.rect.y >= (32 * 15) - player2.halfHeightPlayer and newLevel == False:
                        saveWallMap(player2.mapId, wall_list)
                        player2.mapId = player2.mapId + 21
                        currentlevel.empty(way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        nextlevel = Level(player2.mapId, way_list, ground_list, wall_list, all_sprites_list, item_list, npc_list)
                        player2.rect.y = -(player2.halfHeightPlayer)
                        newLevel = True;
                        displayPlayer = 2
                        #print "Bottom: Move to: " + str(player2.mapId) + " " + str(player2.rect.x) + " " + str(player2.rect.y)
                        currentMapId = player2.mapId

                    # Players movement
                    # Komando1
                    if event.key == pygame.K_LEFT :
                        player1.changeSpeed(-player1.speed, 0)
                        player1.direction = 4
                        newLevel = False

                    if event.key == pygame.K_RIGHT :
                        player1.changeSpeed(player1.speed, 0)
                        player1.direction = 6
                        newLevel = False
                        
                    if event.key == pygame.K_UP :
                        player1.changeSpeed(0, -player1.speed)
                        player1.direction = 8
                        newLevel = False

                    if event.key == pygame.K_DOWN :
                        player1.changeSpeed(0, player1.speed)
                        player1.direction = 2
                        newLevel = False

                    # Komando2
                    if event.key == pygame.K_j :
                        player2.changeSpeed(-player2.speed, 0)
                        player2.direction = 4
                        newLevel = False
                    if event.key == pygame.K_l :
                        player2.changeSpeed(player2.speed, 0)
                        player2.direction = 6
                        newLevel = False
                    if event.key == pygame.K_i :
                        player2.changeSpeed(0, -player2.speed)
                        player2.direction = 8
                        newLevel = False
                    if event.key == pygame.K_k :
                        player2.changeSpeed(0, player2.speed)
                        player2.direction = 2
                        newLevel = False


                    # Shoot with bullet
                    if event.key == pygame.K_SPACE :
                        if player1.ammunition > 0 :
                            shootSound.play()
                            if player1.direction == 8:
                                bullet = BulletVertical()
                                bullet.direction = 8
                                bullet.rect.x = player1.rect.x + 24
                                bullet.rect.y = player1.rect.y
                            if player1.direction == 6 :
                                bullet = BulletHorizontal()
                                bullet.direction = 6
                                bullet.rect.x = player1.rect.x + 48
                                bullet.rect.y = player1.rect.y + 32
                            if player1.direction == 4 :
                                bullet = BulletHorizontal()
                                bullet.direction = 4
                                bullet.rect.x = player1.rect.x 
                                bullet.rect.y = player1.rect.y + 32
                            if player1.direction == 2 :
                                bullet = BulletVertical()
                                bullet.direction = 2
                                bullet.rect.x = player1.rect.x + 24
                                bullet.rect.y = player1.rect.y + 64

                            all_sprites_list.add(bullet)
                            bullet_list.add(bullet)
                            player1.ammunition -= 1

          
          
          
          
            if guiDisplay == False:
                if event.type == pygame.KEYUP :
                    # Player 1
                    if event.key == pygame.K_LEFT :
                        player1.changeSpeed(player1.speed, 0)

                    if event.key == pygame.K_RIGHT :
                        player1.changeSpeed(-player1.speed, 0)

                    if event.key == pygame.K_UP :
                        player1.changeSpeed(0, player1.speed)

                    if event.key == pygame.K_DOWN :
                        player1.changeSpeed(0, -player1.speed)

                    # Player 2
                    if event.key == pygame.K_j :
                        player2.changeSpeed(player2.speed, 0)
                    if event.key == pygame.K_l :
                        player2.changeSpeed(-player2.speed, 0)
                    if event.key == pygame.K_i :
                        player2.changeSpeed(0, player2.speed)
                    if event.key == pygame.K_k :
                        player2.changeSpeed(0, -player2.speed)

        # Zombi Intelligence Artificial
        # Left   <-  (-s, 0)
        # Right  ->  (s, 0)
        # Up      ^  (0, -s)
        # Down    _  (0, s)

        if zombiMap == currentMapId:
            zombiSpeed = 0.1
            for zombi in zombi_list:    
                    if zombi.name == "zombi0" :
                        distanceX = math.fabs(zombi.rect.x - player1.rect.x)
                        distanceY = math.fabs(zombi.rect.y - player1.rect.y)

                        # On the right
                        if zombi.rect.x > player1.rect.x :
                            zombi.changeSpeed(-zombiSpeed, 0)
                        # On the left
                        if zombi.rect.x < player1.rect.x :
                            zombi.changeSpeed(zombiSpeed, 0)
                        # On the bottom
                        if zombi.rect.y > player1.rect.y :
                            zombi.changeSpeed(0, -zombiSpeed)
                        # On the top
                        if zombi.rect.y < player1.rect.y :
                            zombi.changeSpeed(0, zombiSpeed)



        # Update all sprites

        player1.update(all_sprites_list)
        player2.update(all_sprites_list)

        if zombiMap == currentMapId:
            zombi_list.update(all_sprites_list)

        # Calculate mechanics for each bullet
        for bullet in bullet_list:
            if bullet.name == "vertical" :
                if bullet.direction == 8 :
                    bullet.rect.y -= 5
                if bullet.direction == 2 :
                    bullet.rect.y += 5
            if bullet.name == "horizontal" :
                if bullet.direction == 6 :
                    bullet.rect.x += 5
                if bullet.direction == 4:
                    bullet.rect.x -= 5

            # See if it hit a wall

            if pygame.sprite.spritecollide(bullet, wall_list, False):
                print "Hit: wall"
                boomSound.play()
                bullet_list.remove(bullet)
                all_sprites_list.remove(bullet)

            # See if it hit a item
            item_hit_list = pygame.sprite.spritecollide(bullet, item_list, True)

            # For each item hit, remove the bullet and add to the player1.score
            for item in item_hit_list :
                print "Hit: item"
                boomSound.play()
                bullet_list.remove(bullet)
                all_sprites_list.remove(bullet)
                player1.score += 1
                saveItemMap(player1.mapId, item_list)


            # See if it hit a npc
            npc_hit_list = pygame.sprite.spritecollide(bullet, npc_list, True)

            # For each npc hit, remove the bullet and add to the player1.score
            for npc in npc_hit_list :
                #print "Hit: npc"
                boomSound.play()
                bullet_list.remove(bullet)
                all_sprites_list.remove(bullet)
                player1.score += 3


            # Remove the bullet if it flies up off the screen
            if bullet.rect.x > (30 * 32) or bullet.rect.x < 0 or bullet.rect.y > (15 * 32) or bullet.rect.y < 0:
                bullet_list.remove(bullet)
                all_sprites_list.remove(bullet)

        screen.fill(black)

        ground_list.draw(screen)


        if (player1.mapId != player2.mapId) :     
            if (displayPlayer == 1) :
                player1MovingSprites.draw(screen)

                if displayCharacPlayer1 == True :
                    characPlayer1 = font1.render("Player1", True, blue)
                else:
                    characPlayer1 = font1.render("", True, blue)

                screen.blit(characPlayer1, [player1.rect.x, player1.rect.y - 10])
                

            if (displayPlayer == 2) :
                player2MovingSprites.draw(screen)

                if displayCharacPlayer2 == True :
                    characPlayer2 = font1.render("Player2", True, blue)
                else:
                    characPlayer2 = font1.render("", True, blue)

                screen.blit(characPlayer2, [player2.rect.x, player2.rect.y - 10])


        else :
            player1MovingSprites.draw(screen)
            player2MovingSprites.draw(screen)

            if displayCharacPlayer1 == True:
                characPlayer1 = font1.render("Player1", True, blue)
            else :
                characPlayer1 = font1.render("", True, blue)

            screen.blit(characPlayer1, [player1.rect.x, player1.rect.y - 10])
       
            if displayCharacPlayer2 == True:
                characPlayer2 = font1.render("Player2", True, blue)
            else :
                characPlayer2 = font1.render("", True, blue)

            screen.blit(characPlayer2, [player2.rect.x, player2.rect.y - 10])

        # Is a zombiMap
        if zombiMap == currentMapId :
                zombi_list.draw(screen)


        all_sprites_list.draw(screen)

        # Panel

        # Player information
        if displayPlayer == 1 :        
            textName = font.render("Codename: " + str(player1.name), True, green)
            screen.blit(textName, [992, 16 * 2])

            textLife = font.render("Life: " + str(player1.life), True, green)
            screen.blit(textLife, [992, 16 * 3])

            textAmmunition = font.render("Ammunition: " + str(player1.ammunition), True, green)
            screen.blit(textAmmunition, [992, 16 * 4])

            textScore = font.render("Score: " + str(player1.score), True, green)
            screen.blit(textScore, [992, 16 * 5])

            textPlayer1MapId = font.render("Map: " + str(player1.mapId), True, green)
            screen.blit(textPlayer1MapId, [992, 0])

        if displayPlayer == 2:        
            textName = font.render("Codename : " + str(player2.name), True, green)
            screen.blit(textName, [992, 16 * 2])

            textLife = font.render("Life: " + str(player2.life), True, green)
            screen.blit(textLife, [992, 16 * 3])

            textAmmunition = font.render("Ammunition: " + str(player2.ammunition), True, green)
            screen.blit(textAmmunition, [992, 16 * 4])

            textScore = font.render("Score: " + str(player2.score), True, green)
            screen.blit(textScore, [992, 16*5])

            textPlayer2MapId = font.render("Map: " + str(player2.mapId), True, green)
            screen.blit(textPlayer2MapId, [992, 0])

        screen.blit(bar_bottom, [0, 480])
        screen.blit(bar_right, [960, 0])
        #screen.blit(image_fnscar, [960,10])

        # Display GUI
        
        app.paint()
        

        # Display
        pygame.display.flip()

        clock.tick(40)
Example #27
0
class Menu():
	#initialize pygame
	init()
	def __init__(self, surface):
		"Initialize variables, load images, set flags, and fonts"
		self.surface = surface
		self.bg = transform.scale(image.load("res/main_bg.jpg").convert(), (surface.get_width(), surface.get_height()))
		self.carImage = image.load("res/front_car.png")
		self.arrow_left = image.load("res/arrow_left.png")
		self.carImageSized = transform.scale(self.carImage, (150, 100))
		self.carX, self.carY = 437,290
		self.width = self.carImageSized.get_width()
		self.height = self.carImageSized.get_height()
		self.logo = image.load("res/logo_perspective.png")
		self.running = True
		self.rightMenu = image.load("res/menu_right.png")
		self.rightMenuX, self.rightMenuY = 1024, 768
		self.menuFont = font.Font("res/fonts/pricedown.ttf", 35)
		#menu options with color, rects, text, and action on click
		self.optionColors = [(255,255,255),(255,255,255),(255,255,255),(255,255,255),(255,255,255)]
		self.optionRects = [Rect(825,455,self.menuFont.size("Start Game")[0]+10,self.menuFont.size("Start Game")[1]),Rect(825,505,self.menuFont.size("Store")[0]+10,self.menuFont.size("Store")[1]),Rect(825,555,self.menuFont.size("Options")[0]+10,self.menuFont.size("Options")[1]),Rect(825,605,self.menuFont.size("Help")[0]+10,self.menuFont.size("Help")[1]),Rect(825,655,self.menuFont.size("About")[0]+10,self.menuFont.size("About")[1])]
		self.options = ["Start Game", "Store", "Help", "About"]
		self.optionResults = [self.levelRunning,self.storeRunning,self.setHelp,self.setAbout]
		self.store = Store(surface)
		self.level = Level(surface)
		self.about = Popup(surface, "About", ["Developed By Rikin Katyal", "ICS3U Final Project 2015", "Made Using Python and Pygame"])
		self.help = Popup(surface, "Help", ["Use arrow keys or WASD to move.", "Press Space for emergency break.", "Earn coins to spend in the store.", "Drive through obstacles and park", "in marked parking spot."])
		self.help.images([image.load("res/arrows.png"), image.load("res/wasd.png"), image.load("res/coin_medium.png")],[(310,456),(470,450),(660,475)])
		self.settings = Popup(surface, "Settings", ["Sound Effects (SFX)", "Music"])
		self.aboutRunning = False
		self.helpRunning = False
		self.settingsRunning = False

	def render(self, down):
		"Main function to render menu"
		mx, my = mouse.get_pos()
		mb = mouse.get_pressed()
		self.pressed = key.get_pressed()
		# blit menu if not store adn not level
		if not self.store.isRunning() and not self.level.isRunning():
			self.surface.blit(self.bg, (0,0))
			self.width += 16
			self.height += 12
			self.carY += 6
			self.carX -= 8
			self.carImageSized = transform.scale(self.carImage, (self.width, self.height))
			#blit logo and move car down road
			if self.carY > 320:
				self.surface.blit(self.logo, (512-100,380))
			if self.carY < 768:
				self.surface.blit(self.carImageSized, (self.carX, self.carY))
			else:
				self.surface.blit(self.rightMenu, (self.rightMenuX, self.rightMenuY))
				if self.rightMenuX >= 590:
					self.rightMenuX -= 30
				if self.rightMenuY >= 350:
					self.rightMenuY -= 30
				if self.rightMenuX <= 590 and self.rightMenuY <= 350:
					for r in range(len(self.options)):
						# draw.rect(self.surface, (255,255,0), self.optionRects[r])
						if self.optionRects[r].collidepoint((mx,my)) and not self.aboutRunning and not self.helpRunning:
							self.optionColors[r] = (0,0,0)
							if mb[0]:
								self.optionResults[r]()
						else:
							self.optionColors[r] = (255,255,255)
						self.surface.blit(self.menuFont.render(self.options[r], 1, self.optionColors[r]), (830, 450+(r*50)))
		#blit store instead of menu
		elif self.store.isRunning():
			self.store.render(down)
		#blit level screen instead of menu
		elif self.level.isRunning():
			self.level.render()
		#if level is chosen, end menu screen
		if self.level.choseLevel:
			self.running = False
		#about popup
		if self.aboutRunning:
			self.about.render()
			self.aboutRunning = self.about.isRunning()
		#help popup
		elif self.helpRunning:
			self.help.render()
			self.helpRunning = self.help.isRunning()

	def isRunning(self):
		"Check if menu is running"
		return self.running

	def notRunning(self):
		"Stop running menu"
		self.running = False

	def storeRunning(self):
		"Check if store is running"
		self.store.running = True

	def levelRunning(self):
		"Check if level screen is running"
		self.level.running = True

	def setAbout(self):
		"Start about popup"
		self.aboutRunning = True

	def setHelp(self):
		"Start help popup"
		self.helpRunning = True
Example #28
0
class Game:
    


    #def __init__(self, screen, num_b, row_num_b, b_distance):
        #         # TODO
    def __init__(self, level, screen):
        self.level = Level(level)
        self.walls = WallController()
        self.balls = []
        self.balls.append(BallController())
        self.bat = BatController()

        self.balls[0].stickTo(self.bat)

        self.screen = screen


        self.allSpriteList = None
        self.refreshAllSpriteList()
        self.initWalls()
        self.bat.setWalls(self.walls)
        self.lives = 3
        self.won = False

    # load level from file
    def loadLevel(self, level):
        # TODO
        pass

    def refreshAllSpriteList(self):
        self.allSpriteList = pygame.sprite.Group()
        for brickController in self.level.getBricks():
            if brickController is not None:
                self.allSpriteList.add(brickController.brickView)
        for ballController in self.balls:
            self.allSpriteList.add(ballController.ballView)
        for wallView in self.walls.wallViews:
            self.allSpriteList.add(wallView)
        self.allSpriteList.add(self.bat.batView)

    def looseLife(self):
        self.lives -= 1

    def initWalls(self):
        walls = [[Constants.Border, Constants.Border, Constants.Game_Screen_W + 2 * Constants.Wall_width,
                  Constants.Wall_width],
                 [Constants.Border, Constants.Border, Constants.Wall_width,
                  Constants.Game_Screen_H + 2 * Constants.Wall_width],
                 [Constants.Border, Constants.Game_Screen_H + Constants.Wall_width + Constants.Border,
                  Constants.Game_Screen_W + 2 * Constants.Wall_width,
                  Constants.Wall_width],
                 [Constants.Game_Screen_W + Constants.Wall_width + Constants.Border, Constants.Border,
                  Constants.Wall_width,
                  Constants.Game_Screen_H + 2 * Constants.Wall_width]]

        for item in walls:
            self.walls.addWall(item[0], item[1], item[2], item[3])

    # the actual game-mechanism
    def start(self):
        # TODO
        
        pygame.display.set_caption('Wall-Breaker')
        clock=pygame.time.Clock()
        
        #----TEXTS----
        font = pygame.font.Font(None, 25)
        #text_score = font.render("Score: ", True, self.Black)
        text_level = font.render("Level: " + str(self.level.levelNumber), True, Constants.Black)
        text_lives = font.render("Lives: ", True, Constants.Black)
        
        
        #----WINDOW----
        gameExit=False
        while not gameExit and self.lives > 0 and not self.won:
            start = time.time()
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    gameExit=True
                
                self.bat.move(event)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
                    for ball in self.balls:
                        ball.release()
            for ball in self.balls:
                ball.move(self.level, self.walls, self.bat)
                self.level.deleteBrokenBricks()
                self.won = self.level.isReady()
                if not ball.isOnPlayField():
                    ball.stickTo(self.bat)
                    self.looseLife()
            end = time.time()
            #print("Counting time: " + str(end - start))
            start = time.time()
            self.refreshAllSpriteList()
            end = time.time()
            #print("Refresh time: " + str(end - start))
            start = time.time()
            self.allSpriteList.update()
            end = time.time()
            #print("Update time: " + str(end - start))
            start = time.time()
            self.screen.fill(Constants.White)

            self.allSpriteList.draw(self.screen)

            #self.Screen.blit(text_score, [700,150])
            self.screen.blit(text_level, [700, 150])

            text_lives = font.render("Lives: " + str(self.lives), True, Constants.Black)
            self.screen.blit(text_lives, [700, 250])
            end = time.time()
            #print("Draw time: " + str(end - start))
            pygame.display.update()

            clock.tick(15)
        if gameExit:
            pygame.quit()
            quit()
        else:
            return self.won
Example #29
0
    player1.keyDown(key)





##play method that 
play_endless = False
while play_endless == False:
    try:
      menu = Menu()
      break
    except TypeError:


        level = Level(1)
        if level.getLevel() == 1:
            mixer.music.load("All Star 8 Bit.mp3")
            mixer.music.play(-1)
        elif level.getLevel() == 1.5:
            mixer.music.load("harder_better_faster_stronger.mp3")
            mixer.music.play(-1)
        elif level.getLevel() == 2:
            mixer.music.load("Thriller (8 Bit).mp3")
            mixer.music.play(-1)


        frame = simplegui.create_frame('Half-Life 3', 500, 700)
        frame.set_draw_handler(draw)
        frame.set_keyup_handler(keyUp)
        frame.set_keydown_handler(keyDown)
Example #30
0
from Treasure import *
from Player import *
from Level import *

# the current_level variable will all store the level the
# player currently is at
current_level = Level()
level_list = [current_level]



my_player = Player(current_level)

current_level.print_level(my_player)

# main loop
ongoing_game = True
while ongoing_game:

    user_input = input("enter command: ")

    #  get user command
    if user_input == "h" or user_input == "j" or\
       user_input == "k" or user_input == "l":
        # if grid square to the left is within bounds
        result = my_player.move(user_input)

    current_level.print_level(my_player)


while True:
    levelsLeft = ["11", "12", "13",
                  "21", "22", "23",
                  "31", "32", "33"]
    
    deadGhosts = {}
    
    files = os.listdir("Levels/")
    for f in files:
        if f[-4:] == ".sav":
            os.remove("Levels/"+f)
    lx = 1
    ly = 1
    level = Level("Levels/Map"+str(lx)+str(ly))
    
    player = Manpac([7,7], (602,602))
    
    score = Score("Score: ", 0, (125,25))
    lives = Score("Lives: ", 5,  (125,675)) 
    while lives.score >= 5 and len(levelsLeft)>0: 
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player.go("up")
                elif event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player.go("down")
                elif event.key == pygame.K_a or event.key == pygame.K_LEFT:
Example #32
0
    def redrawAll(self, screen):
        #congrats, stars, score, buttons
        screen.blit(self.background, [-150, 0])
        self.mouse = pygame.mouse.get_pos()
        self.click = pygame.mouse.get_pressed()

        self.congrat = self.myFont.render("Congratulations!", True,
                                          (255, 204, 102))
        self.screen.blit(self.congrat, (50, 100))

        if self.starNum == 1:
            screen.blit(self.star, [100, 200])
            screen.blit(self.starOutline, [240, 180])
            screen.blit(self.starOutline, [400, 180])
        elif self.starNum == 2:
            screen.blit(self.star, [100, 200])
            screen.blit(self.star, [260, 200])
            screen.blit(self.starOutline, [400, 180])
        else:
            screen.blit(self.star, [100, 200])
            screen.blit(self.star, [260, 200])
            screen.blit(self.star, [420, 200])

        self.scoreStr = self.myFont2.render("Score:", True, (255, 204, 102))
        self.scoreNum = self.myFont2.render(str(self.score), True,
                                            (255, 204, 102))
        self.screen.blit(self.scoreStr, (200, 380))
        self.screen.blit(self.scoreNum, (420, 380))

        if 265 > self.mouse[0] > 140 and 580 > self.mouse[1] > 540:
            #pygame.draw.rect(self.screen,(153,153,255),(90,580,190,60))
            self.big = pygame.font.Font("PG_Roof Runners_active_bold-it.ttf",
                                        40)
            self.quit = self.big.render("Quit", True, (255, 204, 102))
            self.screen.blit(self.quit, (130, 550))
            if self.click[0] == 1:
                pygame.display.quit()
        else:
            #pygame.draw.rect(self.screen,(0,102,204),(90,580,190,60))
            self.big = pygame.font.Font("PG_Roof Runners_active_bold-it.ttf",
                                        30)
            self.quit = self.big.render("Quit", True, (255, 204, 102))
            self.screen.blit(self.quit, (140, 550))

        if 600 > self.mouse[0] > 390 and 580 > self.mouse[1] > 540:
            #pygame.draw.rect(self.screen,(153,153,255),(90,580,190,60))
            self.big = pygame.font.Font("PG_Roof Runners_active_bold-it.ttf",
                                        40)
            self.again = self.big.render("Play Again", True, (255, 204, 102))
            self.screen.blit(self.again, (400, 550))
            if self.click[0] == 1:
                Level.Levels().run()
        else:
            #pygame.draw.rect(self.screen,(0,102,204),(90,580,190,60))
            self.big = pygame.font.Font("PG_Roof Runners_active_bold-it.ttf",
                                        30)
            self.again = self.big.render("Play Again", True, (255, 204, 102))
            self.screen.blit(self.again, (410, 550))

        Struct.score = 0


#Win().run()
Example #33
0
clock = pygame.time.Clock()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,120,0)

background = pygame.image.load("Assets/bck.png")

screenWidth = 800
screenHeight = 600
fps = 60

gameDisplay = pygame.display.set_mode((screenWidth,screenHeight))

levelobj = Level(0)
brickList = []
level = levelobj.level_design()

for y in range(len(level)):
	for x in range(len(level[y])):
		if (level[y][x] == 1):
			brickList.append(Brick(x*32,y*32,(205,155,100)))
			
for brick in brickList:
	brick.render(gameDisplay)

def game_intr():
	game = message()
	intro = True 
	while intro:
Example #34
0
import sys
from Level import *


pygame.init()
TICKER = pygame.time.Clock()
# GLOBAL VARS
WINDOW_HEIGHT = 600
WINDOW_WIDTH = 800
DISPLAY_SURFACE = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
level = Level()

# initiating stuff
pygame.display.set_caption("Tiles")
DISPLAY_SURFACE.fill((0xFF, 0xFF, 0xFF))
level.generate_level()


# MAIN LOOP
while True:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key in level.ALLOWED_KEYS:
                level.press_key(event.key)
        elif event.type == QUIT:
            pygame.quit()
            sys.exit()
    level.draw_level(DISPLAY_SURFACE)
    pygame.display.update()
    TICKER.tick(30)
Example #35
0
             redrawSoundButton()
             menu.soundOnOff = -menu.soundOnOff
     if event.type == pygame.KEYDOWN:
         print pauseMenuButton
         if event.key == pygame.K_ESCAPE and pauseMenuButton == False:
             pauseMenuButton = True
             print "Pause"
         elif event.key == pygame.K_ESCAPE and pauseMenuButton == True:
             pauseMenuButton = False
             justPaused = True
             print "Resume"
     if startButtonClicked == True and pauseMenuButton == True:
         #Pause Menu Code
         pass
 if pauseMenuButton == False:
     Level.drawLevelOne()
     if spawning:
         waves.startWave()
         for i in range(len(Entity.minions)):
             enemy_spawner = Entity.Spawner(Entity.minions, Level.spawn_dict[1])
             print "calling spawn"
         spawning = False
     if spawning == False:
         if len([enemy for enemy in Entity.minions if enemy.isAlive == True]) == 0:
             spawning = True
     enemy_spawner.spawn(Entity.minions, screen)
     for i in range(len(Entity.minions)):
         if Entity.minions[i].isActive:
             Entity.minions[i].update()
             Entity.minions[i].draw(screen)
         
def initiateLevel(screen, levelPath, character):
    screen_rect = screen.get_rect()
    level = Level(levelPath, character)

    splashscreen(screen, level.splashscreenImg, (0, 0, 1024, 600))
    playGame(screen, level)