Esempio n. 1
0
def filtrarColor(request, color):
	login(request)
	products = Producto.objects.filter(color=color).order_by('nombre')

	if products is not None:
			# LISTADO FILTRO
		categories = Producto.objects.values_list('categoria', flat=True).distinct().order_by('categoria')
		product_type = Producto.objects.values_list('tipo_producto', flat=True).distinct().order_by('tipo_producto')
		brand = Producto.objects.values_list('marca', flat=True).distinct().order_by('marca')
		size = Producto.objects.values_list('talla', flat=True).distinct().order_by('talla')
		colour = Producto.objects.values_list('color', flat=True).distinct().order_by('color')

		context = {
			'products': products,
			'categories': categories,
			'product_type': product_type,
			'brand': brand,
			'size': size,
			'colour': colour
		}

		return render(request, 'store/listado.html', context)

	else:
		return redirect('products')

	return render(request, 'store/listado.html', {'products':products})
Esempio n. 2
0
	def post(self):
		newBook = getBook(self)
		if newBook.put():
			if memcache.get('allbooks'):
				memcache.replace('allbooks',[])
			render(self,'success.html',{'dispMsg':'Book Successfully Added!'})
		else:
			render(self,'success.html',{'dispMsg':'SNAPPED! CONTACT ADMINISTRATOR!'})
Esempio n. 3
0
def deleteUser(request):
	try:
		u = User.objects.get(username= request.user.username)
		u.delete()
		return redirect('home')
	except User.DoesNotExist:
		return render(request, 'store/home.html')
	return render(request, 'store/home.html')
Esempio n. 4
0
def draw(frameCount):

    pygame.display.set_caption("Junior Teste - %.1f" % relogio.get_fps())

    for event in pygame.event.get():
        eventos(event)

    processamentos(frameCount)
    render()
Esempio n. 5
0
def register(request):
	if request.method=="POST":
		name=request.POST['uname']
		mobileno=request.POST['mbno']
		email=request.POST['email']
		#print(name)
		udata={'name':name,'phone':mobileno,'email':email}
		return render(request,'firstapp/details.html',{'udata':udata})
		#return HttpResponse('Done')
	return render(request,'firstapp/register.html')
Esempio n. 6
0
def profile(request):
	login(request)
	obj= get_object_or_404(User, username=request.user.username)
	update_form = UpdateUser(request.POST or None, instance=obj)
	if request.method == "POST" and 'update_btn':
		if update_form.is_valid():
			obj=update_form.save(commit = False)
			obj.save()
			return	render(request, 'store/profile.html', {'update': update_form})

	return render(request, 'store/profile.html', {'update': update_form})
Esempio n. 7
0
def scboard(request):
	if request.method=="POST":
		team1=request.POST.get('team1')
		team2=request.POST.get('team2')
		if team1 is not None:
			t1val=int(request.POST.get('t1val'))+1
			t2val=int(request.POST.get('t2val'))
		else:
			t1val= int(request.POST.get('t1val'))
			t2val=int(request.POST.get('t2val'))+1
		scores={'t1val':t1val,'t2val':t2val}
		return render(request,"firstapp/scboard.html",scores)
		#print(type(t1val))
	return render(request,'firstapp/scboard.html',{})
Esempio n. 8
0
def index(request):
	try:
		request.session["final_word"]
	except:
		request.session["final_word"] = []
	
	return render(request,'words_app/index.html')
Esempio n. 9
0
def signup(request):
	registered = False
	
	if request.method == 'POST':
		user_form = forms.UserForm(data=request.POST)
		profile_form = forms.UserProfileInfoForm(data=request.POST)

		if user_form.is_valid() and profile_form.is_valid():
			user = user_form.save()
			user.set_password(user.password)
			user.save()

			profile = profile_form.save(commit=False)
			profile.user = user

			if 'profile_pic' in request.FILES:
				print(request.FILES)
				profile.profile_pic = request.FILES['profile_pic']

			profile.save()
			registered = True

		else:
			print(user_form.errors, profile_form.errors)
 
	else:
		user_form = forms.UserForm()
		profile_form = forms.UserProfileInfoForm()

	return render(request, 'signup.html', {
		'user_form': user_form,
		'profile_form': profile_form,
		'registered': registered
		})
