def saveTournament(self):#{{{
		if (self.checkUID()):
			self.tournamentsDB = myZODB.MyZODB(self.dbpath)
			self.tournaments = self.tournamentsDB.dbroot
			self.tournaments[self.uid] = tournament.Tournament(self.name, self.uid)
			#### Stworzenie turnieju! musi byc przed odwolywaniem do zmiennych! ####
			transaction.commit() 
			self.tournamentsDB.close()

			### Sortowanie graczy ###
			self.playersdb = myZODB.MyZODB(self.tournaments[self.uid].playersDB)
			self.players = self.playersdb.dbroot
			if (self.random == False):
				self.tmp = {}
				for key in self.players.keys():
					self.tmp[key] = self.players[key].rank
				self.tmp = sorted(self.tmp, key=self.tmp.get)
			else:
				self.tmp = copy.copy(self.players.keys())
				random.shuffle(self.tmp)
			import math
			i=0
			while math.ceil(math.log(len(self.tmp),2))!=math.log(len(self.tmp),2):
				self.tmp[i]=player(BYE,"",0,"",9999)
				i=i+1
			self.playersdb.close()
			self.tournaments[self.uid].playerList = self.tmp
			self.tournaments[self.uid].courts = copy.copy(self.courts)
			self.tournaments[self.uid].createMatchList()
			#### Sprawdzajace zapis ###
			print "Name: %s, uid: %s " % (self.tournaments[self.uid].name, self.tournaments[self.uid].uid)
			print "Hasze posortowanych graczy: ", self.tournaments[self.uid].playerList
			print "Hasze kortow: ", self.tournaments[self.uid].courts
			self.deleteLater() ## ZAMKNIECIE OKNA#}}}
    def createPlayer(self, position = vector):
        newPlayer = player(position, self.playerCount)
        self.activePlayers.append(newPlayer)
        self.playerCount += 1
        if len(self.activePlayers) == 1:
            self.active = self.activePlayers[0]

        return newPlayer
Exemple #3
0
    def play(self,instance): 
        if self.player == None:
            self.player = player()
            self.player.play(self.ndr2)
        elif self.player.name == "NDR2":
            self.player.play(self.jimi)
##       elif self.player.name == "Jimi Hendrix":
##            self.player.off()
##            self.player.name = ""
        else:
            sys.exit(0)
def startGame(wj1,wj2,op1,op2,op3):
    paidui = PD()
    PAI = PAI_def(paidui)
    jineng = JINENG(PAI,paidui)
    P1 = player(wj1,paidui,jineng,PAI,op1,op3)
    P2 = player(wj2,paidui,jineng,PAI,op2,op3)
    P1.init_adv(P2)
    while 1:
        if P1.alive and P2.alive:
            P1.newround()
        else:
            break
        if P1.alive and P2.alive:
            P2.newround()
        else:
            break

    if P1.alive:
        winner = P1.name
        out=1
    else:
        winner = P2.name
        out=0
    X=[]
    Y=[]
    if op3:
        p1target = [out]*len(P1.tobewritten)
        p2target = [int(not out)]*len(P2.tobewritten)
##    for i in P1.tobewritten:
##        i.append(out)
##    for i in P2.tobewritten:
##        i.append(int(not out))
        X = P1.tobewritten+P2.tobewritten
        Y = p1target+p2target
    #f1 = open("save.p",'w')
    #cPickle.dump(L, f1)
        
    #f1.close()
    print '游戏结束\n获胜的玩家是'+winner
    return out,X,Y
Exemple #5
0
    def new_game(self, players):
        shuffle(players)
        self.cards = self.generate_cards()
        self.players = []

        for i, player in enumerate(players):
            player_cards = []
            for j, hand in enumerate(self.cards):
                if i != j:
                    player_cards.append([("x", card[1]) for card in self.cards[j]])
                else:
                    player_cards.append(list(self.cards[j]))
            self.players.append(player(i, player_cards))
    def __init__(self, M, N):
        self.N = N
        self.M = M

        # Pygame settings
        pygame.init()
        (self.cw, self.ch) = (30, 30)
        self.space_h = 5
        self.scr = pygame.display.set_mode((self.cw * (N), self.ch * (M + 1)))
        self.clock = pygame.time.Clock()
        self.P = player(self, (self.M - 1, 1), "P")
        self.set_game()
        self.status = "New Game. Press C to start"
        self.listen()
Exemple #7
0
    def ready(self):
        # 1. distribute players
        for i in range(self.players):
            self.player_group.append(player(i))

        # api laissant pour le département commercial
        # free to play
        # self.player_group[0].de = de([1,2,3])
        # user payé
        # self.player_group[0].de = de([1,2,3,4,5,6])
        # user premium mensuel
        # self.player_group[0].de = de([6,6,6,6,6,6])
        # user premium annuel
        # self.player_group[0].de = de([7,7,7,7,7,7])

        # 2. lancer le jeu
        print("le jeu se commence ! il y a " + str(self.players) + " players")
        print("le joueur qui gagne " + str(self.score_plus_haut) + " gagne")
def main():
	import os
	from time import sleep
	from random import randint
	plr=player()
	while True:
		fl=0
		plr.checkdeath()
		plr.initpos()
		brd=board()
		don=donkey()
		b1=[ball(don)]
		brd.printboard(plr,don,b1)
		while True:
			plr.checkqueen()
			fl=plr.checkdonkey(don,fl)
			if fl==1:
				break
			fl=plr.checkball(b1,fl)
			if fl==1:
				break
			if randint(0,randint(3,6))==1:
				b1+=[ball(don)]
			plr=player.checkfall(plr,brd,don,b1)
			mv=getchar()
			if mv==' ':
				plr=plr.jump(brd,don,b1)
			else:
				plr=plr.getdir(mv)
				plr=plr.move(plr,brd,0,mv)
			for i in b1:
				i=i.move(brd)
			don=don.move(brd)
			brd.printboard(plr,don,b1)
		if fl==1:
			continue	
Exemple #9
0
 def test_add_point(self):
     player0 = player(0)
     score_origin = player0.get_point()
     player0.add_point(10)
     score_now = player0.get_point()
     self.assertEqual(10, score_now - score_origin)
