Exemple #1
0
    def process(self):
        if self.f == None: # Failed to open the file
            editor.SetActive(editor.mainmenu)
            return True

        self.editpad.refresh()
        char = self.editpad.getch()


        if char == ord('q'):
            editor.SetActive(editor.mainmenu)
        elif char == curses.KEY_UP:
            self.editpad.scroll(-1)
        elif char == curses.KEY_DOWN:
            self.editpad.scroll(1)
        elif char == ord('g'):
            t = Textbox(self.textwin, "Goto Line: ")
            val = t.gettext()
            self.editpad.goto(val)
        elif char >= ord('0') and char <= ord('9'):
            val = char - ord('0')
            self.editpad.activate_plugin(val)
        elif char == ord('`'):
            self.editpad.activate_plugin(-1)
        elif char == ord('\n'):
            self.editpad.set_preview()
        elif char == ord('x'):
            self.editpad.unset_preview()
        return True
Exemple #2
0
class SelectFileWin(object):
    def __init__(self):
        window = unbedwin(editor.mainwin, 5, 10)
        self.textbox = Textbox(window, "File Path: ")

    def process(self):
        val = self.textbox.gettext()
        f = FileWin(val)
        editor.SetActive(f)
        return True

    def exit(self):
        self.textbox.clear()
Exemple #3
0
def game_intro(WIDTH, HEIGHT, screen, BLACK, WHITE, font, Star, clock):
    intro = True

    textObject = Textbox((WIDTH - 200) / 2, 340, 200, 24, 24, 20, True, "",
                         (0, 191, 255), (255, 255, 255), (0, 191, 255))

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    username = textObject.getName()
                    intro = False
                    return username

            textObject.handle_event(event)

        screen.fill(BLACK)

        # all_sprites_list.add(elementBox)

        textObject.update()
        textObject.draw(screen)
        menuText = font.render('Welcome to the Periodic Table Quiz', True,
                               (WHITE))
        menuTextW = menuText.get_width()
        screen.blit(menuText, ((WIDTH - menuTextW) / 2, 222))

        # Background stars
        for i in range(1, 20):
            newStarx = random.randint(1, WIDTH)
            newStary = random.randint(1, HEIGHT)
            newstarIntro = Star(screen, WHITE, (newStarx, newStary),
                                random.randint(1, 2), 20)

        pygame.display.update()
        clock.tick(15)
def password_prompt(lang, reset_pw):

	def get_return(z):
		if z == 'pw_mismatch':
			return
		t.z = z
		t.dw()

	t = Mbox()

	t.newFrame("Top Frame", (0, 0))
	t.newFrame("First Frame", (1, 0))
	t.newFrame("Second Frame", (2, 0))

	no_pw_detected = Labelbox(text="no_pw_set_pw", lang=lang, repr='nopwsetpw')
	old_pw_textbox = Textbox(text="Old Password", lang={"Old Password": "******"}, repr='oldpwtextbox')
	new_pw_textbox = Textbox(text="New Password", lang={"New Password": "******"}, repr='newpwtextbox')
	retype_new_pw_textbox = Textbox(text="Retype New Password", lang={"Retype New Password": "******"}, repr='retypenewpwtextbox')
	pw_textbox = Textbox(text="Password", lang={"Password": "******"}, repr='oldpwtextbox')

	if reset_pw:
		t.frames["Top Frame"].addWidget(no_pw_detected, (0, 0))
		t.frames["First Frame"].addWidget(old_pw_textbox, (1, 0))
		t.frames["First Frame"].addWidget(new_pw_textbox, (2, 0))
		t.frames["First Frame"].addWidget(retype_new_pw_textbox, (3, 0))
		t.frames["Second Frame"].addWidget(bsav, (0, 1))
		bsav.config(cmd=lambda: get_return((old_pw_textbox.getData(), new_pw_textbox.getData())) if new_pw_textbox.getData() == retype_new_pw_textbox.getData() else get_return('pw_mismatch'))
		bsav.button.config(width=10)
		old_pw_textbox.label.config(width=19)
		new_pw_textbox.label.config(width=19)
		retype_new_pw_textbox.label.config(width=19)
		no_pw_detected.label.config(wraplength=250, justify=LEFT)
	else:
		t.frames["First Frame"].addWidget(pw_textbox, (0, 0))
		t.frames["Second Frame"].addWidget(bok, (0, 1))
		bok.config(cmd=lambda: get_return(pw_textbox.getData()))
		bok.button.config(width=10)

	t.frames["Second Frame"].addWidget(bcancel, (0, 0))

	
	bcancel.button.config(width=10)
	
	bcancel.config(cmd=lambda: get_return('cancel'))


	t.root.wait_window()

	return t.z