Esempio n. 10
0
def new_activation_link(request, user_id):
    form = RegistrationForm()
    datas = {}
    user = Users.objects.get(id=user_id)
    if user is not None and not user.is_active:
        datas['first_name'] = user.first_name
        datas['last_name'] = user.last_name
        datas['username'] = user.username
        datas['email_path'] = "/ResendEmail.txt"
        datas['email_subject'] = _("New activation key for CMS")

        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
        usernamesalt = datas['username']
        if isinstance(usernamesalt, unicode):
            usernamesalt = usernamesalt.encode('utf8')
        datas['activation_key'] = hashlib.sha1(salt + usernamesalt).hexdigest()

        profile = Profile.objects.get(user=user)
        profile.activation_key = datas['activation_key']
        profile.key_expires = datetime.datetime.strftime(
            datetime.datetime.now() + datetime.timedelta(days=2),
            "%Y-%m-%d %H:%M:%S")
        profile.save()

        form.sendEmail(datas)
        request.session['new_link'] = True  #Display: new link sent
        return render(request, 'register.html', {
            'u': settings.CMS_URL,
            'lpl': lpl
        }, locals())
    else:
        return redirect(settings.CMS_URL)
Esempio n. 11
0
def request_new_pass(request):
    registration_form = Email2Form()
    context = RequestContext(request)
    l = []
    if request.method == 'POST':
        form = Email2Form(request.POST)
        if form.is_valid():
            datas = {}
            datas['email'] = form.cleaned_data['email']
            user = Users.objects.get(email=datas['email'])
            datas['username'] = user.username
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            el = get_object_or_404(Users, email=datas['email'])
            usernamesalt = el.username
            if isinstance(usernamesalt, unicode):
                usernamesalt = usernamesalt.encode('utf8')
            datas['activation_key'] = hashlib.sha1(salt +
                                                   usernamesalt).hexdigest()

            datas['email_path'] = "/ActivationEmail.txt"
            datas['email_subject'] = _("Change your CMS password")

            form.sendEmail(datas)
            form.save(datas)  #Save the user and his profile
            request.session['registered'] = True  #For display purposes
            return redirect(settings.URL + settings.RECIEVED + "/")  #
        else:
            registration_form = form  #Display form with error messages (incorrect fields, etc)
    return render(request, 'req-np.html', {
        'formset': registration_form,
        'u': settings.CMS_URL,
        'lpl': lpl
    }, locals())
Esempio n. 12
0
def new_pass(request, key):
    pas = get_object_or_404(PassChange, activation_key=key)
    user = get_object_or_404(Users, id=pas.user_id)
    registration_form = PasswordForm(user_id=user.id)
    context = RequestContext(request)
    l = []
    if request.method == 'POST':
        form = PasswordForm(request.POST, user_id=user.id)
        if form.is_valid():
            datas = {}
            datas['first_name'] = user.first_name
            datas['last_name'] = user.last_name
            datas['username'] = user.username
            datas['password'] = form.cleaned_data['password1']
            datas['email'] = user.email
            datas['timezone'] = settings.TIME_ZONE
            datas[
                'preferred_languages'] = "[\"" + settings.LANGUAGE_CODE + "\"]"
            datas['activation_key'] = pas.activation_key
            form.save(datas)  #Save the user and his profile
            el = get_object_or_404(Users, username=user.username)
            request.session['registered'] = True  #For display purposes
            PassChange.objects.filter(activation_key=key).delete()
            return redirect(settings.URL + settings.SUCCESS + "/")
        else:
            registration_form = form  #Display form with error messages (incorrect fields, etc)
    return render(
        request, 'set_pass.html', {
            'user': user,
            'formset': registration_form,
            'u': settings.CMS_URL,
            'lpl': lpl
        }, locals())
Esempio n. 13
0
def activation(request, key):
    activation_expired = False
    already_active = False
    profile = get_object_or_404(Profile, activation_key=key)
    if profile.user.is_active == False:
        if timezone.now() > profile.key_expires:
            activation_expired = True  #Display: offer the user to send a new activation link
            id_user = profile.user.id
        else:  #Activation successful
            profile.user.is_active = True
            profile.user.save()
            c = Participations()
            c.delay_time = "00:00:00"
            c.extra_time = "00:00:00"
            c.hidden = "f"
            c.unrestricted = "f"
            c.contest_id = settings.CONTEST_ID
            c.user_id = profile.user.id
            c.name = "ZOTKS"  #change this too if you want.
            c.save()
    else:
        already_active = True  #Display : error message
    return render(request, 'aut.html', {
        'u': settings.CMS_URL,
        'lpl': lpl
    }, locals())