Exemple #10
0
def game_loop():
	global is_god, intro, selecting, GG, side_shooting, score, intro, ultima_cadeira, aluno, user,\
	bullets, bulletSprites, obstacleGroup, cadeira, pause, shooting, obstacle_speed, time_change, pos_change,\
	power_up_change, powers

	intro = False
	selecting = False
	colliding = False
	collide_change = False
	just_dead = False
	pos_change = 0
	shooting = True
	shoot_time = 800
	color_change = black
	obstacle_speed = 3
	speed_change = 0.05
	time_change = 0
	score_string = ""
	name_string = ""

	shoot_sound.set_volume(0.4)

	if is_god:
		game_sound.stop()
		god_sound.play(soundtrack_2)

	aluno = pygame.sprite.GroupSingle(player())
	user = (aluno.sprites())[0]
	bullets = []
	bulletSprites =pygame.sprite.Group()
	obstacleGroup = pygame.sprite.Group()
	powers = pygame.sprite.Group()
	cadeira = [obstacle(random.choice(cadeiras_ref), obstacle_speed, user.slow_time())]
	obstacleGroup.add(cadeira)

	pygame.time.set_timer(USEREVENT + 1, random.randint(1000 - time_change, 1500 - time_change))
	power_up_change = random.randint(5, 9)

	while True:
		pygame.display.update()

		if not pygame.mixer.get_busy():
			if is_god:
				god_sound.play(soundtrack_2)
			else:
				game_sound.play(soundtrack)

		#obtem a posicao do aluno
		for i in aluno:
			aluno_pos = i.pos()

		#criacao de cronometros
		if user.score_change() != 1:
			pygame.time.set_timer(USEREVENT + 5, 7000)

		#EVENTOS
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				quit()

			#eventos do cronometro
			if event.type == USEREVENT + 1:
				cadeira = [obstacle(random.choice(cadeiras_ref), obstacle_speed, user.slow_time())]
				obstacleGroup.add(cadeira)

				if not is_god:
					if power_up_change <= 0:
						power_up_change = random.randint(5, 9)
						power = [power_up(random.randint(1, 4), obstacle_speed)]
						powers.add(power)

				pygame.time.set_timer(USEREVENT + 1, random.randint(1000-time_change, 1500-time_change))

			if event.type == USEREVENT + 2:
				pygame.time.set_timer(USEREVENT + 2, 0)
				shooting = True

			if event.type == USEREVENT + 3:
				pygame.time.set_timer(USEREVENT + 3, 0)
				color_change = black
				if is_god:
					god_sound.unpause()
				else:
					game_sound.unpause()

			if event.type == USEREVENT + 4:
				pygame.time.set_timer(USEREVENT + 4, 0)
				user.end_slow()
				for obstaculo in obstacleGroup:
					obstaculo.speed_change(obstaculo.speed*2)

			if event.type == USEREVENT + 5:
				pygame.time.set_timer(USEREVENT + 5, 0)
				user.end_score()

			if event.type == USEREVENT + 6:
				pygame.time.set_timer(USEREVENT + 6, 0)
				event_6 = False
				side_shooting = False

			if event.type == pygame.KEYDOWN:

				#move o jogador
				if event.key == pygame.K_a:
					pos_change -= 1
				if event.key == pygame.K_d:
					pos_change += 1

				if event.key == pygame.K_p:
					pause = True
					paused()

				#move as balas
				if event.key == pygame.K_UP:
					if not is_god:
						if shooting:
							shoot_sound.play(shoot)
							pygame.time.set_timer(USEREVENT + 2, shoot_time)
							shooting = False
							bulletA = [bullet(aluno_pos[0], 2)]
							bullets+=bulletA
							bulletSprites.add(bulletA[0])
					else:
						bulletA = [bullet(aluno_pos[0], 2)]
						bullets+=bulletA
						bulletSprites.add(bulletA[0])

				if event.key == pygame.K_LEFT and side_shooting:
					if not is_god:
						if shooting:
							shoot_sound.play(shoot)
							pygame.time.set_timer(USEREVENT + 2, shoot_time)
							shooting = False
							bulletA = [bullet(aluno_pos[0], 1)]
							bullets+=bulletA
							bulletSprites.add(bulletA[0])
					else:
						bulletA = [bullet(aluno_pos[0], 1)]
						bullets+=bulletA
						bulletSprites.add(bulletA[0])

				if event.key == pygame.K_RIGHT and side_shooting:
					if not is_god:
						if shooting:
							shoot_sound.play(shoot)
							pygame.time.set_timer(USEREVENT + 2, shoot_time)
							shooting = False
							bulletA = [bullet(aluno_pos[0], 3)]
							bullets+=bulletA
							bulletSprites.add(bulletA[0])
					else:
						bulletA = [bullet(aluno_pos[0], 3)]
						bullets+=bulletA
						bulletSprites.add(bulletA[0])

			if event.type == pygame.KEYUP:
				if event.key == pygame.K_a:
					pos_change += 1
				elif event.key == pygame.K_d:
					pos_change -= 1

		gameDisplay.blit(game_background, (0, 0))

		obstacleGroup.draw(gameDisplay)
		obstacleGroup.update()

		powers.draw(gameDisplay)
		powers.update()

		aluno.draw(gameDisplay)
		aluno.update(pos_change)

		if just_dead:
			just_dead = False

		#detecao de colisoes (obstaculo)
		for obstaculo in obstacleGroup:

			#colisao com o jogador
			if pygame.sprite.collide_rect(user, obstaculo):
				if obstaculo.dif() != 0:
					if user.shield() >= 1:
						score += 5 * user.score_change()
						obstacleGroup.remove(obstaculo)
						user.end_shield()
					else:
						colliding = True

				if is_god:
					score += 20
					obstacleGroup.remove(obstaculo)					

				else:
					if user.is_dead():
						user.update_hp(3)
						ultima_cadeira = obstaculo.nome()
						if is_god:
							god_sound.pause()
						else:
							game_sound.pause()
						death_sound.play(death)
						GG = True
						break

			#colisao com as balas
			if pygame.sprite.spritecollideany(obstaculo, bulletSprites):
				if obstaculo.dif() == 0:
					if is_god:
						score += 40
					else:
						score += 2 * user.score_change()
					pygame.sprite.groupcollide(obstacleGroup, bulletSprites, True, True)
					power_up_change -= 1
					if obstacle_speed <= 4.5:
						obstacle_speed += speed_change
					time_change += 25

				elif obstaculo.dif() == 1:
					if is_god:
						score += 80
					else:
						score += 5 * user.score_change()
					pygame.sprite.groupcollide(obstacleGroup, bulletSprites, True, True)
					power_up_change -= 1
					if obstacle_speed <= 4.5:
						obstacle_speed += speed_change
					time_change += 25

				elif obstaculo.dif() == 2:
					if is_god:
						power_up_change -= 1
						score += 150
						pygame.sprite.groupcollide(obstacleGroup, bulletSprites, True, True)
					else:
						score += 10 * user.score_change()
						pygame.sprite.groupcollide(obstacleGroup, bulletSprites, False, True)
					if obstacle_speed <= 4.5:
						obstacle_speed += speed_change
					time_change += 25

			#quando o jogador ultrapassa um obstaculo
			if obstaculo.pos()[1] > display_height + (obstaculo.height()):
				if obstacle_speed <= 4.5:
						obstacle_speed += speed_change
				power_up_change -= 1

				if obstaculo.dif() == 0:
					if not is_god:
						score -= 2
				elif obstaculo.dif() == 1:
					if not is_god:
						score -= 4
				obstacleGroup.remove(obstaculo)

		#detecao de colisoes (power_up)
		for power in powers:
			if pygame.sprite.spritecollideany(power, bulletSprites):
				pygame.sprite.groupcollide(powers, bulletSprites, True, True)
				power_up_change = random.randint(5, 9)

			if power.pos()[1] > display_height + (power.height()):
				powers.remove(power)
				power_up_change = random.randint(5, 9)

			if pygame.sprite.collide_rect(user, power):
				user.apply(power.type())
				power_up_change = random.randint(5, 9)

				if user.slow_time():
					for obstaculo in obstacleGroup:
						obstaculo.speed_change(obstaculo.speed/2)
					pygame.time.set_timer(USEREVENT + 4, 5000)

				if power.type() == 4:
					side_shooting = True
					pygame.time.set_timer(USEREVENT + 6, 10000)

				powers.remove(power)


		#quando o jogador e atingido por um obstaculo
		if colliding and not collide_change:
			collide_change = True
			if not is_god:
				user.update_hp(-1)
				if user.hp() != 0:
					gasp_sound.play(gasp)
					color_change = bright_red
			pygame.time.set_timer(USEREVENT + 3, 500)

		#mecanismo de tranca
		elif not colliding and collide_change:
			collide_change = False

		colliding = False

		#se o jogador perde
		if GG:
			just_dead = True
			#verifica se bateu o highscore
			table = open('highscore.txt','r')
			s = table.readline()
			i = -1
			while s[i].isdigit():
				score_string = s[i] + score_string
				i-=1
			
			i = 0
			while s[i] != "-":
				name_string += s[i]
				i+=1

			name_string = name_string[:-1]
			i = 0
			table.close

			if score > eval(score_string):
				deathscreen(score, name_string, score_string)
			else:
				crash()
				score_string = ""
				name_string = ""

		else:
			screen_text_center("ECT'S: " + str(score) , 700, 20, 20, black)
			screen_text_center("Paciencia: " +str(user.hp()) , 99, 19, 20, white)
			screen_text_center("Paciencia: " +str(user.hp()) , 100, 20, 20, color_change)
			power_up_display()

		#update
		bulletSprites.update()
		bulletSprites.draw(gameDisplay)
		obstacleGroup.update()
		clock.tick(60)
Exemple #11
0
from board import *
from wall import *
from bricks import *
from player import *
from bomb import *
from enemy import *
import sys, tty, termios, os

os.system("clear")
matrix = board()
matrix = matrix.getBoard()
matrix = wall(matrix)
matrix = matrix.make_wall()
matrix = bricks(matrix)
matrix = matrix.make_bricks()
player_obj = player()
matrix = player_obj.display_pos(matrix)
enemy_obj = enemy()
move_obj = enemy_obj.make_enemy(matrix)
bomb_obj = bomb()
lives = 3
score = 0
for i in range(38):
    for j in range(76):
        print(move_obj[i][j], end='')
    print('')
print("LIVES=" + str(lives))
print("SCORE=" + str(score))
bomb_plant = False
bomb_x = 0
bomb_y = 0
Exemple #12
0
from tkinter import *
from player import *
import random as r
from tkinter import messagebox
import numpy as np
user_1 = player()
user_2 = player()