Exemple #5
0
    def draw_current_population(self):
        # center text:
        # (x, y, width_X, length_Y) (textbox)

        row_pitch = C.row_pitch
        max_length = self.width // 4 - 2 * row_pitch
        center_pos = [7 * self.width // 8, 0]
        sample = ''.join(self.pop.population[0].genes)

        size = Textbox.shift_size(sample, C.pop_size, C.font, max_length)
        font = pygame.font.SysFont(C.font, size)
        n = 0

        for individual in self.pop.population:
            string = ''.join(individual.genes)

            txt = font.render(string, True, C.text_color)

            center_pos[1] += +size * (n + 1) + row_pitch
            txt_rect = txt.get_rect(center=center_pos)

            if center_pos[1] < self.height - row_pitch - txt.get_rect()[3]:
                self.game_display.blit(txt, txt_rect)
Exemple #6
0
 def __init__(self):
     window = unbedwin(editor.mainwin, 5, 10)
     self.textbox = Textbox(window, "File Path: ")
def main(t, lang, d):
    d.loadData()

    window_ = AppWindow(t)

    window_.lang = None

    teacher_table = Table(repr='teachertable')
    teacher_table_headers = [
        'Date', 'Check-In Time', 'Start Time', 'Check-Out Time', 'Confirm Time'
    ]

    window_.newFrame("First Frame", (1, 0))
    window_.newFrame("Second Frame", (2, 0))
    window_.newFrame("Third Frame", (2, 1))
    window_.newFrame("Fourth Frame", (4, 1))
    window_.newFrame("Fifth Frame", (3, 0))

    window_.frames["Second Frame"].rowconfigure(0, weight=5, minsize=350)
    window_.frames["Second Frame"].columnconfigure(0, weight=5, minsize=630)

    window_.frames["Fifth Frame"].grid(columnspan=3)

    search_value = Textbox(text="Search", repr=None)
    search_options = Toggle_option(
     options=(('Barcode', 'bCode'),('First Name', 'firstName'), \
     ('Last Name', 'lastName'), ('Chinese Name', 'chineseName'), \
     ('Phone Number', 'phoneNumber')), repr=None)
    search_button = Buttonbox(text='Search',
                              lang=window_.lang,
                              repr='searchbutton')

    window_.frames["First Frame"].addWidget(search_value, (0, 0))
    window_.frames["First Frame"].addWidget(search_options, (1, 0))
    window_.frames["First Frame"].addWidget(search_button, (0, 1))

    fward = Buttonbox(text='>> Next 30 >>', lang=window_.lang, repr='>>')
    bward = Buttonbox(text='<< Previous 30 <<', lang=window_.lang, repr='<<')
    blast = Buttonbox(text='>>> Last Page >>>', lang=window_.lang, repr='>>>')
    window_.frames["Fifth Frame"].addWidget(fward, (1, 1))
    window_.frames["Fifth Frame"].addWidget(bward, (1, 0))
    window_.frames["Fifth Frame"].addWidget(blast, (1, 2))

    fward.config(width=17)
    bward.config(width=17)
    blast.config(width=17)

    fward.selfframe.grid(padx=2)
    bward.selfframe.grid(padx=2)
    blast.selfframe.grid(padx=2)

    #window_.frames["Second Frame"].addWidget(teacher_table, (2, 0))

    sL, page_list = [], []
    for s in d.studentList.values():
        dp = s.datapoints
        sL.append([
            dp['bCode'], dp['firstName'], dp['lastName'], dp['chineseName'],
            dp['dob']
        ])

    sL.sort()

    students_on_page = []
    new_frame = Frame(window_.frames["Second Frame"])
    for s in sL:
        students_on_page.append(s)
        if len(students_on_page) >= 15:
            teacher_table_on_page = Table(repr='teachertable')
            teacher_table_on_page.place(parent=new_frame, row=0, column=0)
            teacher_table_on_page.setData(headers=teacher_table_headers,
                                          data=students_on_page)
            page_list.append(new_frame)
            new_frame = Frame(window_.frames["Second Frame"])
            students_on_page = []
        elif s == sL[-1]:
            teacher_table_on_page = Table(repr='teachertable')
            teacher_table_on_page.place(parent=new_frame, row=0, column=0)
            teacher_table_on_page.setData(headers=teacher_table_headers,
                                          data=students_on_page)
            page_list.append(new_frame)

    page_list[0].grid()

    #sL.append(l)

    #if len(sL[-1]) == 0 and len(sL) != 1: sL.pop()

    window_.pNum = 1

    def toPage(p):
        teacher_table.setData(headers=teacher_table_headers, data=sL[p])
        teacher_table.canvas.config(width=700, height=350)
        teacher_table.set_width(1, 5, 14)

        def open_edit_window(pos):
            student_id = teacher_table.data[pos[0] - 1][0]
            editS2.main(window_.lang, d, i=student_id)

        for pos, cell in teacher_table.cells.items():
            if pos[0] == 0: continue
            cell.config(bind=('<Double-Button-1>',
                              lambda event, pos=pos: open_edit_window(pos)))

    def next():
        if window_.pNum == len(sL) - 1: return
        toPage(window_.pNum + 1)
        window_.pNum = window_.pNum + 1

    def previous():
        if window_.pNum == 1: return
        toPage(window_.pNum - 1)
        window_.pNum = window_.pNum - 1

    def last():
        window_.pNum = len(sL) - 1
        toPage(window_.pNum)

    '''
	if len(sL[0]) > 15:
		toPage(1)
		fward.config(cmd=next)
		bward.config(cmd=previous)
		blast.config(cmd=lambda: toPage(len(sL) - 1))
		first_page.config(cmd=lambda: toPage(0))
	else:
		toPage(0)
	'''

    def s():
        window_.s = window_.search_value.getData()

        if search_options.stringvar.get() != 'bCode':
            sty = search_options.stringvar.get()
            sdp = window_.search_value.getData()

            sl = []

            for s in d.studentList:
                dp = False
                if sty == 'phoneNumber':
                    if d.studentList[s].datapoints['hPhone'] == sdp or \
                     d.studentList[s].datapoints['cPhone'] == sdp or \
                     d.studentList[s].datapoints['cPhone2'] == sdp:
                        dp = d.studentList[s].datapoints

                elif d.studentList[s].datapoints[sty] == sdp:
                    dp = d.studentList[s].datapoints

                if dp:
                    sl.append([
                        dp['bCode'], dp['firstName'], dp['lastName'],
                        dp['chineseName']
                    ])

            if len(sl) == 0:
                student_does_not_exist(window_.lang)
                return

            window_.s = sl[0][0]
            if len(sl) > 1:
                sl.sort()
                window_.s = spicker(sl)
                if not window_.s: return

        editS2.main(window_.lang, d=d, top=True, i=window_.s)

    search_value.entry.bind("<Return>", lambda x: s())
    search_button.config(cmd=s)
def convert_to_encrypted(lang, d):

	def get_return(z):
		t.z = z
		t.to_encrypt_file = to_encrypt_file_textbox.getData()
		t.db_file = db_file_textbox.getData()
		t.pw_file = pw_file_textbox.getData()
		t.pw = pw_textbox.getData()
		t.dw()

	def set_file(textbox):
		out_file = filedialog.asksaveasfilename()
		if len(out_file) != 0:
			textbox.setData(out_file + '.rybdb')

	def open_file(textbox):
		out_file = filedialog.askopenfile()
		if out_file != None:
			textbox.setData(out_file.name)

	t = Mbox()
	#t.root.overrideredirect(0)
	#t.root.bind("<Destroy>", lambda event: None)

	t.newFrame("First Frame", (0, 0))


	to_encrypt_file_textbox = Textbox(text='Unencrypted File', lang={'Unencrypted File': 'Unencrypted File'}, repr='unc_db_file')
	db_file_textbox = Textbox(text='Encrypt File To', lang={'Encrypt File To': 'Encrypt File To'}, repr='db_file')
	pw_file_textbox = Textbox(text='Password File', lang={'Password File': 'Password File'}, repr='pw_file')
	pw_textbox = Textbox(text='Password', lang={'Password': '******'}, repr='pw')

	brw1 = Buttonbox(text='browse', lang=language, repr='brw1')
	brw2 = Buttonbox(text='browse', lang=language, repr='brw2')
	brw3 = Buttonbox(text='browse', lang=language, repr='brw3')

	t.frames["First Frame"].addWidget(to_encrypt_file_textbox, (0, 0))
	t.frames["First Frame"].addWidget(db_file_textbox,(1, 0))
	t.frames["First Frame"].addWidget(pw_file_textbox,(2, 0))
	t.frames["First Frame"].addWidget(brw3, (0, 2))
	t.frames["First Frame"].addWidget(brw1, (1, 2))
	t.frames["First Frame"].addWidget(brw2, (2, 2))
	t.frames["First Frame"].addWidget(pw_textbox, (3, 0))
	t.frames["First Frame"].addWidget(bsav, (4, 1))
	t.frames["First Frame"].addWidget(bcancel, (5, 1))


	db_file_textbox.label.config(width=12)
	pw_file_textbox.label.config(width=12)
	to_encrypt_file_textbox.config(width=12)
	pw_textbox.label.config(width=12)
	brw1.button.config(width=7)
	brw2.button.config(width=7)
	brw3.button.config(width=7)
	bsav.button.config(width=22)

	brw1.config(cmd=lambda: set_file(db_file_textbox))
	brw2.config(cmd=lambda: set_file(pw_file_textbox))
	brw3.config(cmd=lambda: open_file(to_encrypt_file_textbox))
	bsav.config(cmd=lambda: get_return('success'))
	bcancel.config(cmd=lambda: get_return('cancel'), lang=lang)



	t.root.wait_window()

	if t.z == 'cancel':
		return

	key = str.encode(t.pw)
	studentList = pickle.load(open(t.to_encrypt_file, 'rb'))
	cipher = AES.new(key, AES.MODE_CFB, d.iv)
	binary_string = pickle.dumps(studentList)
	encrypted = cipher.encrypt(binary_string)

	f = open(t.db_file, 'wb')
	f.write(bytearray(encrypted))
	f.close()

	f = open(t.pw_file, 'wb')
	f.write(bytearray(str.encode(t.pw)))
	f.close()
Exemple #9
0
    def __init__(self, ):
        self.fps = 60

        self.screen_width = 1024
        self.screen_height = 580
        self.gravity = 0.1

        # Online?
        self.online = False

        # Images
        # K is for Kuchen, P1 and P2 for Player 1 and Player 2
        self.K_sprite = pygame.image.load("drawables/kuchen.png")
        self.P1_sprite = pygame.image.load("drawables/player1.png")
        self.P2_sprite = pygame.image.load("drawables/player2.png")

        # Sizes
        self.K_size_x = 10
        self.K_size_y = 10
        P1_size_x = 20
        P1_size_y = 20
        P2_size_x = 20
        P2_size_y = 20

        # Positions
        self.K_pos = (15, self.screen_height - 15)
        self.P1_pos = (0, self.screen_height - P1_size_y)
        self.P2_pos = (self.screen_width - P2_size_x,
                       self.screen_height - P2_size_y)

        # Init of Items in the game
        self.Kuchen = KuchenClass(self.K_size_x, self.K_size_y, self.K_pos[0],
                                  self.K_pos[1])
        self.Kuchen.set_v(0, 0)
        self.Player1 = Item(P1_size_x, P1_size_y, self.P1_pos[0],
                            self.P1_pos[1])
        self.Player1.set_v(0, 0)
        self.Player1.set_a(0, self.gravity)
        self.Player2 = Item(P2_size_x, P2_size_y, self.P2_pos[0],
                            self.P2_pos[1])
        self.Player2.set_v(0, 0)
        self.Player2.set_a(0, self.gravity)

        # Pygame elements
        pygame.init()
        pygame.font.init()
        gameDisplay = pygame.display
        self.screen = gameDisplay.set_mode(
            (self.screen_width, self.screen_height))
        gameDisplay.set_caption('Throw the Kuchen')
        self.clock = pygame.time.Clock()
        allsprites = pygame.sprite.RenderPlain(
            (self.Player1, self.Player2, self.Kuchen))

        # Background image
        self.imgBg = pygame.image.load("drawables/bg.png")

        # User Interface Elements
        self.wind = self.get_wind()
        if self.wind < 0: self.msgWind = str(abs(self.wind)) + " ->"
        elif self.wind > 0: self.msgWind = "<- " + str(abs(self.wind))
        else: self.msgWind = str(abs(self.wind))
        self.txtWind = Textbox(self.msgWind, (self.screen_width // 2, 0))
        self.txtForce = Textbox(str(self.throw_force),
                                (self.screen_width // 2, 50))
        self.txtAngle = Textbox(str(int(self.throw_angle)),
                                (self.screen_width // 2, 100))
        self.btnThrow = Button("drawables/button_throw.png",
                               (self.screen_width // 2, 200), "Throw!")
        self.btnContinue = Button("drawables/button_continue.png",
                                  (self.screen_width // 2, 200),
                                  "Press to continue")

        # This might be changed if we use a random starting player
        self.gameStatus = "P1_Ready"
        self.score_added = False
Exemple #10
0
class GameLoop():
    # COLORS
    WHITE = (255, 255, 255)
    GREY = (155, 155, 155)
    BLACK = (0, 0, 0)

    throw_force = 5
    throw_angle = 45
    P1_score = 0
    P2_score = 0

    # I dont include JustStarted and Finished here, to mark them a outside the regular flow
    statusFlow = [
        "P1_Ready", "P1_Threw", "P1_Missed", "P1_Hit", "P2_Ready", "P2_Threw",
        "P2_Missed", "P2_Hit"
    ]
    gameStatus = "JustStarted"
    api_url_base = 'http://127.0.0.1:5000/'
    api_url = '{0}info'.format(api_url_base)

    def __init__(self, ):
        self.fps = 60

        self.screen_width = 1024
        self.screen_height = 580
        self.gravity = 0.1

        # Online?
        self.online = False

        # Images
        # K is for Kuchen, P1 and P2 for Player 1 and Player 2
        self.K_sprite = pygame.image.load("drawables/kuchen.png")
        self.P1_sprite = pygame.image.load("drawables/player1.png")
        self.P2_sprite = pygame.image.load("drawables/player2.png")

        # Sizes
        self.K_size_x = 10
        self.K_size_y = 10
        P1_size_x = 20
        P1_size_y = 20
        P2_size_x = 20
        P2_size_y = 20

        # Positions
        self.K_pos = (15, self.screen_height - 15)
        self.P1_pos = (0, self.screen_height - P1_size_y)
        self.P2_pos = (self.screen_width - P2_size_x,
                       self.screen_height - P2_size_y)

        # Init of Items in the game
        self.Kuchen = KuchenClass(self.K_size_x, self.K_size_y, self.K_pos[0],
                                  self.K_pos[1])
        self.Kuchen.set_v(0, 0)
        self.Player1 = Item(P1_size_x, P1_size_y, self.P1_pos[0],
                            self.P1_pos[1])
        self.Player1.set_v(0, 0)
        self.Player1.set_a(0, self.gravity)
        self.Player2 = Item(P2_size_x, P2_size_y, self.P2_pos[0],
                            self.P2_pos[1])
        self.Player2.set_v(0, 0)
        self.Player2.set_a(0, self.gravity)

        # Pygame elements
        pygame.init()
        pygame.font.init()
        gameDisplay = pygame.display
        self.screen = gameDisplay.set_mode(
            (self.screen_width, self.screen_height))
        gameDisplay.set_caption('Throw the Kuchen')
        self.clock = pygame.time.Clock()
        allsprites = pygame.sprite.RenderPlain(
            (self.Player1, self.Player2, self.Kuchen))

        # Background image
        self.imgBg = pygame.image.load("drawables/bg.png")

        # User Interface Elements
        self.wind = self.get_wind()
        if self.wind < 0: self.msgWind = str(abs(self.wind)) + " ->"
        elif self.wind > 0: self.msgWind = "<- " + str(abs(self.wind))
        else: self.msgWind = str(abs(self.wind))
        self.txtWind = Textbox(self.msgWind, (self.screen_width // 2, 0))
        self.txtForce = Textbox(str(self.throw_force),
                                (self.screen_width // 2, 50))
        self.txtAngle = Textbox(str(int(self.throw_angle)),
                                (self.screen_width // 2, 100))
        self.btnThrow = Button("drawables/button_throw.png",
                               (self.screen_width // 2, 200), "Throw!")
        self.btnContinue = Button("drawables/button_continue.png",
                                  (self.screen_width // 2, 200),
                                  "Press to continue")

        # This might be changed if we use a random starting player
        self.gameStatus = "P1_Ready"
        self.score_added = False

    def getKeys(self):

        delta_angle = 0
        delta_force = 0

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            if self.throw_angle < 90:
                self.throw_angle += 0.05
            else:
                self.throw_angle = 90
        if keys[pygame.K_DOWN]:
            if self.throw_angle > 0:
                self.throw_angle -= 0.05
            else:
                self.throw_angle = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEBUTTONUP:
                mousepos = pygame.mouse.get_pos()
                bt_area = self.btnThrow.get_area()
                bc_area = self.btnContinue.get_area()
                if bt_area[0] < mousepos[0] < bt_area[1] and bt_area[
                        2] < mousepos[1] < bt_area[3]:
                    self.gameStatus = self.throw(self.Kuchen, self.gameStatus,
                                                 self.wind)
                    if self.wind < 0:
                        self.msgWind = str(abs(self.wind)) + " ->"
                    elif self.wind > 0:
                        self.msgWind = "<- " + str(abs(self.wind))
                    else:
                        self.msgWind = str(abs(self.wind))
                    self.txtWind = Textbox(self.msgWind,
                                           (self.screen_width // 2, 0))
                if bc_area[0] < mousepos[0] < bc_area[1] and bc_area[
                        2] < mousepos[1] < bc_area[3]:
                    if self.gameStatus[2:] == "_Hit":
                        self.score_added = False
                    self.wind = self.nextPlayer()
                    if self.wind > 0:
                        self.msgWind = str(abs(self.wind)) + " ->"
                    elif self.wind < 0:
                        self.msgWind = "<- " + str(abs(self.wind))
                    else:
                        self.msgWind = str(abs(self.wind))
                    self.txtWind = Textbox(self.msgWind,
                                           (self.screen_width // 2, 0))
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    delta_angle = 1
                if event.key == pygame.K_DOWN:
                    delta_angle = -1
                if event.key == pygame.K_LEFT:
                    delta_force = -1
                if event.key == pygame.K_RIGHT:
                    delta_force = 1
                if event.key == pygame.K_RETURN:
                    if self.gameStatus[2:] == "_Ready":
                        self.gameStatus = self.throw(self.Kuchen,
                                                     self.gameStatus,
                                                     self.wind)
                    elif self.gameStatus[2:] == "_Missed" or self.gameStatus[
                            2:] == "_Hit":
                        if self.gameStatus[2:] == "_Hit":
                            self.score_added = False
                        self.wind = self.nextPlayer()
                        if self.wind > 0:
                            self.msgWind = str(abs(self.wind)) + " ->"
                        elif self.wind < 0:
                            self.msgWind = "<- " + str(abs(self.wind))
                        else:
                            self.msgWind = str(abs(self.wind))
                        self.txtWind = Textbox(self.msgWind,
                                               (self.screen_width // 2, 0))
                        self.screen.blit(self.K_sprite, self.K_pos)
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    delta_angle = 0
                if event.key == pygame.K_DOWN:
                    delta_angle = 0
                if event.key == pygame.K_LEFT:
                    delta_force = 0
                if event.key == pygame.K_RIGHT:
                    delta_force = 0

        self.throw_angle += delta_angle
        self.throw_force += delta_force

    def getCollisions(self):
        new_pos = self.Kuchen.update()
        if (self.gameStatus[0:2] == "P1"):
            self.gameStatus = check_collision(self.Kuchen, self.Player2,
                                              self.gameStatus)
        elif (self.gameStatus[0:2] == "P2"):
            self.gameStatus = check_collision(self.Kuchen, self.Player1,
                                              self.gameStatus)
        if self.gameStatus != "P1_Hit" and self.gameStatus != "P2_Hit":
            self.gameStatus = check_collision_boundaries(
                self.Kuchen, 0, 0, self.screen_width, self.screen_height,
                self.gameStatus)
        return new_pos

    def nextStatus(self):
        for statusIx in list(range(0, len(self.statusFlow) - 1, 1)):
            if self.gameStatus == self.statusFlow[statusIx]:
                newStatus = self.statusFlow[(statusIx + 1) %
                                            len(self.statusFlow)]

    def throw(self, thrownObject, Status, wind):
        NewStatus = Status.split('_')[0] + "_Threw"
        # We correct angle for -y and both players here instead of under item.py
        if Status[0:2] == "P1":
            corrected_angle = 90 - int(self.throw_angle)
        elif Status[0:2] == "P2":
            corrected_angle = 270 + int(self.throw_angle)
        thrownObject.set_v_vector(self.throw_force, corrected_angle)
        thrownObject.set_a(wind, self.gravity)
        return NewStatus

    def nextPlayer(self):
        if self.online:
            url_text = '{0}' + self.gameStatus
            self.api_url = url_text.format(self.api_url_base)
            response = requests.put(self.api_url)
            exitcode = response.status_code
            data = json.loads(response.content.decode('utf-8'))
            self.gameStatus = data['gameStatus']
        else:
            if self.gameStatus[0:2] == "P1": self.gameStatus = "P2_Ready"
            elif self.gameStatus[0:2] == "P2": self.gameStatus = "P1_Ready"

        if self.gameStatus[0:2] == "P2":
            self.Kuchen.set_pos(self.screen_width - 15,
                                self.screen_height - 15)
        elif self.gameStatus[0:2] == "P1":
            self.Kuchen.set_pos(15, self.screen_height - 15)

        NewWind = self.get_wind()
        return NewWind

    def get_wind(self):
        #0.05 is fine
        newWind = random.randint(-5, 5) / 100
        return newWind

    def run(self):
        self.screen.blit(self.imgBg, (0, 0))
        while not self.gameStatus == "Finished":
            #tick
            self.clock.tick(self.fps)
            #input
            self.getKeys()
            #update and draw
            if (self.gameStatus[2:] == "_Threw"):
                self.K_pos = self.getCollisions()
                print(self.K_pos)
            elif (self.gameStatus[2:] == "_Ready"):
                self.txtWind.draw(self.screen)
                self.txtForce.draw(self.screen)
                self.txtAngle.draw(self.screen)
                self.btnThrow.draw(self.screen)
            elif (self.gameStatus[2:] == "_Missed"):
                self.btnContinue.draw(self.screen)
            elif (self.gameStatus[2:] == "_Hit"):
                if self.score_added == False:
                    if self.gameStatus[0:2] == "P1":
                        self.P1_score += 1
                    elif self.gameStatus[0:2] == "P2":
                        self.P2_score += 1
                    self.score_added = True
                PxWinsTxt = Textbox(self.gameStatus[0:2] + " Wins!", (200, 50))
                WinCounterTxt = Textbox(
                    str(self.P1_score) + " : " + str(self.P2_score),
                    (200, 150))
                PxWinsTxt.draw(self.screen)
                WinCounterTxt.draw(self.screen)
                self.btnContinue.draw(self.screen)
            ##NOT NEEDED IF NOT ONLINE? -> self.nextStatus()
        #    self.screen.fill(0)
        # redraw background
            print("####")
            old_pos = self.K_pos
            #self.K_pos = self.Kuchen.get_pos()
            print(old_pos)
            self.screen.blit(
                self.imgBg,
                (old_pos[0] - self.K_size_x, old_pos[1] - self.K_size_y),
                pygame.Rect(old_pos[0] - self.K_size_x,
                            old_pos[1] - self.K_size_y, 3 * self.K_size_x,
                            3 * self.K_size_y))

            self.screen.blit(self.P1_sprite, self.P1_pos)
            self.screen.blit(self.P2_sprite, self.P2_pos)
            self.screen.blit(self.K_sprite, self.K_pos)
            self.txtForce = Textbox(str(self.throw_force),
                                    (self.screen_width // 2, 50))
            self.txtAngle = Textbox(str(int(self.throw_angle)),
                                    (self.screen_width // 2, 100))
            pygame.display.flip()

        pygame.quit()
        quit()
Exemple #11
0
    def getKeys(self):

        delta_angle = 0
        delta_force = 0

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            if self.throw_angle < 90:
                self.throw_angle += 0.05
            else:
                self.throw_angle = 90
        if keys[pygame.K_DOWN]:
            if self.throw_angle > 0:
                self.throw_angle -= 0.05
            else:
                self.throw_angle = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEBUTTONUP:
                mousepos = pygame.mouse.get_pos()
                bt_area = self.btnThrow.get_area()
                bc_area = self.btnContinue.get_area()
                if bt_area[0] < mousepos[0] < bt_area[1] and bt_area[
                        2] < mousepos[1] < bt_area[3]:
                    self.gameStatus = self.throw(self.Kuchen, self.gameStatus,
                                                 self.wind)
                    if self.wind < 0:
                        self.msgWind = str(abs(self.wind)) + " ->"
                    elif self.wind > 0:
                        self.msgWind = "<- " + str(abs(self.wind))
                    else:
                        self.msgWind = str(abs(self.wind))
                    self.txtWind = Textbox(self.msgWind,
                                           (self.screen_width // 2, 0))
                if bc_area[0] < mousepos[0] < bc_area[1] and bc_area[
                        2] < mousepos[1] < bc_area[3]:
                    if self.gameStatus[2:] == "_Hit":
                        self.score_added = False
                    self.wind = self.nextPlayer()
                    if self.wind > 0:
                        self.msgWind = str(abs(self.wind)) + " ->"
                    elif self.wind < 0:
                        self.msgWind = "<- " + str(abs(self.wind))
                    else:
                        self.msgWind = str(abs(self.wind))
                    self.txtWind = Textbox(self.msgWind,
                                           (self.screen_width // 2, 0))
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    delta_angle = 1
                if event.key == pygame.K_DOWN:
                    delta_angle = -1
                if event.key == pygame.K_LEFT:
                    delta_force = -1
                if event.key == pygame.K_RIGHT:
                    delta_force = 1
                if event.key == pygame.K_RETURN:
                    if self.gameStatus[2:] == "_Ready":
                        self.gameStatus = self.throw(self.Kuchen,
                                                     self.gameStatus,
                                                     self.wind)
                    elif self.gameStatus[2:] == "_Missed" or self.gameStatus[
                            2:] == "_Hit":
                        if self.gameStatus[2:] == "_Hit":
                            self.score_added = False
                        self.wind = self.nextPlayer()
                        if self.wind > 0:
                            self.msgWind = str(abs(self.wind)) + " ->"
                        elif self.wind < 0:
                            self.msgWind = "<- " + str(abs(self.wind))
                        else:
                            self.msgWind = str(abs(self.wind))
                        self.txtWind = Textbox(self.msgWind,
                                               (self.screen_width // 2, 0))
                        self.screen.blit(self.K_sprite, self.K_pos)
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    delta_angle = 0
                if event.key == pygame.K_DOWN:
                    delta_angle = 0
                if event.key == pygame.K_LEFT:
                    delta_force = 0
                if event.key == pygame.K_RIGHT:
                    delta_force = 0

        self.throw_angle += delta_angle
        self.throw_force += delta_force
Exemple #12
0
def game_run():
    file = r'activation.mp3'
    # Initialize
    pygame.mixer.init()
    # Load the file pf music
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()

    # Initialize and create screen.
    pygame.init()
    setting = Setting()
    screen = pygame.display.set_mode(
        (setting.screen_width, setting.screen_height))
    pygame.display.set_caption("Aircraft war")

    # Create play button
    play_button = Button(setting, screen, 'Play', 200)
    help_button = Button(setting, screen, 'Help', 400)

    # Draw a rocket.
    rocket = Rocket(setting, screen)

    # Set a Group for bullets.
    bullets = Group()

    # Set a Group for alien bullets.
    alien_bullets = Group()

    # Set a Group for aliens.
    aliens = Group()

    # Create aliens.
    functions.create_aliens(setting, screen, rocket, aliens, alien_bullets)

    # Create States.
    states = States(setting)

    # Create Scoreboard.
    scoreboard = Scoreboard(setting, screen, states)

    # Create Textbox.
    textbox = Textbox(setting, screen)

    # Create Incidents.
    incidents = Group()

    # Create Background.
    BackGround = Background('background.jpg', [0, 0])

    # Main loop.
    while True:
        functions.respond_events(setting, screen, states, scoreboard, rocket,
                                 aliens, bullets, alien_bullets, play_button,
                                 help_button, textbox, incidents)
        if states.game_active:
            rocket.update_rocket()
            bullets.update(rocket)
            alien_bullets.update(setting)
            incidents.update(states)
            functions.update_bullets(setting, screen, states, scoreboard,
                                     rocket, aliens, bullets, alien_bullets)
            functions.update_aliens(setting, screen, states, scoreboard,
                                    rocket, aliens, bullets, alien_bullets,
                                    incidents)
            functions.update_alien_bullets(setting, screen, states, scoreboard,
                                           rocket, aliens, bullets,
                                           alien_bullets, incidents)
            functions.update_incidents(setting, screen, states, scoreboard,
                                       rocket, aliens, bullets, alien_bullets,
                                       incidents)
        functions.screen_update(setting, screen, states, scoreboard, rocket,
                                aliens, bullets, alien_bullets, play_button,
                                help_button, textbox, incidents)
        screen.fill([255, 255, 255])
        screen.blit(BackGround.image, BackGround.rect)
Exemple #13
0
	def __init__(self, **kwargs):
		Textbox.__init__(self, **kwargs)
		self.bold = False
		if 'bold' in kwargs: self.bold = kwargs['bold']
Exemple #14
0
Player2.set_v(0, 0)
Player2.set_a(0, GRAVITY)

  # Pygame elements
pygame.init()
pygame.font.init()
gameDisplay = pygame.display
screen = gameDisplay.set_mode((MAX_X, MAX_Y))
gameDisplay.set_caption('Throw the Kuchen')
clock = pygame.time.Clock()

  # User Interface Elements
if WIND < 0: windMsg = str(abs(WIND)) + " ->"
elif WIND > 0: windMsg = "<- " + str(abs(WIND))
else: windMsg = str(abs(WIND))
windTxt = Textbox(windMsg , (200, 0))
forceTxt = Textbox(str(throw_force), (200, 50))
angleTxt = Textbox(str(int(throw_angle)), (200, 100))
throwButton = Button("drawables/button_throw.png", (200, 200), "Throw!")
continueButton = Button("drawables/button_continue.png", (200, 200), "Press to continue")

# Statuses: 
#  JustStarted
#  Px_Ready
#  Px_Threw
#  Px_Hit
#  Px_Missed
gameStatus = "JustStarted"
# Just in case we want to start randomly here
gameStatus = "P1_Ready"
score_added = False
Exemple #15
0
    def run(self):
        self.screen.blit(self.imgBg, (0, 0))
        while not self.gameStatus == "Finished":
            #tick
            self.clock.tick(self.fps)
            #input
            self.getKeys()
            #update and draw
            if (self.gameStatus[2:] == "_Threw"):
                self.K_pos = self.getCollisions()
                print(self.K_pos)
            elif (self.gameStatus[2:] == "_Ready"):
                self.txtWind.draw(self.screen)
                self.txtForce.draw(self.screen)
                self.txtAngle.draw(self.screen)
                self.btnThrow.draw(self.screen)
            elif (self.gameStatus[2:] == "_Missed"):
                self.btnContinue.draw(self.screen)
            elif (self.gameStatus[2:] == "_Hit"):
                if self.score_added == False:
                    if self.gameStatus[0:2] == "P1":
                        self.P1_score += 1
                    elif self.gameStatus[0:2] == "P2":
                        self.P2_score += 1
                    self.score_added = True
                PxWinsTxt = Textbox(self.gameStatus[0:2] + " Wins!", (200, 50))
                WinCounterTxt = Textbox(
                    str(self.P1_score) + " : " + str(self.P2_score),
                    (200, 150))
                PxWinsTxt.draw(self.screen)
                WinCounterTxt.draw(self.screen)
                self.btnContinue.draw(self.screen)
            ##NOT NEEDED IF NOT ONLINE? -> self.nextStatus()
        #    self.screen.fill(0)
        # redraw background
            print("####")
            old_pos = self.K_pos
            #self.K_pos = self.Kuchen.get_pos()
            print(old_pos)
            self.screen.blit(
                self.imgBg,
                (old_pos[0] - self.K_size_x, old_pos[1] - self.K_size_y),
                pygame.Rect(old_pos[0] - self.K_size_x,
                            old_pos[1] - self.K_size_y, 3 * self.K_size_x,
                            3 * self.K_size_y))

            self.screen.blit(self.P1_sprite, self.P1_pos)
            self.screen.blit(self.P2_sprite, self.P2_pos)
            self.screen.blit(self.K_sprite, self.K_pos)
            self.txtForce = Textbox(str(self.throw_force),
                                    (self.screen_width // 2, 50))
            self.txtAngle = Textbox(str(int(self.throw_angle)),
                                    (self.screen_width // 2, 100))
            pygame.display.flip()

        pygame.quit()
        quit()
Exemple #16
0
def game_over(font, WHITE, BLACK, WIDTH, HEIGHT, clock, screen, Star, username,
              score):
    ove = True

    textObject = Textbox((WIDTH - 200) / 2, 340, 200, 24, 24, 20, True, "",
                         (0, 191, 255), (255, 255, 255), (0, 191, 255))

    while ove:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:

                    # Appending and reading from LeaderboardT.txt before the leaderboard function is called so data is ready to be displayed
                    # a+ Opens file for both reading and appending
                    file = open("leaderboardT.txt", "a+")
                    file.write(str(username) + "," + (str(score)) + "\n")

                    # the seek() method changes the current file position back to the top so it can be read from the begining again
                    file.seek(0)

                    # Numlines is used to find the range of how many elements need to be blitted later on in the leaderboard
                    numLines = 0
                    leaderboardTuple = []

                    for line in file:
                        data = line.split(",")
                        usernameL = data[0]
                        scoreL = data[1]
                        scoreL = scoreL.strip('\n')
                        leaderboardTuple.append((usernameL, int(scoreL)))

                        numLines += 1

                    # Only the top 10 are displayed
                    if numLines > 10:
                        numLines = 10

                    print(Sort_Tuple(leaderboardTuple))

                    print(numLines)
                    file.close()

                    leaderboardTuple = Sort_Tuple(leaderboardTuple)
                    game_leaderboard(font, WHITE, BLACK, WIDTH, HEIGHT, clock,
                                     screen, Star, username, score,
                                     leaderboardTuple, numLines)
                    ove = False

        screen.fill(BLACK)

        overText = font.render('Game Over', True, (WHITE))
        overTextW = overText.get_width()
        screen.blit(overText, ((WIDTH - overTextW) / 2, (HEIGHT) / 2))

        for i in range(1, 20):
            newStarx = random.randint(1, WIDTH)
            newStary = random.randint(1, HEIGHT)
            newstarDifficult = Star(screen, WHITE, (newStarx, newStary),
                                    random.randint(1, 2), 20)

        pygame.display.update()
        clock.tick(15)
    c = cells[i]
    if c.t == Terrain.PATH:
        towers.append(Tower(i, c.x, c.y, cell_size, TowerType.PATH.value))  # users can't replace this
        #display.register(towers[len(towers) - 1])
    else:
        towers.append(Tower(i, c.x, c.y, cell_size, TowerType.ZEROTOWER.value))  # users can replace this
        #display.register(towers[len(towers) - 1])

# enemies
enemies = []

# menu objects for buying and placing
# position should be relative to cell_size
menu = []
# 0-1 ; Title
menu.append(Textbox((6, 6), dark(red), font, "Neon Tower Defence"))
display.register(menu[0])
menu.append(Textbox((5, 5), text_color, font, "Neon Tower Defence"))
display.register(menu[1])
# 2-4 ; Level
playbutton = Cell(-4, cell_size * 3 + 5, cell_size, cell_size / 4 * 3, Terrain.PLAYBUTTON)
level_active = False


# this function is part of the menu: playbutton
def start_level(e):
    global level_active, menu, wave_number
    if not level_active:
        if e.type == pygame.MOUSEBUTTONDOWN:
            if e.button == 1:
                m_pos = pygame.mouse.get_pos()