Esempio n. 14
0
def cart(request):
    tokenValue = request.COOKIES.get("token")
    if not tokenValue:
        return redirect('/login/')
    try:
        user = User.objects.get(tokenValue=tokenValue)
    except User.DoesNotExist as e:
        return JsonResponse({'error':2})
    carts = Cart.objects.filter(user__tokenValue=tokenValue)
    return render(request, 'cart/cart.html', {'carts':carts})
Esempio n. 15
0
def home(request):
    slideList = SlideShow.objects.all()

    mainList = MainDescription.objects.all()
    for item in mainList:
        products = Product.objects.filter(categoryId=item.categoryId)
        item.product1 = products.get(productId=item.product1)
        item.product2 = products.get(productId=item.product2)
        item.product3 = products.get(productId=item.product3)
    return render(request, 'home/home.html',{"slideList":slideList, "mainList":mainList})
Esempio n. 16
0
def register(request):
	login(request)
	register_form = UCFCompleted()
	# codigo para el formulario del registro
	if request.method == "POST" and 'register_btn':
		register_form = UCFCompleted(request.POST)
		if register_form.is_valid():
			register_form.save();
			return HttpResponseRedirect('/')

	return render(request, 'store/registro.html', {'registro': register_form})
Esempio n. 17
0
	def post(self):
		out = {'featuredBooks':getFeaturedBooks(False)}
		newBook = getBook(self)
		error = False
		if not newBook.bookTitle:
			out['bookTitleError'] = 'Book Title cant be empty.'
			error = True
		elif not newBook.price and newBook.price != 0:
			out['priceError'] = 'If you dont enter price, we will assume that you want to donate.'
			error = True
		elif not ( newBook.contact):
			out['contactError'] = 'Please input at least one method of contacting you.'
			error = True
	
		out['newBook'] = newBook
		if error:
			render(self,'main.html',out)
		else:
			out['googleImages'] = google(newBook.bookTitle)
			render(self,'verify.html',out)	
Esempio n. 18
0
	def __init__(self, ants, logger, game_state):
		self.ants = ants
		self.logger = logger
		self.game_state = game_state
		self.dir_rotation = [('n','e','s','w'),
							 ('e','s','w','n'),
							 ('s','w','n','e'),
							 ('w','n','e','s')]
		self.dir_astar = 0
		self.dir_hill = 0
		self.flood_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.render = render(ants, self.game_state)
Esempio n. 19
0
def index(request):
    url="https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}"
    city='LONDON'
    r=requests.get(url.format(city)).json()
    city_weather={
        'city':city,
        'tempature':r['main']['temp'],
        'description':r['weather'][0]['description'],
        'icon':r['weather'][0]['icon']
    }
    context={'city_weather':city_weather}
    return render(request,'weather.html',context)
Esempio n. 20
0
def order_history(request, order_number):
    order = get_object_or_404(Order, order_number=order_number)

    messages.info(request, (
        f'This is a past confirmation for order number {order_number}. '
        'A confirmation email was sent on the order date.'
    ))

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
        'from_profile': True,
    }

    return render(request, template, context)
Esempio n. 21
0
def market(request, gid, cid, sid):
    leftCategorieList = CategorieGroup.objects.all()

    products = Product.objects.filter(categoryId=gid)

    if cid != "0":
        products = products.filter(childId=cid)
    if sid == "1":
        pass
    elif sid == "2":
        products = products.order_by("price")
    elif sid == "3":
        products = products.order_by("-price")
    childs = ChildGroup.objects.filter(categorie__categorieId=gid)
    return render(request, 'market/market.html', {'leftCategorieList':leftCategorieList, 'products':products, 'childs':childs, 'gid':gid,'cid':cid})
Esempio n. 22
0
    def post(self , request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False)

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            user = authenticate(username=username , password=password)

            if user is not None:
                if user.is_active:
                    login(request , user)
                    return redirect('music:index')

        return render(request, self.template_name , {'form':form})