user_1.name = "Player 1 - O"
user_2.name = "Player 2 - X"
user_1.symbole ="X"
user_2.symbole = "O"
user_1.enteries =[[0, 0, 0],[0,0, 0],[0,0, 0]]
user_2.enteries =[[0, 0, 0],[0,0, 0],[0,0, 0]]

#########

user_1.turn = r.choice([True , False])
user_2.turn = not(user_1.turn)


def turner(x,y):
    if user_1.turn:
        if not(user_1.enteries[x][y] or user_2.enteries[x][y]):
            user_1.enteries[x][y] = 1
            user_1.turn = user_2.turn
            user_2.turn = not(user_2.turn)
            disp.set("The Turn For:\n " +str(user_2.name))  
    else:
        if not(user_1.enteries[x][y] or user_2.enteries[x][y]):
            user_2.enteries[x][y] = 1
Exemple #13
0
def reset():
    global game_objects, player1
    game_objects = []
    player1 = player()
    game_objects.append(player1)
        print("")
        print(
            "*************************************************************************************"
        )
        print(
            "*                           Player 1 choisie un combatant                           *"
        )
        print(
            "*                        1. Mage 2. Vieille 3. Étudiant                             *"
        )
        print(
            "*************************************************************************************"
        )

        Player1 = player(
            1,
            int(input("Entrer le numero correspondant au combatant choisi.")))

        print("")
        print("Vous avez choisi:", Player1.name)
        print("")
        print("")
        print("")
        print(
            "*************************************************************************************"
        )
        print(
            "*                           Player 2 choisie un combatant                           *"
        )
        print(
            "*                        1. Mage 2. Vieille 3. Étudiant                             *"
Exemple #15
0
    'enemy_ct_boss': 25,
    'enemy_dmg': 8,
    'enemy_life_time': 6000,
    'enemy_spawn_time': 800,
    'player_health': 100,
    'death_penalty': 5,
    'num_injects': 2,
    'heal_amount': 35,
    'shield_amount': 2,
    'powerup_respawn': True,
    'boss_spawn': (5600, 2000),
    'player_spawn': (300, 8700)
}

#world and entities initialization
player_char = player((0, 0), player_images, sounds, difficulty)
level1 = Level(player_char, background, render_size, image_dict, difficulty)
player_HUD = HUD(screen, player_char, "Assets/health_bar1.png", powerup_img)

#win screen fade timer
fade_timer = 100
fade_ct = 40
win_screen_timer = 5000
no_win = True

#music for game
world_music = "Assets/Sounds/lightout.ogg"
boss_music = "Assets/Sounds/music(do not use).ogg"
boss_music_playing = False

#start music
Exemple #16
0
#THis python 2 program is meant to play a game of euchre, for reasons I can't understand

import random
from collections import Counter
from itertools import cycle
from round import *
from player import *
from misc import *

################################################################################

player1 = player('Liz')
player2 = player('Bingham')
player3 = player('Darcy')
player4 = player('Jane')
player1.toLeftOf = player4
player2.toLeftOf = player1
player3.toLeftOf = player2
player4.toLeftOf = player3
players = [player1, player2, player3, player4]
kitten = kitty()

player1.lead = True
player4.dealer = True

Team1Score = 0
Team2Score = 0

round1 = Round(players, kitten)
for i in range(10):
        round1.deal()
Exemple #17
0
pygame.display.update()

flag = 0
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            flag = 1
            break
    if flag:
        break
        pygame.display.update()

mapobj = maze_map(surface)
mapobj.show()

player_1 = player([13, 29], surface)

ghost1 = ghost([11, 13], surface, 0, color="red")
ghost2 = ghost([15, 13], surface, 1, color="blue")
ghost3 = ghost([14, 13], surface, 2, color="yellow")

draw((ghost1.coord), ghost1.ghost_colour)
draw((ghost2.coord), ghost2.ghost_colour)
draw((ghost3.coord), ghost3.ghost_colour)

pygame.display.flip()
clock = pygame.time.Clock()

GAME_FONT = pygame.font.SysFont('Comic Sans MS', 24)

with multiprocessing.Manager() as manager:
Exemple #18
0
    def czolgi(self):#właściwa gra
        if self.start:
            self.map.reload()
            self.nab=[]
            self.gracze=[]
            for x in range(0,len(self.map.gracze)):
                pl=player(self.map.gracze[x][0],
                self.map.gracze[x][1],  20,  20,
                self.ini.read("gracz"+str(x+1),"up"),
                self.ini.read("gracz"+str(x+1),"down"),
                self.ini.read("gracz"+str(x+1),"left"),
                self.ini.read("gracz"+str(x+1),"right"),
                self.ini.read("gracz"+str(x+1),"speed"),
                self.ini.read("gracz"+str(x+1),"shoot"),
                self.ini.read("gracz"+str(x+1),"color"), 
                self.ini.read("gracz"+str(x+1),"ppx"),
                self.ini.read("gracz"+str(x+1),"ppy"),  x+1)
                self.gracze.append(pl)
            self.anim=self.lec=self.jezd=pygame.time.get_ticks()
            self.start=0
        
        self.map.rysuj()
        self.bufor.blit(self.map.bm,(0,0))
        pygame.draw.rect(self.bufor, (200,200,200),(self.e_w,0,self.a_w,self.a_h))
                
        atim=pygame.time.get_ticks()
        while self.lec<atim or self.jezd<atim or self.anim<atim:#pętla timerów
            if self.lec<atim:#timer do kul
                t=0
                tlen=len(self.nab)
                while t<tlen:
                        if self.nab[t].jezdz(self):
                            self.nab.pop(t)
                            t-=1
                            tlen-=1
                        t+=1
                self.lec+=4            

            if self.jezd<atim:#timer do jazdy
                t=0
                tlen=len(self.gracze)
                while t<tlen:
                    self.gracze[t].jezdz(self)
                    t+=1
                self.jezd+=7
                
            if self.anim<atim:#timer do objektów mapy
                self.map.jezdz(self)
                self.anim+=10
                
            atim=pygame.time.get_ticks()

        t=0
        tlen=len(self.gracze)
        while t<tlen:
            self.gracze[t].rysuj(self)
            t+=1
        t=0
        tlen=len(self.nab)
        while t<tlen:
            self.nab[t].rysuj(self)
            t+=1
 
        if len(self.gracze)<=1:
            self.start=1
            self._wait(2, "Wygral gracz "+str(self.gracze[0].name))
Exemple #19
0
 def ringAlarm(self): 
     if self.player == None:
         self.player = player()
     self.player.play(self.ndr2)
Exemple #20
0
import re
from deck import *
from player import *
from computerplayer import *
from pokerdecisions import *

plName = raw_input("Please enter your name:")

numAI = input("Please enter the number of computer players:")

while True:
    #Creating each round because this is proof of concept
    #would do something else for final project.
    gamepl = player(plName)
    aiPlayers = []
    for i in range(int(numAI)):
        aiPlayers.append(computerPlayer())

    ourDeck = deck()
    ourDeck.shuffle()

    for i in range(5):
        gamepl.addCard(ourDeck.deal())
        for i in aiPlayers:
            i.addCard(ourDeck.deal())

    gamepl.sortHand()
    for i in aiPlayers:
        i.sortHand()

    check = True
Exemple #21
0
            self.light_walls = light_walls
            self.radius = radius
            self.fovmap = libtcod.map_new(width, height)
      
    def setRadius(self,r):
		self.radius = radius



'''
Declaration of base variables
'''
curTurn = 0         # the current turn
minTurn = 0         # minimum number of turns to next iteration of game loop

player = player()   # the player character

orc = creatures.Orc(10,10)
bat = creatures.Bat(15,15)
bat2 = creatures.Bat(8,8)
actors = [player,orc,bat,bat2]  # player is not in the list of actors, but is always a relevant actor
lights = []

testlight = entities.Light(37,7,50,10)
lights.append(testlight)
testlight2 = entities.Light(9,10,1,10)
lights.append(testlight2)

gamemap = Map.Map()

myfov = fov(gamemap.width,gamemap.height)
Exemple #22
0
 def setup_players(self):
     you = player()
     other = comp()
     self.players = [you, other]
Exemple #23
0
#create a temporary variable to hold and compare highscore
temp = highscore

#open file to write highscore
fileO = open("highscore.txt","w")

#create highscore label in bottom left
highLabel = label(pos=(-350,-350,0), text='Highscore: %d' % temp, box = False)

#create ball
b1=bird()

#create pipe obstacles
obs1=obstacle(sceneRange)
obs2=obstacle(sceneRange*2)
#obs2=cylinder(pos=(150,-150,0),axis=(0,150,0),radius=75/2,color=color.green)
    