Esempio n. 23
0
def thanks(request, user_id):
    user = get_object_or_404(Users, id=user_id)
    registration_form = EmailForm(user_id=user_id)
    context = RequestContext(request)
    l = []
    if request.method == 'POST':
        form = EmailForm(request.POST, user_id=user_id)
        if form.is_valid():
            datas = {}
            datas['first_name'] = user.first_name
            datas['last_name'] = user.last_name
            datas['username'] = user.username
            datas['password'] = user.password
            datas['email'] = form.cleaned_data['email']
            datas['timezone'] = settings.TIME_ZONE
            datas[
                'preferred_languages'] = "[\"" + settings.LANGUAGE_CODE + "\"]"
            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            usernamesalt = datas['username']
            if isinstance(usernamesalt, unicode):
                usernamesalt = usernamesalt.encode('utf8')
            datas['activation_key'] = hashlib.sha1(salt +
                                                   usernamesalt).hexdigest()

            datas['email_path'] = "/ActivationEmail.txt"
            datas['email_subject'] = _("Activate your user account for CMS")
            if not user.is_active:
                form.sendEmail(datas)
                form.save(datas)  #Save the user and his profile
            el = get_object_or_404(Users, username=user.username)
            request.session['registered'] = True  #For display purposes
            return redirect(settings.URL + settings.THANKS + "/" +
                            str(user.id) + "/")
        else:
            registration_form = form  #Display form with error messages (incorrect fields, etc)

    return render(
        request, 'thanks.html', {
            'user': user,
            'formset': registration_form,
            'u': settings.CMS_URL,
            'lpl': lpl
        }, locals())
Esempio n. 24
0
def login(request):
    if request.method == 'GET':
        if request.is_ajax():
            strNum = '1234567890'
            rand_str = ''
            for i in range(0, 6):
                rand_str += strNum[random.randrange(0, len(strNum))]
            msg = "您的验证码是:%s。请不要把验证码泄露给其他人。"%rand_str
            phone = request.GET.get('phoneNum')
            # send_sms(msg, phone)
            request.session["code"] = rand_str
            print("*********", rand_str)
            response = JsonResponse({"data": "ok"})
            return response
        else:
            return render(request, "mine/login.html")
    else:
        phone = request.POST.get("username")
        passwd = request.POST.get("passwd")
        code = request.session.get("code")

        if passwd == code:
            # 验证码验证成功
            # 判断用户是否存在
            uuidStr = str(uuid.uuid4())
            try:
                user = User.objects.get(pk=phone)
                user.tokenValue = uuidStr
                user.save()
            except User.DoesNotExist as e:
                # 注册
                user = User.create(phone, None, uuidStr, "hhhh")
                user.save()
            request.session["phoneNum"] = phone
            response = redirect("/mine/")
            response.set_cookie("token", uuidStr)
            return response
        else:
            # 验证码验证失败
            return redirect("/login/")
Esempio n. 25
0
def addAddress(request):
    if request.method == 'GET':
        return render(request, 'mine/addaddress.html')
    else:
        name = request.POST.get('name')
        sex = request.POST.get('sex')
        if sex == "0":
            sex = True
        sex = False
        telphone = request.POST.get('telphone')
        address_2 = request.POST.get('address_2')
        address_3 = request.POST.get('address_3')
        address_4 = request.POST.get('address_4')
        address_5 = request.POST.get('address_5')
        address_6 = request.POST.get('address_6')
        postCode = request.POST.get('postCode')
        allAddress = address_2 + address_3 + address_4 + address_5 + address_6
        phone = request.session.get('phoneNum')
        user = User.objects.get(pk=phone)
        address = Address.create(name, sex, telphone, postCode, allAddress, address_2, address_3, address_4, address_5, address_6, user)
        address.save()
        return redirect('/mine/address/')
Esempio n. 26
0
def products(request):
	# Se llaman todos los productos para luego ser listados
	products = Producto.objects.all().order_by('nombre')

	# LISTADO FILTRO
	categories = Producto.objects.values_list('categoria', flat=True).distinct().order_by('categoria')
	product_type = Producto.objects.values_list('tipo_producto', flat=True).distinct().order_by('tipo_producto')
	brand = Producto.objects.values_list('marca', flat=True).distinct().order_by('marca')
	size = Producto.objects.values_list('talla', flat=True).distinct().order_by('talla')
	colour = Producto.objects.values_list('color', flat=True).distinct().order_by('color')

	context = {
		'products': products,
		'categories': categories,
		'product_type': product_type,
		'brand': brand,
		'size': size,
		'colour': colour
	}

	login(request)

	return render(request, 'store/listado.html', context)