#create obstacle velocity constants
dt=.01
Vx=25

#create player and draw score
p1=player()

#draw the start game prompt label
startLabel = label(pos=(0,0,0),text='Press Enter to start!')



Exemple #24
0
#Define Global Variables
index = [0.8, 0.5, 0.3]  # usage of attribute
levelup = False

from player import *

# def update(self):
# Load all game graphics
# menu = pg.image.load('menu.png')
# menu_rect = menu.get_rect()

races = random.choice(["orc", 'human', 'elf'])

all_sprites = pg.sprite.Group()
player = player(race="orc")
all_sprites.add(player)
monsters = pygame.sprite.Group()
for i in range(0, 8, 1):
    monster1 = monster()
    monsters.add(monster1)
    print(monster1.x, monster1.y)

# Game Loop
running = True
startmenu.main()
while running:
    #keep loop running at the same speed
    clock.tick(FPS)
    # Process input (events)
    if player.x == monster1.x and player.y == monster1.y:
	def setUp (self) :
		""" setup for the tests to run"""
		self.player = player("Bob", "X")
Exemple #26
0
 def createPlayer(self):
     self.bots[2].append(player(randint(100, 900), randint(100, 700), self))
Exemple #27
0
import pygame
from settings import *
from player import *
from board import *
from ghost import *
import random

pygame.init()

pygame.display.update()
clock = pygame.time.Clock()

pacman = player()
brd = board()
ghosts = []
ghosts.append(reda())
ghosts.append(yellowa())
ghosts.append(bluea())
ghosts.append(pinka())

total = len(brd.rect)
score = 0

start_time = pygame.time.get_ticks()

while True:

    x_change = 0
    y_change = 0

    screen.fill(black)
Exemple #28
0
# name placeholder (if someone accesses /game directly)
name = "Tiger Woods"
winner = ""

# possible actions for player as dict
actions = {
    "card": False,
    "hold": False,
    "double": False,
}

# list of chips to be displayed
chips_display = []

user = player()
dealer = dealer()
deck = carddeck()


@app.route("/", methods=["GET", "POST"])
# starting application / opening page
def index():
    # start game and get name & chips amount
    if request.method == "POST":
        # modifiy global variables and redirect to the game
        global name, chips
        name = request.form.get("name")
        chips = float(request.form.get("chips"))
        return redirect("/game")
    else:
def game():



    #Functions

    def add(obj):
        allSpritesGroup.add(obj)
        allSpritesList.append(obj)


    def screenAssign():

        for i in range(0,len(allSpritesList)):

            if allSpritesList[i].onScreenCheck() and onScreenGroup.has(allSpritesList[i]) == False:
                onScreenGroup.add(allSpritesList[i])
                offScreenGroup.remove(allSpritesList[i])
            elif allSpritesList[i].onScreenCheck() == False and offScreenGroup.has(allSpritesList[i]) == False:
                offScreenGroup.add(allSpritesList[i])
                onScreenGroup.remove(allSpritesList[i])


    def loadLevel(x):
        
        f =  open("Levels\level_"+ str(x) + ".txt","r")

        loadType = ""

        platformCoordinates = []
        wallCoordinates = []
        enemyCoordinates = []

        platformList = []
        wallList = []
        enemyList = []
        
        for inp in f:
            
            if inp == "Platforms\n":
                loadType = "platform"
                                
            elif inp == "Walls\n":
                loadType = "wall"

            elif inp == "Enemies\n":
                loadType = "enemy"

            elif inp != "\n":
                #coordinate parsing
                spaceInd = inp.find(" ")
                newLineInd = inp.find("\n")
                
                xlen = spaceInd

                xCoordinate = 0
                yCoordinate = 0

                for i in range(0, xlen):

                    if i != 0:
                        xCoordinate = xCoordinate*10
                    xCoordinate += int(inp[i])

                for i in range(spaceInd+1, newLineInd):

                    if i != 0:
                        yCoordinate = yCoordinate*10
                    yCoordinate += int(inp[i])

                if loadType == "platform":

                    platformCoordinates.append((xCoordinate,yCoordinate))
                    
                elif loadType == "wall":
                    
                    wallCoordinates.append((xCoordinate,yCoordinate))
                    
                elif loadType == "enemy":

                    enemyCoordinates.append((xCoordinate,yCoordinate))
                    

        for i in range(0, len(platformCoordinates)):
            platformList.append(gamePlatform(platformCoordinates[i][0],platformCoordinates[i][1],platform4Image))
            add(platformList[i])
        for i in range(0, len(wallCoordinates)):
            wallList.append(wall(wallCoordinates[i][0],wallCoordinates[i][1],wallImage))
            add(wallList[i])

        for i in range(0, len(enemyCoordinates)):
            enemyList.append(enemy(enemyCoordinates[i][0],enemyCoordinates[i][1],enemyImage))
            add(enemyList[i])


    #Sprite Group Declarations

    allSpritesGroup = pygame.sprite.Group()
    onScreenGroup = pygame.sprite.RenderUpdates()
    offScreenGroup = pygame.sprite.Group()

    #Sprite list

    allSpritesList = []
    bulletList = []

    ##FPS management
    fps = 60
    loop_delta = 1./fps
    current_time = target_time = time.clock()


    #Player declaration

    playerSpeed = 3

    bulletImage = pygame.image.load("Bullet & Sparks\Bullet.png")
    bulletImage = pygame.transform.scale(bulletImage,(10,8))
    
    playerImage = pygame.image.load("Characters\Guy with Gun.png")
    player1 = player(0,0,playerImage,bulletImage,(3,8))
    player1.resize(gameGlobals.playerWidth,gameGlobals.playerHeight)
    player1.gravity(True)

    onGround = False

    add(player1)

    #how far a bullet travels offscreen
    bulletBuffer = 1000

    #mouse cursor

    cursorImage = pygame.image.load("Bullet & Sparks\crosshair.png")
    cursor = mouseCursor(0,0,cursorImage)
    cursor.resize(50,50)

    pygame.mouse.set_visible(False)

    allSpritesGroup.add(cursor)
    onScreenGroup.add(cursor)


    #z
    #Moving player to centre
    #xOrig and yOrig in globals
    
    player1.move(gameGlobals.xOrig, gameGlobals.yOrig)

    #Images

    platform4Image = pygame.image.load("Platforms & Walls\platform4.png")

    enemyImage = pygame.image.load("Characters\Guy with Gun3.jpg")

    wallImage = pygame.image.load("Platforms & Walls\Wall3.jpg")
    wallImage = pygame.transform.scale(wallImage, (100,100))

    backgroundImage = pygame.image.load("Backgrounds\City.png")
    backgroundImage = pygame.transform.scale(backgroundImage, (gameGlobals.screenWidth, gameGlobals.screenHeight))
    
    screen.blit(backgroundImage,(0,0))

    screenAssign()
    
    pygame.display.update()



#=============================================================================    
#=============================================================================
    
    loadLevel(1)


#=============================================================================
#============================================================================= 

    
    while True:

        #Set current and previous time for FPS
        #All code should be between
        #the two fps management snippets
        previous_time, current_time = current_time, time.clock()


        #Pygame event management
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.display.quit()
                pygame.quit()
                sys.exit()

        #Player Input


        mousePos = mouseX, mouseY = pygame.mouse.get_pos()

        if (player1.direction == "left" and mouseX > player1.rect.x + player1.width) or (player1.direction == "right" and mouseX < player1.rect.x):
            player1.flip()

        if pygame.mouse.get_pressed()[0]:
            bulletList.append(player1.shoot())
            add(bulletList[len(bulletList)-1])
                
        keys = pygame.key.get_pressed()
        if keys[pygame.K_d]:
            player1.move(playerSpeed,0)
        if keys[pygame.K_a]:
            player1.move(-playerSpeed,0)
        if keys[pygame.K_SPACE] and onGround == True:
            player1.fallSpeed = -8


        

        
        #Draw section
        screen.blit(backgroundImage,(0,0))

        allSpritesGroup.update()

        deleteList = []
        onGround = False
        for i in range(0,len(allSpritesList)):
            if onScreenGroup.has(allSpritesList[i]):
                #Put Collision stuff here

                check = checkClass(allSpritesList[i])

                if check == "gamePlatform":

                    if pygame.sprite.collide_rect(player1, allSpritesList[i])and player1.y + player1.height - player1.fallSpeed - 5 <= allSpritesList[i].y and keys[pygame.K_s] != True :
                        player1.fallSpeed = 1
                        player1.y = allSpritesList[i].y - player1.height
                        onGround = True

                if check == "wall":

                    if pygame.sprite.collide_rect(player1, allSpritesList[i]):

                        if player1.fallSpeed < 0 and player1.y - player1.fallSpeed + 10 > allSpritesList[i].y + allSpritesList[i].height:
                            player1.y = allSpritesList[i].y + allSpritesList[i].height
                            player1.fallSpeed = 1
                        elif player1.fallSpeed > 0 and player1.y + player1.height - player1.fallSpeed - 10 < allSpritesList[i].y:
                            player1.y = allSpritesList[i].y - player1.height
                            player1.fallSpeed = 1
                            onGround = True

                        elif keys[pygame.K_d] and player1.x + player1.width - playerSpeed - 10 < allSpritesList[i].x:
                            player1.x = allSpritesList[i].x - player1.width
                        elif keys[pygame.K_a] and player1.x + playerSpeed + 10 > allSpritesList[i].x + allSpritesList[i].width:
                            player1.x = allSpritesList[i].x + allSpritesList[i].width

                if check == "bullet":
                    if allSpritesList[i].shooter != "player":
                        print("kill player")

        #Code to destroy collided bullet, enemies, etc.
        
        for i in range (0,len(deleteList)):
            del bullets[deleteList[i]-i]
        
        updateArea = onScreenGroup.draw(screen)

        screenAssign()

        pygame.display.update(updateArea)


        #FPS management
        target_time += loop_delta
        sleep_time = target_time - time.clock()
        if sleep_time < 0:
            sleep_time = 0
        time.sleep(sleep_time)
Exemple #30
0
 def setup_players(self):
     you=player()
     other=comp()
     self.players=[you,other]
Exemple #31
0
    def addPlayer(self, name, dealer="NULL", userRight=False):
        playerObj = player(name, dealer, userRight)
        self.playerDict[playerObj.name] = playerObj
        self.totalPlayers.append(playerObj)

        print ("Player '%s' is added to the game." % playerObj.name)
Exemple #32
0

def distance(x1, y1, x2, y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)


def offscreen(o):
    if o.__class__.__name__ == 'player':
        return False
    return o.x > window.width or o.x < 0 or o.y > window.height or o.y < 0


keys = {'up': False, 'down': False, 'right': False, 'left': False}

game_objects = []
player1 = player()

font.add_file('TulpenOne-Regular.ttf')

title = text.Label("Taking Sides",
                   font_name="Tulpen One",
                   x=100,
                   y=globals.window_height / 2,
                   font_size=85)
subtitle = text.Label("Press 'P' to play...",
                      font_name="Tulpen One",
                      x=106,
                      y=globals.window_height / 2 - 100,
                      font_size=38)

menuPolygon = polygon(5, None)
Exemple #33
0
def main(scr):
	status = curses.newwin(1, curses.COLS, 0, 0) 
	status.bkgd('0')
	status.refresh()

	curses.start_color()
	debug = curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
	green = curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_GREEN)
	black = curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLACK)
	blue = curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLUE)
	debug = curses.color_pair(1)
	green = curses.color_pair(2)
	black = curses.color_pair(3)
	blue = curses.color_pair(4)

	controlMapOne = {
		curses.KEY_UP:DIRECTION_UP, 
		curses.KEY_DOWN:DIRECTION_DOWN, 
		curses.KEY_LEFT:DIRECTION_LEFT, 
		curses.KEY_RIGHT:DIRECTION_RIGHT
	}
	controlMapTwo = {
		ord('w'):DIRECTION_UP,
		ord('s'):DIRECTION_DOWN,
		ord('a'):DIRECTION_LEFT,
		ord('d'):DIRECTION_RIGHT
	}

	curses.curs_set(False)
	scr.nodelay(True)

	tickDuration = 0.15
	playerOneCoord = player(29, 2, DIRECTION_UP)
	playerTwoCoord = player(29, 30, DIRECTION_UP)
	keypress = None
	currentDirectionOne = DIRECTION_UP
	currentDirectionTwo = DIRECTION_UP
	nextDirectionOne = DIRECTION_UP
	nextDirectionTwo = DIRECTION_UP

	draw(scr)
	drawPixel(scr, playerOneCoord[0], green)
	drawPixel(scr, playerTwoCoord[0], blue)
	previousTime = time.time()
	while True:
		if getDeltaTime(previousTime) >= tickDuration:
			playerOneCoord.append(movePlayer(scr, playerOneCoord[len(playerOneCoord)-1], green, nextDirectionOne, controlMapOne))
			playerTwoCoord.append(movePlayer(scr, playerTwoCoord[len(playerTwoCoord)-1], blue, nextDirectionTwo, controlMapTwo))
			if len(playerOneCoord) > 5:
				erasePixel(scr, playerOneCoord.popleft(), black)
				erasePixel(scr, playerTwoCoord.popleft(), black)
			previousTime = time.time()
			currentDirectionOne = nextDirectionOne
			currentDirectionTwo = nextDirectionTwo

		keypress = scr.getch()

		if keypress in (curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT):
			nextDirectionOne = getDirection(currentDirectionOne, keypress, controlMapOne)
		elif keypress in (ord('w'), ord('a'), ord('s'), ord('d')):
			nextDirectionTwo = getDirection(currentDirectionTwo, keypress, controlMapTwo)
		elif keypress == ord('p'):
			curses.delay_output(5000)
		elif keypress == ord('q'):
			break
		elif keypress == ord('r'):
			scr.clear()
			draw(scr)
Exemple #34
0
def reset():
    global game_objects, player1
    game_objects = []
    player1 = player()
    game_objects.append(player1)
Exemple #35
0
	def InitPlayer(self):
		self.Player = player()
Exemple #36
0

game_board = board()
matrix = game_board.returnboard()

w = wall(matrix)

matrix = w.form_wall()

b = bricks(matrix)
matrix = b.modify_wall()

x = 0
y = 0

p = player(x, y, matrix)

enemy_numbers = 0
total = 3
enemy1 = []

for i in range(enemy_numbers):
    q = enemy(matrix)
    q.initial()
    enemy1.append(q)


def print_board(matrix):
    for i in range(38):
        for j in range(76):
            if matrix[i][j] == 'B':
Exemple #37
0
	def add_player(self, pid, login, gid, kills = 0, deaths = 0):
		game = self.games[gid]
		pl = player(pid, login, game, self, kills, deaths)
		game.join(pl)	
		self.players[pid] = pl
Exemple #38
0
movementSpeed = 0.05


#Exits pygame
def close():
    pygame.display.quit()
    pygame.quit()
    quit()


pygame.mouse.set_visible(False)
pygame.event.set_grab(True)

clock = pygame.time.Clock()

player = player(10.0, 5.0, -0.7, 0, 0, 0.7)

#Start game loop
while player.alive:
    #Draws background. Black and Grey
    screen.fill((25, 25, 25))
    pygame.draw.rect(screen, (50, 50, 50),
                     (0, HEIGHT / 2, WIDTH,
                      HEIGHT / 2))  #Draws grey rectang sle in bottom half

    #Sets whether keys are held or not
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            keys[event.key] = True
        elif event.type == KEYUP:
            keys[event.key] = False
Exemple #39
0
difficulty = {	'enemy_ct':			15,
				'enemy_ct_boss':	25,
				'enemy_dmg':		8,
				'enemy_life_time':	6000,
				'enemy_spawn_time':	800,
				'player_health':	100,
				'death_penalty':	5,
				'num_injects':		2,
				'heal_amount':		35,
				'shield_amount':	2,
				'powerup_respawn':	True,
				'boss_spawn':		(5600, 2000),
				'player_spawn':		(300, 8700)	}

#world and entities initialization
player_char = player((0, 0), player_images, sounds, difficulty)
level1=Level(player_char, background, render_size, image_dict, difficulty)
player_HUD = HUD(screen, player_char, "Assets/health_bar1.png", powerup_img)

#win screen fade timer
fade_timer = 100
fade_ct = 40
win_screen_timer = 5000
no_win = True

#music for game
world_music = "Assets/Sounds/lightout.ogg"
boss_music = "Assets/Sounds/lightin.ogg"
boss_music_playing = False

#start music
 def createPlayer(self):
     self.bots[2].append(player(randint(100,900), randint(100,700), self))