Esempio n. 27
0
def profile(request):
    """ Display the user's profile. """
    profile = get_object_or_404(UserProfile, user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile updated successfully')
        else:
            messages.error(request, 'Update failed. Please ensure the form is valid.')
    else:
        form = UserProfileForm(instance=profile)
    orders = profile.orders.all()

    template = 'profiles/profile.html'
    context = {
        'form': form,
        'orders': orders,
        'on_profile_page': True
    }

    return render(request, template, context)
Esempio n. 28
0
def sprejeto(request):
    return render(request, 'sprejeto.html', {
        'u': settings.CMS_URL,
        'lpl': lpl
    }, locals())
Esempio n. 29
0
    currentEvents = pygame.event.get() # cache current events
    for event in currentEvents:
        if event.type == QUIT or \
            (event.type == KEYDOWN and event.key == K_ESCAPE):
            run = False

    keyState = pygame.key.get_pressed()

    xDir = keyState[K_d] - keyState[K_a]
    yDir = keyState[K_SPACE] - keyState[K_LSHIFT]
    zDir = keyState[K_s] - keyState[K_w]

    direction = Vector([xDir, yDir, zDir])

    if not direction.is_zero():
        direction = direction.normalize()

    velChange = (sphere.get_velocity() - lastDirection*speed)\
                .projected(Vector([1.0, 0.0, 0.0]), Vector([0.0, 0.0, 1.0]))

    if direction != lastDirection:
        sphere.add_velocity((direction - lastDirection )* speed - velChange)
        lastDirection = direction


    update_physics(game)
    render(game)

pygame.quit()
Esempio n. 30
0
	def __init__(self, ants, logger):
		try:		
			# Setup shared variables
			self.ants = ants
			self.logger = logger
			self.render = render(ants, self)
			self.turn = 0
			self.diffuse_rate = DIFFUSE_RATE
			self.coefficient = COEFFICIENT
			
			# Time out setup
			total_time = self.ants.turntime
			safe_time = total_time * TIME_OUT_BUFFER
			self.time_out_vision = total_time - (TIME_OUT_VISION * safe_time)
			self.time_out_diffuse = self.time_out_vision - (TIME_OUT_DIFFUSE * safe_time)
			self.logger.debug("Time out total: %s , safe: %s", total_time, safe_time)
			self.logger.debug("Time out vision: %s", self.time_out_vision)
			self.logger.debug("Time out diffuse: %s", self.time_out_diffuse)
			
			self.kill_time = self.ants.turns * KILL_TIME
			self.logger.debug("Kill time: %s", self.kill_time)
			
			# Setup my ant variables
			self.my_hills = set()
			self.my_hill_scans = set()
			self.num_my_hills = 0
			self.prev_my_hills = 0
			
			self.my_dead_ants = []
			self.my_ants = set()
			self.movable = set()
			self.num_my_ants = 0		
			
			# Setup enemy ant variables
			self.owner_set = set()
			self.owner_count = 0
			self.enemy_dead_ants = []
			self.enemy_ants = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
			self.enemy_hills = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
			self.enemy_hill_scans = set()
			self.num_enemy_ants = 0

			# Setup food variables
			self.food = set()
			
			self.desired = set()
			self.weakest = 0
			self.target = 0
			self.confidence = 0
			self.attack_ant = None
			self.attack_target = None
			self.food_target = None
			self.path_max = PATH_MAX
			self.paths = []

			# Other maps
			self.occupied = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.mobile_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.food_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.seen = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.passable = [[True]*self.ants.cols for row in range(self.ants.rows)]
			self.vision = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.new_diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.my_attack_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.enemy_attack_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.nodes = []
						
			# Setup vision offset
			self.vision_offsets_2 = []
			mx = int(sqrt(self.ants.viewradius2))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= self.ants.viewradius2:
						self.vision_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
			
			# Setup attack offset
			radius = self.ants.attackradius2 * ATTACK_BUFFER
			self.enemy_attack_offsets_2 = []
			mx = int(sqrt(radius))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= radius:
						self.enemy_attack_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
						
			# Setup attack offset
			radius = self.ants.attackradius2 * DEFEND_BUFFER
			self.my_attack_offsets_2 = []
			mx = int(sqrt(radius))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= radius:
						self.my_attack_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
			
			# Full sized maps
			self.west_map = []
			self.east_map = []
			self.north_map = []
			self.south_map = []
					
			for row in range(self.ants.rows):
				self.west_map.append((row - 1) % self.ants.rows)
				self.east_map.append((row + 1) % self.ants.rows)
				
			for col in range(self.ants.cols):
				self.north_map.append((col - 1) % self.ants.cols)
				self.south_map.append((col + 1) % self.ants.cols)
			
		except:
			self.logger.error("Error game_state init: print_exc(): %s", traceback.format_exc())
Esempio n. 31
0
	def get(self):
		out = {'newBook':'','featuredBooks':getFeaturedBooks(False)}
		render(self,'main.html',out)
Esempio n. 32
0
import io
from load import *
from parse import *
from render import *

files = getFiles(inputDir, fileExtension)
for file in files:
    outLocation = outputDir + file.name + '.html'
    templateName = file.template + '.html'

    outFile = io.open(outLocation, mode='w', encoding='utf-8')

    outFile.write(render(templateDir + templateName, file))
Esempio n. 33
0
 def get(self , request):
     form = self.form_class(None)
     return render(request, self.template_name , {'form':form})
Esempio n. 34
0
	def __init__(self, ants, logger):
		# Setup share variables
		self.ants = ants
		self.logger = logger
		self.render = render(ants, self)
		self.turn = 0
						
		# Setup my ant variables
		self.my_ants = set()
		self.movable = set()
		self.num_my_ants = 0		
		self.my_hills = set()
		
		# Setup enemy ant variables
		self.enemy_ants = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
		self.enemy_hills = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
		self.num_enemy_ants = 0

		# Setup food variables
		self.food = set()
		self.eaten = 0
		self.unseen = set()
		self.fog = set()
		self.blocked = set()
		
		self.reset_list = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.empty = [[0]*self.ants.cols for row in range(self.ants.rows)]
		
		# Setup a quick set of all the blocks
		self.all_blocks = set()
		for col in range(self.ants.cols):
			for row in range(self.ants.rows):
				loc = row, col
				self.all_blocks.add(loc)
				
		
		for row in range(self.ants.rows):
			for col in range(self.ants.cols):
				loc = (row, col)
				self.unseen.add(loc)
				
		# Setup bucket map 
		self.size = BUCKET_SIZE
		self.bucket_rows = int(self.ants.rows / self.size)
		self.bucket_cols = int(self.ants.cols / self.size)
		
		self.find_bucket = [[(0,0)]*self.ants.cols for row in range(self.ants.rows)]	
		for row in range(self.ants.rows):
			for col in range(self.ants.cols):
				b_col = int(col / self.size)
				b_row = int(row / self.size)
				self.find_bucket[row][col] = (b_row, b_col)
				
		self.bucket_map = []
		for row in range(self.bucket_rows + 1):
			self.bucket_map.append([])
			for col in range(self.bucket_cols + 1):
				self.bucket_map[row].append(bucket(self.size))
			
		for row in range(self.bucket_rows):
			for col in range(self.bucket_cols):
				self.bucket_map[row][col].loc = (row * self.size, col * self.size)
						
		# Other maps
		self.occupied = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.mobile_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.food_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.seen = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.passable = [[True]*self.ants.cols for row in range(self.ants.rows)]
		self.vision = [[False]*self.ants.cols for row in range(self.ants.rows)]
		self.diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
		self.new_diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
		
		# Setup vision offset
		self.vision_offsets_2 = []
		mx = int(sqrt(self.ants.viewradius2))
		for d_row in range(-mx,mx+1):
			for d_col in range(-mx,mx+1):
				d = d_row**2 + d_col**2
				if d <= self.ants.viewradius2:
					self.vision_offsets_2.append((
						d_row%self.ants.rows-self.ants.rows,
						d_col%self.ants.cols-self.ants.cols
					))
		
		# Setup attack offset
		radius = self.ants.attackradius2 * ATTACK_BUFFER
		self.attack_offsets_2 = []
		mx = int(sqrt(radius))
		for d_row in range(-mx,mx+1):
			for d_col in range(-mx,mx+1):
				d = d_row**2 + d_col**2
				if d <= radius:
					self.attack_offsets_2.append((
						d_row%self.ants.rows-self.ants.rows,
						d_col%self.ants.cols-self.ants.cols
					))
Esempio n. 35
0
"""
UVG
GRAFICAS POR COMPUTADORA - seccion 20

Davis Alvarez - 15842

SR1: Points
"""
from render import *

img = render()

img.glInit()  #5
img.glCreateWindow(400, 400)  #5
img.glClearColor(0.5, 1, 0.36)  #10
img.glClear()  #20
img.glViewPort(1, 1, 398, 398)  #10
img.glColor(0, 0.5, 0.5)  #15
#img.glVertex(0.75,0.12)#30
"""Testear viewport
img.glVertex(1,1)
img.glVertex(-1,1)
img.glVertex(-1,-1)
img.glVertex(1,-1)
img.glVertex(0,0)
"""
"""Testear Linea"""
#primer cuadrante
img.glLine(0, 0, 1, 0)
img.glLine(0, 0, 1, 0.1)
img.glLine(0, 0, 1, 0.2)
 def render_3d(self):
      render(self.x_values, self.y_values, self.z_values)
Esempio n. 37
0
	def post(self):
		out = {'newBook':''}
		q = self.request.get('findBook')
		out['bookRequested'] = q
		out['books'] = findBook(q)
		render(self,'findBook.html',out)
Esempio n. 38
0
 def render_3d(self):
     render(self.x_values, self.y_values, self.z_values)
Esempio n. 39
0
    sphere.update_pos(direction*speed)

##    if collided:
##        #currentColor = RED
##        otherCube.set_color(RED)
##    else:
##        #currentColor = GREEN
##        otherCube.set_color(GREEN)

    #pos = mainCube.get_pos().get_value()
    #pos = icosahedron.get_pos().get_value()
    #pos = plane.get_pos().get_value()
##    pos = sphere.get_pos().get_value()

    render(game, collisionInfo)


##    if collisionPoint:
##        colPos = collisionPoint.value
##        glPushMatrix()
##        glTranslatef(colPos[0], colPos[1], colPos[2])
##        drawCross([1.0, 1.0, 1.0])
##        glPopMatrix()
##        drawVector(penetrationNormal.value)

    #pygame.display.flip()
    #pygame.time.wait(10)


pygame.quit()
Esempio n. 40
0
def home(request):
    return render(request, 'index.html')
Esempio n. 41
0
def uspeh(request):
    return render(request, 'uspeh.html', {
        'u': settings.CMS_URL,
        'lpl': lpl
    }, locals())
Esempio n. 42
0
	def __init__(self, ants, logger):
		try:		
			# Setup shared variables
			self.ants = ants
			self.logger = logger
			self.render = render(ants, self)
			self.turn = 0
			self.diffuse_rate = DIFFUSE_RATE
			self.coefficient = COEFFICIENT
			
			# Time out setup
			total_time = self.ants.turntime
			safe_time = total_time * TIME_OUT_BUFFER
			self.time_out_vision = total_time - (TIME_OUT_VISION * safe_time)
			self.time_out_analysis = self.time_out_vision - (TIME_OUT_ANALYSIS * safe_time)
			self.time_out_diffuse = self.time_out_analysis - (TIME_OUT_DIFFUSE * safe_time)
			self.logger.debug("Time out total: %s , safe: %s", total_time, safe_time)
			self.logger.debug("Time out vision: %s", self.time_out_vision)
			self.logger.debug("Time out analysis: %s", self.time_out_analysis)
			self.logger.debug("Time out diffuse: %s", self.time_out_diffuse)
			
			self.kill_time = self.ants.turns * KILL_TIME
			self.logger.debug("Kill time: %s", self.kill_time)
			
			# Setup my ant variables
			self.my_hills = set()
			self.num_my_hills = 0
			self.prev_my_hills = 0
			
			self.my_dead_ants = []
			self.my_ants = set()
			self.movable = set()
			self.num_my_ants = 0		
			
			# Setup enemy ant variables
			self.enemy_dead_ants = []
			self.enemy_ants = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
			self.enemy_hills = [set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set(), set()]
			self.num_enemy_ants = 0

			# Setup food variables
			self.food = set()
			
			self.desired = set()
			self.weakest = 0
			self.target = 0
			self.confidence = 0
			self.attack_ant = None
			self.attack_target = None
			self.food_target = None
			self.path_max = PATH_MAX
			self.paths = []
			
			self.map_scan = map_scan(ants, logger, self)				
					
			# Setup bucket map 
			self.size = BUCKET_SIZE
			self.bucket_rows = int(self.ants.rows / self.size)
			self.bucket_cols = int(self.ants.cols / self.size)
			
			self.find_bucket = [[(0,0)]*self.ants.cols for row in range(self.ants.rows)]	
			for row in range(self.ants.rows):
				for col in range(self.ants.cols):
					b_col = int(col / self.size)
					b_row = int(row / self.size)
					self.find_bucket[row][col] = (b_row, b_col)
					
			self.bucket_map = []
			for row in range(self.bucket_rows + 1):
				self.bucket_map.append([])
				for col in range(self.bucket_cols + 1):
					self.bucket_map[row].append(bucket(self.size))
				
			for row in range(self.bucket_rows):
				for col in range(self.bucket_cols):
					self.bucket_map[row][col].loc = (row * self.size, col * self.size)
							
			# Other maps
			self.occupied = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.mobile_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.food_map = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.seen = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.passable = [[True]*self.ants.cols for row in range(self.ants.rows)]
			self.vision = [[False]*self.ants.cols for row in range(self.ants.rows)]
			self.diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.new_diffusion = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.my_attack_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.enemy_attack_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.fighting_map = [[-999999]*self.ants.cols for row in range(self.ants.rows)]
			self.g_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.g_map = [[0]*self.ants.cols for row in range(self.ants.rows)]
			self.g_highest = 0
			self.nodes = []
						
			# Setup vision offset
			self.vision_offsets_2 = []
			mx = int(sqrt(self.ants.viewradius2))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= self.ants.viewradius2:
						self.vision_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
			
			# Setup attack offset
			radius = self.ants.attackradius2 * ATTACK_BUFFER
			self.enemy_attack_offsets_2 = []
			mx = int(sqrt(radius))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= radius:
						self.enemy_attack_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
						
			# Setup attack offset
			radius = self.ants.attackradius2 * DEFEND_BUFFER
			self.my_attack_offsets_2 = []
			mx = int(sqrt(radius))
			for d_row in range(-mx,mx+1):
				for d_col in range(-mx,mx+1):
					d = d_row**2 + d_col**2
					if d <= radius:
						self.my_attack_offsets_2.append((
							d_row%self.ants.rows-self.ants.rows,
							d_col%self.ants.cols-self.ants.cols
						))
			
			# Full sized maps
			self.west_map = []
			self.east_map = []
			self.north_map = []
			self.south_map = []
					
			for row in range(self.ants.rows):
				self.west_map.append((row - 1) % self.ants.rows)
				self.east_map.append((row + 1) % self.ants.rows)
				
			for col in range(self.ants.cols):
				self.north_map.append((col - 1) % self.ants.cols)
				self.south_map.append((col + 1) % self.ants.cols)
				
			# Bucket sized maps			
			self.west_bucket_map = []
			self.east_bucket_map = []
			self.north_bucket_map = []
			self.south_bucket_map = []			
			
			for row in range(self.bucket_rows):
				self.west_bucket_map.append((row - 1) % self.bucket_rows)
				self.east_bucket_map.append((row + 1) % self.bucket_rows)
				
			for col in range(self.bucket_cols):
				self.north_bucket_map.append((col - 1) % self.bucket_cols)
				self.south_bucket_map.append((col + 1) % self.bucket_cols)
			
			self.diffuse_sections = []
			self.bucket_sections = []
			self.total_sections = int(1 / (SECTION * SECTION))
			self.next_diffuse_section = 0
			self.next_vision_section = 1
			sections = int(1 / SECTION)
			for row in range(sections):
				for col in range(sections):
					left = int((row / sections) * self.ants.rows)
					top = int((col / sections) * self.ants.cols)
					right = int(((row + 1) / sections) * self.ants.rows)
					bottom = int(((col + 1) / sections) * self.ants.cols)
					section_bounds = bounds(left, top, right, bottom)
					self.diffuse_sections.append(section_bounds)

					left = int((row / sections) * self.bucket_rows)
					top = int((col / sections) * self.bucket_cols)
					right = int(((row + 1) / sections) * self.bucket_rows)
					bottom = int(((col + 1) / sections) * self.bucket_cols)
					section_bounds = bounds(left, top, right, bottom)
					self.bucket_sections.append(section_bounds)
					
			self.diffuse_sections.append(bounds(0, 0, 0, 0))
			self.bucket_sections.append(bounds(0, 0, 0, 0))
	
			#self.logger.debug("Diffuse Map size %s, %s", self.ants.rows, self.ants.cols)
			#for section in self.diffuse_sections:
			#	self.logger.debug("Diffuse Section left %s, top %s, right %s, bottom %s", section.left, section.top, section.right, section.bottom)
			
			#self.logger.debug("Bucket Map size %s, %s", self.bucket_rows, self.bucket_cols)
			#for section in self.bucket_sections:
			#	self.logger.debug("Bucket Section left %s, top %s, right %s, bottom %s", section.left, section.top, section.right, section.bottom)
				
		except:
			self.logger.error("Error game_state init: print_exc(): %s", traceback.format_exc())
Esempio n. 43
0
 def get(self):	
   render(self,'front.html',{'mainpageTitle':'title','output':'sample output'})
Esempio n. 44
0
def my_view(request):
    if not request.user.is_authenticated():
        return render(request, 'myapp/login_error.html')
Esempio n. 45
0
	def get(self,id):
		out = {'newBook':getOneBook(id)}
		render(self,'showBook.html',out)