def mainFunc():
  #--- --- --- --- --- --- Instantiating Player --- --- --- --- --- ---
  prot = player(requestString("Please enter your character name."))
  
  
  #--- --- --- --- --- --- Instantiating Items --- --- --- --- --- ---
  itemKnife = item(1,"Knife", "A long jagged knife stained with blood from previous uses!")
  itemKey = item(2,"Key","A key which glows bright red.\nIt might fit that lock in the main room!")


  #--- --- --- --- --- --- Instantiating Rooms --- --- --- --- --- ---
  # Entrance
  roomEntrance = room("Empty Room","To the north you spot a decrepit door sitting in the pale light of a dying torch. " + \
                      "As you approach, the smell of decay intensifies and you can't help but fear what may be waiting " + \
                      "for you on the other side. With no other exits in sight, do you choose to move forward?")
  
  # Inner Chamber
  roomChamber = room("Inner Chamber", "Upon entering the room the smell of decaying flesh burns through your nose and fills your " + \
                 "lungs like a fire consuming a house. In the center of the room stands a single lamp, giving off an eerie " + \
                 "red glow. The lamp appears to cast living shadows upon the walls. As you cautiously approach the light you " + \
                 "can't help but notice a faint thump getting louder as the lamp gets closer. Upon reaching the lamp you realize " + \
                 "the cause of the thumping sound is liquid dripping on to the lamp. You reach and touch the lamp only to " + \
                 "increased your own dread; the lamp is soaked in blood. With your heart pounding you take swift look around and " + \
                 "notice there are three doors, all leading in opposite directions. Which door do you choose to open first: " + \
                 "north, east, or west?") 
  
  # Secret Room
  roomSecret = room("The Pit", "You have found some sort of a hidden room behind the painting; hope begins to build that this could " + \
                    "lead to a way out of this nightmare. After completely entering the room you realize there is no " + \
                    "source of light other than what is bleeding in from the fire behind you. You step to the side to allow more light in " + \
                    "to penetrate the darkness and lose your footing. As you had hoped this room was the end to the nightmare... Just not the " + \
                    "end you were praying for. You have fallen to your death.")
  
  # Knife Room
  roomKnifeBaseDescription = "You immediately notice the warmth of a fire upon your skin as you walk through the door's threshold. " + \
                   "You begin to feel yourself naturally relax as a result of the fire. This quickly dissipates as you take a look around " + \
                   "to see the room is decorated with devices that could serve no other purpose than torture. Directly across from you to " + \
                   "the west, next to the fire, is a single table lined with assorted tools. Looking to the north you notice yet another " + \
                   "door, meaning a continuation to the nightmare."
  roomKnife = room("Torture Chamber", roomKnifeBaseDescription + " To the south nothing immediately catches your eye; however, after a " + \
                   "second look you can't help but notice an elaborate painting of a lovely woman dancing under a pale moon's light.")
                    
  # Developer Credits Room
  roomCredits = room("Developer's Shrine", "In the back wall of the room to the North, you see some sort of strange writing. As you approach, " + \
                     "your heart begins to drop and you feel sick to your stomach as you find that your earlier assumption was correct; you are " + \
                     "part of a sinister game. All is not lost... if this is a game then there must be a way to win!") 
  
  # Bear Room
  roomBearBaseDescription = "Natural light seems for fill this room and you hope this is your exit. You follow the light to find the source is " + \
                            "an opening high in the ceiling, but you see no way to climb up to it."
  roomBear = room("Guardian's Quarters",roomBearBaseDescription + " Directly across from you to the east, you see a door which " + \
                  "appears to be blocked by a monstrous bear. To your relief the animal is asleep, but you will need some sort of weapon to get " + \
                  "past. To the north you spot a small opening which may contain an answer.")  
  
  # Riddle Room
  roomRiddle = room("Prisoner's Cell", "You enter what appears to be a forgotten room. Old spider webs fill the dark crevices and thick carpet of dust " + \
                    "has collected on the stone floor. On the far wall you see an odd plaque with something written on it but you cannot make out " + \
                   "what written from this distance. Perhaps you should take a closer look.")              
 
  # Password Room
  roomPassword = room("Chamber of Whispers", "You finally reach an opening after what seemed to be an eternity traveling through a lightless tunnel. " + \
                      "A soft glow radiates from the center of the room with no obvious cause as to where the source of the light is. You slowly " + \
                      "and very cautiously approach. Once at the soft glow you are able to look at the rest of the room more clearly. " + \
                      "All around the room you see the remains of what appears to be those that have come before for you. Nothing else stands out, " + \
                      "so perhaps you should inspect the light further.")
                  
  # Victory Room
  roomVictoryBaseDescription = "After placing the key in the lock, the door seems to have taken a hold of it on its own. It's as if it has been " + \
                     "waiting for this moment for an eternity, like a hungry animal that has been given a scrap of food."
  roomVictory = room("Exit", roomVictoryBaseDescription + " Speaking of hungry animals, it seems the bear in the next room has awoken. You are not " + \
                     "able to get the door open before the ravenous bear is upon you.")
    
    
  #--- --- --- --- --- --- Add Inspectable Items --- --- --- --- --- --- ---
  # Bear in Guardian's Quarters; inspecting will kill the bear if the player has a knife, creating an East door; also updates victory text
  def bearDoor():
    if prot.searchInventory(1) == true :
      roomBear.setExit("EAST", roomRiddle)
      roomBear.setDescription(roomBearBaseDescription + " To the east, there is the carcass of a bear near a door. " + \
                              "To the north you spot a small opening.")
      roomVictory.setDescription(roomVictoryBaseDescription + " You hear several clicks and slowly the door creeps open. A light so bright " + \
                                 "you have to shield your eyes consumes to blood red glow of the room. Within a couple of seconds you can see " + \
                                 "clearly and walk up long stair case where an open field greets you at the top. You feel the warmth of the " + \
                                 "afternoon sun on your face and realize you have made it out alive.")
      roomBear.setInspect("BEAR","The bear is quite dead.")
  roomBear.setInspect("BEAR","The bear sleeps in front of a door and you cannot go through without disturbing it. You need something to kill it.", bearDoor)
    
  # Knife on table in Torture Room; inspecting gives the player a knife and changes the bear interaction
  def tableKnife():
    if not prot.searchInventory(itemKnife.getId()):
      prot.addToInventory(itemKnife)
      roomKnife.removeInspect("TABLE")
      roomBear.setInspect("BEAR","You remember the knife in your pocket and quickly use it to kill the sleeping bear. The way east is now clear.",bearDoor)
  roomKnife.setInspect("TABLE","At the end of the table you spot a long jagged dagger which could be useful in a dangerous situation. You take it.",tableKnife)
  
  # Painting on wall of Torture Chamber; inspecting creates a South door
  def paintingDoor():
    roomKnife.setExit("SOUTH", roomSecret)
    roomKnife.setDescription(roomKnifeBaseDescription + " To the south, behind an elaborate painting of a lovely woman dancing under a pale moon's light, " + \
                             "there is another door.")
  roomKnife.setInspect("PAINTING","Upon closer examination you see that the painting is wavering ever so slightly. You step a bit closer " + \
                      " and feel a cool breeze and the smell of fresh air. You've found a door hidden behind the painting.",paintingDoor)
                      
  # Inscription on wall in Developer's Shrine
  roomCredits.setInspect("WALL","The wall reads:\nMatthew Mason - Spinner of Yarns and explorer of Russia\n" + \
                         "Heather McCabe - Heroine of the Storm and leader of our company\n" + \
                         "Jason Lloyd - Slayer of Pythons and master of all things logistical\n" + \
                         "Brett Hansen - He's pretty cool too I guess")                    
                      
  # Plaque in Prisoner's Cell; inspecting prompts the player to solve a riddle
  def riddle():
    printNow("The plaque reads: 'It has a white light at the end of it and can be over in the blink of an eye. If you have seen " + \
                        "our secret, you know its value. What do I speak of?")
    riddleGuess = requestString("Speak the answer to the riddle: ")
    if riddleGuess == None: # Cancel
      printNow(">> Unsure, you step away from the plaque.")
      return
    elif riddleGuess.upper() == "LIFE": # Correct answer
      printNow(">> You speak confidently: 'LIFE'")
      printNow("You are suddenly certain that the phrase 'password1234' is important.")
    else: # Incorrect answer
      printNow(">> You speak confidently: '" + riddleGuess.upper() + "'")
      printNow ("Nothing happens. Your answer must have been incorrect.")
  roomRiddle.setInspect("PLAQUE", "", riddle)     
  
  # Light in Chamber of Whispers; inspecting prompts the player to provide the password which will give player a key
  def password():
    printNow("Suddenly, hundreds of voices begin to talk all at the same time. Through the commotion you cannot make out what they are saying. " + \
             "Just before it goes silent you hear a whisper: 'Give us the password to receive our treasure...'")
    passwordGuess = requestString("State the password:"******">> Unsure, you back away slowly.")
    elif passwordGuess == "password1234": # Correct answer
      prot.addToInventory(itemKey)
      printNow(">> You speak confidently: '" + passwordGuess + "'")
      printNow( "A key suddenly appears in your pocket.")
    else: # Incorrect answer
      printNow(">> You speak confidently: '" + passwordGuess + "'")
      printNow ("The voices shriek: 'Leave us and return when you know the password!'")
  roomPassword.setInspect("LIGHT", "", password)  
  
  
  #--- --- --- --- --- --- Add Initial Exits --- --- --- --- --- ---
  # Empty Room
  roomEntrance.setExit("NORTH", roomChamber)
  
  # Inner Chamber
  roomChamber.setExit("EAST", roomBear)
  roomChamber.setExit("SOUTH", roomEntrance)
  roomChamber.setExit("WEST", roomKnife)
  roomChamber.setExit("NORTH", roomVictory)
  
  # Torture Chamber
  roomKnife.setExit("NORTH", roomCredits)
  roomKnife.setExit("EAST", roomChamber)
  
  # Developer's Shrine
  roomCredits.setExit("SOUTH", roomKnife)
  
  # Guardian's Quarters
  roomBear.setExit("WEST", roomChamber)
  roomBear.setExit("NORTH", roomPassword)
  
  # Chamber of Whispers
  roomPassword.setExit("SOUTH",roomBear)
  
  # Prisoner's Cell
  roomRiddle.setExit("WEST", roomBear)
  
  
  #--- --- --- --- --- --- Add Map Print Function --- --- --- --- ---
  # Get list of room names
  roomList = [roomEntrance.getName(), roomKnife.getName(),roomChamber.getName(),roomBear.getName(), roomRiddle.getName(),
              roomCredits.getName(), roomVictory.getName(),roomPassword.getName()]
  #set flags for rooms visited
  roomFlags = [false, false, false, false, false, false, false, false]  
  
  # Print map of dungeon; [_] indicates visited room, [X] indicates current location
  def printMap():
    # Map lines with northern-most point at level three
    levelOne = ""
    levelTwo = ""
    levelThree = ""
    # Loop through flags list, setting lines to print for all levels
    for key in range(0, len(roomFlags)):
      # Level one is southern-most point and single room set (special case) 
      if key in range(0,1):
        if currRoom.getName() == roomList[key]:
          levelOne = "    [X]"
        elif roomFlags[key] == true:
          levelOne = "    [_]"
      # Level two is comprised of middle rooms
      elif key in range(1, 5):
        if currRoom.getName() == roomList[key]:
          levelTwo += "[X]"
        elif roomFlags[key] == true:
          levelTwo += "[_]"
        else:
          levelTwo += "    "
      # Level three is comprised of northern-most rooms
      elif key in range(5,len(roomFlags)):
         if currRoom.getName() == roomList[key]:
           levelThree += "[X]"
         elif roomFlags[key] == true:
           levelThree += "[_]"
         else:
           levelThree += "    "
    # Print map by line with northern-most point at level three
    printNow("----- MAP -----\n" + levelThree+"\n"+levelTwo+"\n"+levelOne)    
  
  
  #--- --- --- --- --- --- Add Directions Function --- --- --- --- ---
  def getDirections():
    directionString = "You may move in these directions: "
    if (currRoom.getExit("NORTH")!= false):
      directionString = directionString + "[NORTH]  "
    if (currRoom.getExit("EAST")!= false):
      directionString = directionString + "[EAST]  "
    if (currRoom.getExit("SOUTH")!= false):
      directionString = directionString + "[SOUTH]  "
    if (currRoom.getExit("WEST")!= false):
      directionString = directionString + "[WEST]  "
    return directionString
  
  
  #--- --- --- --- --- --- Main Code Segment --- --- --- --- --- ---
  # Global variable initialization
  victoryFlag = false # This flag will be flipped when player reaches victory room
  currRoom = roomEntrance # currRoom contains current location of player character
  
  # Print starting Description
  lineSeparator = "===============================================\n"
  printNow("You awaken from a dream you cannot remember in an unfamiliar setting. As you wait for your eyes to " + \
           "adjust you can't help but notice the pungent sent of decay lingering in the air. You immediately begin " + \
           "to feel a chill running down your spine as the realization hits that you may be part of some sinister game.")
  printNow("(type HELP if you have any questions)\n")
  printNow(lineSeparator)
  printNow("Current Location: " + roomEntrance.getName())
  printMap()
  printNow(roomEntrance.getDescription())
  
  # Main game loop; will loop until the player dies, exits, or reaches victory room
  while(victoryFlag == false):

    # Set victory flag and break if the player is in the victory room
    if (currRoom.getName() == roomVictory.getName() and prot.searchInventory(2) == True):
      # Only win if the bear isn't alive still
      if roomBear.getExit("EAST") != False:
        victoryFlag = True
      break
    # Break if the player is in the secret room
    elif (currRoom.getName() == roomSecret.getName()):
      break
    
    # Get player command input
    (cmd, args) = getUserInput()
    
    # Handle MOVE command
    if (cmd == "MOVE"):
      nextRoom = currRoom.getExit(args)
      # Invalid direction/no room in that direction
      if (nextRoom == false):
        printNow("That's not a valid direction. " + getDirections())
        continue
      # Victory room is locked
      elif (nextRoom.getName() == roomVictory.getName() and prot.searchInventory(2) == false):
        printNow("You don't have the key for that door.")
        continue
      # Change room, update map and print new description
      else:
        # Set flag for room visited
        for i in range(0,len(roomList)):
          if currRoom.getName() == roomList[i]:
            roomFlags[i] = true
      
        # Print description and map
        printNow(">> You boldly move " + args.lower() + " into the next room.")
        printNow(lineSeparator)
        currRoom = nextRoom
        printNow("Current Location: " + currRoom.getName())
        printMap()
        printNow(currRoom.getDescription())
        continue
    
    # Handle LOOK command (currently disabled)
    #elif (cmd == "LOOK"):    
      #printNow(">> You look to the " + args.lower() + ".")
      #printNow(currRoom.getLook(args))
      #continue
      
    # Handle INSPECT command
    elif (cmd == "INSPECT"):
      printNow(">> You inspect the " + args.lower() + ".")
      inspectDescription = currRoom.getInspect(args)
      if inspectDescription != "":
        printNow(inspectDescription)
      continue
    
    # Handle TAKE command
    elif (cmd == "TAKE"):
      canTakeItem = currRoom.takeItem(args)
      
      if canTakeItem:
        prot.addToInventory(item)
        printNow(">> You take the " + args.lower() + ".")
      else:
        printNow("You can't take that.")
      continue
    
    # Handle DIRECTIONS command
    elif (cmd == "DIRECTIONS"):
      printNow(getDirections())
    
    # Handle EXIT and HELP requests
    elif (cmd == "MENU"):
      if (args == "EXIT"):
        printNow("\nA grue sneaks up from behind and eats you.")
        break
      elif (args == "HELP"):
        printNow("\n# Commands:")
        printNow("# MOVE: Lets you move in the cardinal directions. Must be followed by north, south, east or west. Usage: 'move <direction>'")
        printNow("# INSPECT: Take a closer look at an item. Usage: 'inspect <item>'")
        printNow("# DIRECTIONS: Get a list of room exits. Usage: 'directions'")
        #printNow("# LOOK: Take a closer look in a direction. Usage: 'look <direction>'")
        #printNow("# TAKE: Take an item into your inventory. Usage: 'take <item>'")
        #printNow("# USE: Use an item in your inventory. Usage: 'use <item>'")
        printNow("# EXIT: Give up and end your adventure prematurely. Usage: 'exit'")
        #printNow("# HELP: Bring up this lovely menu. Usage: You really should know this one by now!")
        printNow("\n")
    
    # Handle anything else
    else:
      printNow("That's not a valid command.")
      continue
  
  # Declare victory or loss upon exit from the game loop.
  if (victoryFlag == true): #win
    showInformation("Way to go, %s!" %prot.getName())
  else: #loss
    showInformation("%s, you are a disgrace to adventurers everywhere!\nThis dungeon is saddened by your patheticness!" %prot.getName())
Exemple #42
0
	def addplayer(self):
		self.players.append(player(len(self.players) + 1, self))
Exemple #43
0
		for j in xrange(0, SCREEN_HEIGHT+2):
			posJ = j * SQM_SIZE
			y= (SCREEN_HEIGHT/2+1)-j+player.posy
			for i in range(0, SCREEN_WIDTH+2):
				posI = i * SQM_SIZE
				x = i - (SCREEN_WIDTH / 2+1) + player.posx
				ventana.blit(screen.pos[x, y].background,
							 (posI - SQM_SIZE + screen.displacementX, posJ - SQM_SIZE + screen.displacementY))
		ventana.blit(player.ImagePlayer, (posX, posY))
		mutex.release()
		pygame.display.update()


pygame.init()
ventana = pygame.display.set_mode((WIDTH, HEIGHT))
player = player()
screen = screen(player.posx,player.posy)
pygame.display.set_caption("ZombieLand")

ruta = []
# miFuente = pygame.font.Font("mifuente.otf")
# miTexto = miFuente.render("prueba fuente",0,(200,60,80))
# ventana.blit(miFuente, (posX,posY))
posY, posX = (HEIGHT / 2) - (SQM_SIZE/2), (WIDTH / 2) - (SQM_SIZE/2)

#Banderas para indicar que una tacla esta presionada:
flagLeft = False
flagRight = False
flagUp = False
flagDown = False
draw= threading.Thread(target=dibujar, args=(ventana, player, screen, mutex,)).start() #falta pasar los parametros por referencia
Exemple #44
0
    parser.add_option("-p", "--port", dest="port", help="Write a port")
    parser.add_option("-h", "--host", dest="host", help="Write an host")
    parser.add_option("-H", "--help", action="store_true", help="show this help message")

    (options, args) = parser.parse_args()
    if options.help or options.teamName == None or options.port == None or options.host == None:
        parser.print_help()
        sys.exit()

    teamName = options.teamName
    port = options.port
    host = options.host

    connexion.connect((host, int(port)))

    myPlayer = player(connexion, teamName, port, host)
    inputs = [connexion]
    outputs = []
    timeout = 0.1

    myPlayer.connect()

    while 42:
        inputready, outputready, exceptready = select.select(inputs, outputs, [], timeout)
        if not (inputready or outputready or exceptready):
            myPlayer.findGoodMove()
        else:
            for s in exceptready:
                sys.exit()
            for s in inputready:
                if s == connexion:
Exemple #45
0
def iround(n):
    y = round(n) - 0.5
    return int(y) + (y > 0)

def distance(x1, y1, x2, y2):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

def offscreen(o):
    if o.__class__.__name__ == 'player':
        return False
    return o.x > window.width or o.x < 0 or o.y > window.height or o.y < 0

keys = {'up': False, 'down': False, 'right': False, 'left': False}

game_objects = []
player1 = player()

font.add_file('TulpenOne-Regular.ttf')

title = text.Label("Taking Sides", font_name="Tulpen One", x=100, y=globals.window_height/2, font_size=85)
subtitle = text.Label("Press 'P' to play...", font_name="Tulpen One", x=106, y = globals.window_height/2 - 100, font_size = 38)

menuPolygon = polygon(5,None)
menuPolygon.x = 600
menuPolygon.y = 2 * globals.window_height / 3
menuPolygon.radius =  -(globals.window_width / 10)
menuPolygon.velY = random.randint(-4,4)
menuPolygon.velX = random.randint(-4,4)
menuPolygon.setVertices()

game_objects.append(player1)
        print("That is not a confirmational answer. Please try again")

#print("Please insert the horizontal territory of I Don't Know")
#a = input()
#print("Please insert the vertical territory of I Don't Know")
#b = input()
#a = int(a)
#b = int(b)
a = 50
b = 50


print("What is your name?")
name = input()
p1 = player(name, a, b)
print("Nice to meet you, " + name + "!")
p1.status()

print("Are you ready?")
response = input()
print("Good luck")

e1 = enemy("e1", a, b)
print("There is an enemy at " + str(e1.x) + "," + str(e1.y))

#e1.move_towards_p(p1)
#print(str(e1.x) + "," + str(e1.y))

#print(e1.close(p1))
    def __init__(self, *args, **kwargs):
        self.WorldName = ""
        super(Window, self).__init__(*args, **kwargs)
        self.state = ""

        # Whether or not the window exclusively captures the mouse.
        self.exclusive = False

        # When flying gravity has no effect and speed is increased.
        self.flying = False

        # Strafing is moving lateral to the direction you are facing,
        # e.g. moving to the left or right while continuing to face forward.
        #
        # First element is -1 when moving forward, 1 when moving back, and 0
        # otherwise. The second element is -1 when moving left, 1 when moving
        # right, and 0 otherwise.
        self.strafe = [0, 0]

        # Current (x, y, z) position in the world, specified with floats. Note
        # that, perhaps unlike in math class, the y-axis is the vertical axis.
        self.position = self.startpos = (0, 0, 0)

        # First element is rotation of the player in the x-z plane (ground
        # plane) measured from the z-axis down. The second is the rotation
        # angle from the ground plane up. Rotation is in degrees.
        #
        # The vertical plane rotation ranges from -90 (looking straight down) to
        # 90 (looking straight up). The horizontal rotation range is unbounded.
        self.rotation = (0, 0)

        # Which sector the player is currently in.
        self.sector = None

        # Velocity in the y (upward) direction.
        self.dy = 0

        # A list of blocks the player can place. Hit num keys to cycle.
        # self.inventory = [Blocks.Grass, Blocks.Sand, Blocks.Brick, Blocks.Stone, Blocks.Dirt, Blocks.CobbelStone]
        self.hotbarelement = 0

        # The current block the user can place. Hit num keys to cycle.
        # self.block = self.inventory[0]

        # Convenience list of num keys.
        self.num_keys = config.CONFIGS["init"]["KEYBINDS"][
            "inventoryslots:keys"]
        self.num_keys = config.CONFIGS["init"]["KEYBINDS"][
            "inventoryslots:keys"]

        # Instance of the model that handles the world.
        self.model = Model(self)

        self.chatlabel = pyglet.text.Label(
            "",
            font_name="Arial",
            font_size=18,
            x=30,
            y=50,
            anchor_x="left",
            anchor_y="top",
            color=(0, 0, 0, 255),
        )

        self.player = player(self)
        player.playerinst = self.player

        self.world = None

        # time to manage destroy-system
        self.mouseclicktime = 0
        self.isclicked = False
        self.clickingblock = None
        self.clickstarttime = 0

        # mousepos for playerinventory
        self.mousepos = (0, 0)

        # helper vars for braking system
        self.braking_start = None

        self.turning_strafe = [0, 0]

        # This call schedules the `update()` method to be called
        # TICKS_PER_SEC. This is the main game event loop.
        pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)
        pyglet.clock.schedule_interval(tickhandler._run, 0.5)
        pyglet.clock.schedule_interval(EventHandler.eventhandler.update,
                                       1.0 / TICKS_PER_SEC)

        self.keyEvent = None
        self.last_generate = 1000

        self.menü = None
        self.menünames = config.CONFIGS["init"]["GAME_STATES"]
        self.menüeventbinds = []
        self.camerastate = 0  # 0: normal, 1: viewing player from out

        if config.CONFIGS["init"]["GAMETYPE"] != "FULL":
            eventhandler.on_event("on_draw_2D", self.on_draw_2d_demo_label)
            print("demo mode")

        self.worldname = None
        self.seed = 0

        self.gametime = 0  # a value between 0 and 2000 (0=2000)

        self.lastsize = (800, 600)

        self.demostarttime = time.time()
Exemple #48
0
ypos = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
win = pygame.display.set_mode((600, 700))


def make_box():
    count = 7
    shift = 0
    for i in range(55, 166 + 55, 55):
        for j in range(0, count):
            boxes.append(brick(shift * 85 + j * 85, i))
        count -= 2
        shift += 1


run = True
paddle = player()
speed = 4
ball = balls(paddle, speed)
clock = pygame.time.Clock()
key = pygame.image.load('Resources/ball_t (2).png')
saddle = pygame.image.load("Resources/paddle.png")
background_image = pygame.image.load("Resources/space.jpg")
pygame.mixer.init()
pygame.mixer.music.load('Resources/music.mp3')
pygame.mixer.music.play(-1)
while run:
    win.blit(background_image, [0, 0])
    if lives == 0:
        run = False
    else:
        strp = 0
 def __playerLoader(self):
     """Loads the player"""
     self._Player = player(self._level)
     self._playerList.add(self._Player)
Exemple #50
0
 def InitPlayer(self):
     self.Player = player()