-
Contagem de Conteúdo
13 -
Ingressou
-
Última visita
Tipo de Conteúdo
Perfis
Fóruns
Blogs
Calendário
Downloads
Postagens postado por CAIOG94
-
-
# SEAL ADVENTURE - JOGO 1º SEMESTRE # GRUPO 3 # CAIO GUIMARÃES SA SILVA # MARCO AURÉLIO SODRÉ # SAMIRA DE BARROS CAVALCANTE # TAIGUARA TALES DA SILVA VITORINO import pygame from pygame.locals import* # import math, random, sys, os class Game(): def __init__(self): pygame.init() pygame.display.set_caption("Seal Adventure") self.running, self.playing = True, False self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False self.DISPLAY_W, self.DISPLAY_H = 800, 600 # Tamanho da tela self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H)) self.window = pygame.display.set_mode(((self.DISPLAY_W,self.DISPLAY_H))) self.font_name = 'fonte/PressStart2P-vaV7.ttf' #self.font_name = pygame.font.get_default_font() self.BLACK,self. BLUE = (0, 0, 0), (63, 255, 223) #Definindo cores self.main_menu = MainMenu(self) #Classes self.options = OptionsMenu(self) self.credits = CreditsMenu(self) self.curr_menu = self.main_menu def game_loop(self): while self.playing: self.check_events() if self.START_KEY: self.playing= False #INICIO # # # CONFIGURAÇÕES DE TELA ------------------------------------------------------------------ larguraTela, alturaTela = 1000, 500 metadeLargura = larguraTela / 2 metadeAltura = alturaTela / 2 areaTela = larguraTela * alturaTela tela = pygame.display.set_mode((larguraTela, alturaTela)) bg = pygame.image.load("Cenario/cenariogelo.jpeg") background = pygame.transform.scale(bg, (larguraTela, alturaTela)) pygame.display.set_caption("Seal Adventure") pygame.init() CLOCK = pygame.time.Clock() FPS = 45 BLACK = (0, 0, 0) # # # MUSICA DO JOGO ----------------------------------------------------------------------------------- pygame.mixer.music.load('Musicas/Snow02.ogg') pygame.mixer.music.play(-1) # # # PERSONAGEM --------------------------------------------------------------------------------- scale_hero=[100,100] left = [pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'desenhoesquerda.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 2.0.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 3.0.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'pertras1.png')),(scale_hero)) ] right = [pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'desenho.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 2.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'correndo 3.png')),(scale_hero)), pygame.transform.scale(pygame.image.load(os.path.join('Personagens', 'perfren1.png')),(scale_hero)) ] scale_bullet=[35,35] bullet_img = pygame.transform.scale(pygame.image.load(os.path.join('Bullets', 'poder.png')), (scale_bullet)) x = 100 y = 395 radius = 80 vel = 5 move_left = False move_right = False stepIndex = 0 class Hero: def __init__(self, x, y): # walk self.x = x self.y = y self.velx = 6 self.vely = 15 self.face_right = True self.face_left = False self.stepIndex = 0 # Jump self.jump = False # Bullet self.bullets = [] self.cool_down_count = 0 # Health self.hitbox = (self.x, self.y, 64, 64) self.health = 40 self.lives = 1 self.alive = True # kills #self.kills = 0 def move_hero(self, userInput): if userInput[pygame.K_RIGHT] and self.x <= larguraTela - radius: self.x += self.velx self.face_right = True self.face_left = False elif userInput[pygame.K_LEFT] and self.x >= 0: self.x -= self.velx self.face_right = False self.face_left = True else: self.stepIndex = 0 def draw(self, tela): self.hitbox = (self.x, self.y, 78, 90) pygame.draw.rect(tela, (255, 0, 0), (self.x + 30, self.y - 10, 40, 10)) if self.health >= 0: pygame.draw.rect(tela, (0, 255, 0), (self.x + 30, self.y - 10, self.health, 10)) if self.stepIndex >= 16: self.stepIndex = 0 if self.face_left: tela.blit(left[self.stepIndex // 4], (self.x, self.y)) self.stepIndex += 1 if self.face_right: tela.blit(right[self.stepIndex // 4], (self.x, self.y)) self.stepIndex += 1 def jump_motion(self, userInput): if userInput[pygame.K_SPACE] and self.jump is False: jumpvar = pygame.mixer.Sound('Musicas/SFX_Jump_17.wav') jumpvar.play() self.jump = True if self.jump: self.y -= self.vely * 2 self.vely -= 1 if self.vely < -15: self.jump = False self.vely = 15 def direction(self): if self.face_right: return 1 if self.face_left: return -1 def cooldown(self): if self.cool_down_count >= 20: self.cool_down_count = 0 elif self.cool_down_count > 0: self.cool_down_count += 1 def shoot(self): self.hit() self.cooldown() if (userInput[pygame.K_f] and self.cool_down_count == 0): shootvar=pygame.mixer.Sound('Musicas/fogo.wav') shootvar.play() bullet = Bullet(self.x, self.y, self.direction()) self.bullets.append(bullet) self.cool_down_count = 1 #scale_hero = [100, 100] ataque = pygame.image.load(os.path.join('Personagens', 'ataque.png')) tela.blit(ataque, (90,90)) for bullet in self.bullets: bullet.move() if bullet.off_screen(): self.bullets.remove(bullet) def hit(self): for enemy in enemies: for bullet in self.bullets: if enemy.hitbox[0] < bullet.x < enemy.hitbox[0] + enemy.hitbox[2] and enemy.hitbox[ 1] < bullet.y < enemy.hitbox[1] + enemy.hitbox[3]: dano = pygame.image.load(os.path.join('Personagens', 'dano.png')) tela.blit(dano, (100, 100)) enemy.health -= 25 player.bullets.remove(bullet) class Bullet: def __init__(self, x, y, direction): self.x = x + 70 self.y = y + 30 self.direction = direction def draw_bullet(self): tela.blit(bullet_img, (self.x, self.y)) def move(self): if self.direction == 1: self.x += 15 if self.direction == -1: self.x -= 15 def off_screen(self): return not (self.x >= 0 and self.x <= larguraTela) # INIMIGO ---------------------------------------------------------------------------------------- scale_enimy=[100,100] left_enemy = [pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.png')),(scale_enimy)) ] right_enemy = [pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIM1.0.png')),(scale_enimy)), pygame.transform.scale(pygame.image.load(os.path.join('Inimigos', 'PINGUIMATAQUE1.0.png')),(scale_enimy)) ] class Enemy: def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.stepIndex = 0 # Health self.hitbox = (self.x, self.y, 64, 64) self.health = 40 self.kills=0 #self.ultimakills=0 def step(self): if self.stepIndex >= 32: self.stepIndex = 0 def draw(self, tela): self.hitbox = (self.x, self.y, 78, 90) pygame.draw.rect(tela, (255, 0, 0), (self.x + 20, self.y - 10, 40, 10)) if self.health >= 0: pygame.draw.rect(tela, (0, 255, 0), (self.x + 20, self.y - 10, self.health, 10)) self.step() if self.direction == left: tela.blit(left_enemy[self.stepIndex // 8], (self.x, self.y)) if self.direction == right: tela.blit(right_enemy[self.stepIndex // 8], (self.x, self.y)) self.stepIndex += 1 def move(self): self.hit() if self.direction == left: self.x -= 10 if self.direction == right: self.x += 9 def hit(self): if player.hitbox[0] < enemy.x + 32 < player.hitbox[0] + player.hitbox[2] and player.hitbox[1] < enemy.y + 32 < player.hitbox[1] + player.hitbox[3]: if player.health > 0: player.health -= 1 if player.health == 0 and player.lives > 0: player.lives -= 1 player.health = 40 elif player.health == 0 and player.lives == 0: player.alive = False def off_screen(self): return not (self.x >= -80 and self.x <= larguraTela + 30) # # # FUNÇÃO TELA ------------------------------------------------------------------------------ def draw_game(): tela.fill(BLACK) tela.blit(background, (0, 0)) # Draw Playerf player.draw(tela) # Draw Bullets for bullet in player.bullets: bullet.draw_bullet() # Draw Enemies for enemy in enemies: enemy.draw(tela) # Player Health if player.alive == False: tela.fill((0, 0, 0)) SCALE_FUNDO=[1000,500] SCALE_FUNDO= pygame.transform.scale(pygame.image.load(os.path.join('Cenario/menu.jpeg')), (SCALE_FUNDO)) tela.blit(SCALE_FUNDO, (0,0)) font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 32) text = font.render('GAME OVER! pressione R', True, (138, 47, 47)) textRect = text.get_rect() textRect.center = (metadeLargura, metadeAltura) tela.blit(text, textRect) #self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem if userInput[pygame.K_r]: player.alive = True player.lives = 1 player.health = 40 #kills = 0 font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 27) text = font.render('Mortos: ' + str(kills) + ' Vidas: ' + str(player.lives), True, (63, 255, 223)) # text2 = font.render('Última pontuação de mortes: ' + str(ultimakills) , True, (63, 255, 223)) # text3 = font.render('Recorde de mortes: ' + str(highkills) , True, (63, 255, 223)) tela.blit(text, (180, 20)) #tela.blit(text2, (180, 55)) #tela.blit(text3, (180, 90)) pygame.display.update() CLOCK.tick(FPS) # ultimakills=0 #highkills=kills #contador = kills player = Hero(250, 320) enemies = [] kills=0 # # # LOOP ------------------------------------------------------------------------ run = True while run: # # # FECHAR TELA ------------------------------------------------------------ for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() sys.exit() # Input userInput = pygame.key.get_pressed() # shoot player.shoot() # Movement player.move_hero(userInput) player.jump_motion(userInput) # # # CONTROLE INIMIGOS if len(enemies) == 0: rand_nr = random.randint(0, 1) if rand_nr == 1: enemy = Enemy(1010, 320, left) enemies.append(enemy) if rand_nr == 0: enemy = Enemy(0, 320, right) enemies.append(enemy) for enemy in enemies: enemy.move() if enemy.off_screen() or enemy.health <= 0: enemies.remove(enemy) if enemy.health <= 0: kills += 1 # Draw game in windows draw_game() #FIM def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running, self.playing = False, False self.curr_menu.run_display = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: self.START_KEY = True if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE: self.BACK_KEY = True if event.key == pygame.K_DOWN or event.key == pygame.K_s: self.DOWN_KEY = True if event.key == pygame.K_UP or event.key == pygame.K_w: self.UP_KEY = True def reset_keys(self): self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False def draw_text(self, text, size, x, y 😞 #Cor da letra, tamanho font = pygame.font.Font(self.font_name,size) text_surface = font.render(text, True, self.BLUE) text_rect = text_surface.get_rect() text_rect.center = (x,y) self.display.blit(text_surface,text_rect) class Menu(): def __init__(self, game): self.game = game self.mid_w, self.mid_h = self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 self.run_display = True self.cursor_rect = pygame.Rect(0, 0, 130, 130) self.offset = - 100 def draw_cursor(self): self.game.draw_text('▶', 20, self.cursor_rect.x, self.cursor_rect.y) def blit_screen(self): self.game.window.blit(self.game.display, (0, 0)) pygame.display.update() self.game.reset_keys() class MainMenu(Menu): def __init__(self, game): Menu.__init__(self, game) self.state = "Iniciar" self.startx, self.starty = self.mid_w, self.mid_h+80 self.tutorialx, self.tutorialy = self.mid_w, self.mid_h + 120 self.creditsx, self.creditsy = self.mid_w, self.mid_h + 160 self.exitx, self.exity = self.mid_w, self.mid_h + 200 self.cursor_rect.midtop = (self.startx + self.offset, self.starty) def display_menu(self): # Aparência do Menu self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) pygame.mixer.music.load('Musicas/prologue.mp3') pygame.mixer.music.play(-1) while self.run_display: self.game.check_events() self.check_input() self.game.display.blit(menuprincipal2,(0,0)) # Preenchendo tela com imagem self.game.draw_text("Jogar", 20, self.startx, self.starty) self.game.draw_text("Como Jogar?", 20, self.tutorialx, self.tutorialy) self.game.draw_text("Créditos", 20, self.creditsx, self.creditsy) self.game.draw_text("Sair", 20, self.exitx, self.exity) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.draw_cursor() self.blit_screen() def move_cursor(self): # Movimentação do Cursor (Setinha) if self.game.DOWN_KEY: # Usando seta pra baixo if self.state == 'Iniciar': self.cursor_rect.midtop = (self.tutorialx + self.offset, self.tutorialy) self.state = 'Como Jogar?' elif self.state == 'Como Jogar?': self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy) self.state = 'Créditos' elif self.state == 'Créditos': self.cursor_rect.midtop = (self.exitx + self.offset, self.exity) self.state = 'Sair' elif self.state == 'Sair': self.cursor_rect.midtop = (self.startx + self.offset, self.starty) self.state = 'Iniciar' elif self.game.UP_KEY: # Usando ceta pra cima if self.state == 'Iniciar': self.cursor_rect.midtop = (self.exitx + self.offset, self.exity) self.state = 'Sair' elif self.state == 'Sair': self.cursor_rect.midtop = (self.creditsx + self.offset, self.creditsy) self.state = 'Créditos' elif self.state == 'Como Jogar?': self.cursor_rect.midtop = (self.startx + self.offset, self.starty) self.state = 'Iniciar' elif self.state == 'Créditos': self.cursor_rect.midtop = (self.tutorialx + self.offset, self.tutorialy) self.state = 'Como Jogar?' def check_input(self): self.move_cursor() if self.game.START_KEY: if self.state == 'Iniciar': self.game.playing = True elif self.state == 'Como Jogar?': self.game.curr_menu = self.game.options elif self.state == 'Créditos': self.game.curr_menu = self.game.credits elif self.state == 'Sair': self.game.exiting = sys.exit() self.run_display = False class OptionsMenu(Menu): def __init__(self, game): Menu.__init__(self, game) self.arrowx, self.arrowy = self.mid_w, self.mid_h + 0 self.rightx, self.righty = self.mid_w, self.mid_h + 60 self.leftx, self.lefty = self.mid_w, self.mid_h + 90 self.shotx, self.shoty = self.mid_w, self.mid_h + 120 self.shotz, self.shoth = self.mid_w, self.mid_h + 150 def display_menu(self): self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem while self.run_display: self.game.check_events() self.check_input() self.game.display.fill((0, 0, 0)) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem self.game.draw_text('Tutorial', 40, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 - 120) self.game.draw_text("Teclado", 30, self.arrowx, self.arrowy) self.game.draw_text("Andar para Direita: →", 15, self.rightx, self.righty) self.game.draw_text("Andar para Esquerda: ←", 15, self.leftx, self.lefty) self.game.draw_text("Disparar Tiro: F", 15, self.shotx, self.shoty) self.game.draw_text("Pular: Barra de Espaço", 15, self.shotz, self.shoth) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.blit_screen() def check_input(self): if self.game.BACK_KEY: self.game.curr_menu = self.game.main_menu self.run_display = False elif self.game.START_KEY: pass class CreditsMenu(Menu): def __init__(self, game): Menu.__init__(self, game) def display_menu(self): self.run_display = True menuprincipal = pygame.image.load('Cenario/menu.jpeg') menuprincipal2 = pygame.transform.scale(menuprincipal, (800, 600)) while self.run_display: self.game.check_events() if self.game.START_KEY or self.game.BACK_KEY: self.game.curr_menu = self.game.main_menu self.run_display = False self.game.display.fill(self.game.BLACK) self.game.display.blit(menuprincipal2, (0, 0)) # Preenchendo tela com imagem self.game.draw_text('CRIADORES DO SEAL ADVENTURE', 20, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 4 - 20) self.game.draw_text('CAIO GUIMARÃES SA SILVA', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 10) self.game.draw_text('MARCO AURÉLIO SODRÉ', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 30) self.game.draw_text('SAMIRA DE BARROS CAVALCANTE FIGUEIREDO', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 50) self.game.draw_text('TAIGUARA TALES DA SILVA VITORINO', 15, self.game.DISPLAY_W / 2, self.game.DISPLAY_H / 2 + 70) self.game.draw_text("Voltar: ESC", 10, self.mid_w - 200, self.mid_h + 260) self.game.draw_text("Avançar: Enter", 10, self.mid_w + 200, self.mid_h + 260) self.blit_screen() def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running, self.playing = False, False self.curr_menu.run_display = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: self.START_KEY = True if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE: self.BACK_KEY = True if event.key == pygame.K_DOWN or event.key == pygame.K_s: self.DOWN_KEY = True if event.key == pygame.K_UP or event.key == pygame.K_w: self.UP_KEY = True # INICIALIDADOR DO JOGO g = Game() while g.running: g.curr_menu.display_menu() g.game_loop()
Gostaria de algumas ajuda ,do arquivo abaixo:
1º - Não estou conseguindo zerar o contador de mortes, quando se inicia uma nova partida. Contador fica acumulado.
2º - Não estou conseguindo executar um sprite ,quando eu aperto o botão de pulo (space) e o botão de ataque (Tecla F).
3º - Não estou conseguindo fazer o placar de mais mortes e última quantidade de mortes.
-
pode me ajudar nisso @geovaniif
Quero que o contador de mortes zere ao iniciar um nova partida.
-
-
def draw_game():
tela.fill(BLACK)
tela.blit(background, (0, 0))
# Draw Player
player.draw(tela)
# Draw Bullets
for bullet in player.bullets:
bullet.draw_bullet()
# Draw Enemies
for enemy in enemies:
enemy.draw(tela)
# Player Health
if player.alive == False:
tela.fill((0, 0, 0))
font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 32)
text = font.render('GAME OVER! pressione R', True, (138, 47, 47))
textRect = text.get_rect()
textRect.center = (metadeLargura, metadeAltura)
tela.blit(text, textRect)
if userInput[pygame.K_r]:
player.alive = True
player.lives = 1
player.health = 40
font = pygame.font.Font('fonte/PressStart2P-vaV7.ttf', 27)
text = font.render('Mortos: ' + str(kills) + ' Vidas: ' + str(player.lives), True, (189, 178, 209)) tela.blit(text, (230, 20))
pygame.display.update()
CLOCK.tick(FPS)
player = Hero(250, 410)
enemies = []
kills = 0
while player.lives == 0:
kills = 0
Eu estou tendo problemas na hora que acaba as vidas do personagem e dá gameover, pois quero que resete o contador de mortes a 0 quando dá Game over , mas já usei :
while player.lives == 0:
kills = 0
ou while player.lives <0
kills = 0
e nada do contador de Mortes resetar. Gostaria de saber como resetar o contador de mortes ?
-
N = int(input("Digite o valor de N:"))
while N<6 or N%2==1 or N>32:
print("O número {} digitado é inválido".format(N))
N = int(input("Digite o valor de N válido:"))
i=1
j=1
while i < N+1:
for j in range(1,N-i+1):
print(" ", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
print("**", end="")
else: print(" ", end="")
i = i + 1
j = j + 1
print()
for i in range(N-1,0, -1):
for j in range(1,N-i+1):
print(" ", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
print("**", end="")
else: print(" ", end="")
i = i + 1
j = j + 1
print()
Obs: não posso usar a função range nesse exercicio. Quero tiralo, sem mudar o objetivo do exercício e diminuir a quantidade de números do losango, sendo N=6 ,5 linhas, N=10, 9 linhas @geovaniif
-
Juro que estou tentando usar a logica ,mas não esta indo nao. @geovaniif
Código abaixo:
min = int(input("Digite um valor mínimo: "))
L=[]
QTDE =0
soma=0
divisor=2
cont2=0
primo =True
while min < 1:
print("\n O valor digitado {} , deve ser obrigatoriamente maior que 1 \n".format(min))
min = int(input("Digite um valor mínimo: "))
max = int(input("Digite um valor máximo: "))
while max < min:
print("\n O valor max {} , deve ser maior que valor min {} \n".format(max, min))
max = int(input("Digite o valor máximo: "))
L.append(min)
L.append(max)
if max > min:
cont=min
print("\nMin = {} e Max = {}\n".format(min, max))
while cont>=min and cont <= max :
Resto = cont % divisor
while divisor > cont and primo:
if cont % divisor ==0:
print(cont)
primo =False
soma = soma + cont
QTDE=QTDE +1
cont = cont + 1
if primo: cont2 += 1 if cont2>1:
print("\n Quantidade de primos no intervalo {} é = {}".format(L,QTDE))
print(" Soma dos primos no intervalo {} é = {}".format(L, soma))
else:
print(" Não há primos no intervalo {}".format(L)) print("\n\nFim do Programa")
-
Codigo:
min = int(input("Digite um valor mínimo: ")) L=[] QTDE =0 soma=0 i=2 while min < 1: print("\n O valor digitado {} , deve ser obrigatoriamente maior que 1 \n".format(min)) min = int(input("Digite um valor mínimo: ")) max = int(input("Digite um valor máximo: ")) while max < min: print("\n O valor max {} , deve ser maior que valor min {} \n".format(max, min)) max = int(input("Digite o valor máximo: ")) L.append(min) L.append(max) if max > min: cont=min print("\nMin = {} e Max = {}\n".format(min, max)) while cont>=min and cont <= max : Resto = cont % i if Resto == 0: print(cont) soma = soma + cont QTDE=QTDE +1 cont = cont + 1 if QTDE > 0 : print("\n Quantidade de primos no intervalo {} é = {}".format(L,QTDE)) print(" Soma dos primos no intervalo {} é = {}".format(L, soma)) else: print(" Não há primos no intervalo {}".format(L)) print("\n\nFim do Programa")
Não estou conseguindo imprimir somente os números primos dentre o intervalo do número minimo e numero maximo.
obs: Não devo usar range
-
vLW. identação as vezes ajuda, outra atrapalha. tenho que aprimorar e muito isso, Seja em python, C e em outraslinguagens de programação. Estou cursando Jogos digitais Tecnologo. Muito obrigado mesmmo @geovaniif
- 1
-
Muito obrigado @geovaniif. No caso a unica diferença, seria que no exercicio pede para inserir a quantidade de elementos que a lista terá e quais serão eles . o Else esta ok, mas no if quando eu peço pra mostrar a posicao do 3 na lista{3,4,3,3} mostra a posição errado dos 2 ultimos 3, mostrando assim
elemento 3 na posicao 0
elemento 3 na posicao 1 - correto elemento 3 na posicao 2
elemento 3 na posicao 2 - correto elemento 3 na posicao 3
ou outra situação que quando pede
-
2 horas atrás, CAIOG94 disse:
Boa Tarde! segue o print do codigo. Realmente tentei usar o que me informou para usar array ,mas nao consegui.
enunciado do exercicio:
Escreva um programa que leia do teclado um número inteiro N e em seguida preencha uma lista com N
elementos aleatórios. Em seguida, o programa deve ler um número inteiro X e informar se o valor de X
está na lista, bem como em qual posição. Se houver mais de uma ocorrência de X na lista, todas devem
ser informadas.- 1
-
Boa Tarde! segue o print do codigo. Realmente tentei usar o que me informou para usar array ,mas nao consegui.
enunciado do exercicio:
Escreva um programa que leia do teclado um número inteiro N e em seguida preencha uma lista com N
elementos aleatórios. Em seguida, o programa deve ler um número inteiro X e informar se o valor de X
está na lista, bem como em qual posição. Se houver mais de uma ocorrência de X na lista, todas devem
ser informadas. -
n= int(input("Digite quantidade de valores para a Lista A: "))
A=[]
i=0
QTDE=0
while i<n :
X = int(input("Digite o elemento {} da lista A: ".format(i+1)))
A.append(X)
QTDE = QTDE + 1
i = i + 1
N = int(input("Digite um numero aleátorio: "))
if N in A:
for N in A:
x=0
N = 0
print("\n O elemento {} consta na posição {} ".format(X, i-1))
N=N+1
i = i + 1
x = x + 1
else: print("\n O elemento {} não consta na lista A ".format(N))
print("\n\nFim do Programa")
Problemas ao executar a mecânica corretamente do Pulo no Game (bgi) c++
em C++
Postado
"Estou com um problema na hora de executar a ação do pulo, pois quando eu aperto o botão (seta pra cima) o objeto aparece no limite da altura do pulo e desce. Já pesquisei alguns vídeos ,mas não consegui por isso em prática."
#include<stdio.h>
#include<stdlib.h>
#include<graphics.h>
#include<math.h>
#include<conio.h>
#define LEFT 75
#define RIGHT 77
#define UP 72
#define DOWN 80
#define ESC 27
#define QntP 3
int main() {
int pg = 2;
int tamC, tamN, tamN2, tamC2;
int x, y, a=20;
double passoX, passoY;
char tecla = 0;
HWND janela;
int LarTela, AltTela;
int LarJogo, AltJogo;
int xIniJogo, yIniJogo;
void *Corote[QntP]; // esta variável é um vetor dinâmico que contém o sprite
void *CoroteM; // esta variável é um vetor dinâmico que contém a máscara
void *fundo;
void *fundo2;
int FPS;
FPS = 30;
float CamX=0;
float CamY=0;
int CamT=500;
int CamT2=0;
int CamV=1;
float c=0;
bool anda = false, troca = false, jump = false, chao= false;
int b = 0;
int i = 0;
int itroca = 0;
unsigned long long gt1, gt2;
int massa=1;
float grav=200;
LarTela = 800;
AltTela = 600;
initwindow(6400, AltTela, "Teste");
tamN = imagesize(0, 0, 6400, 599);
fundo = malloc(tamN);
readimagefile("Mapadomario.bmp", 0, 0, 6400, 599);
getimage(0, 0, 6400, 599, fundo);
tamN2 = imagesize(0, 0, 800, 599);
fundo2 = malloc(tamN2);
readimagefile("Mapadomario.bmp", 0, 0, 6400, 599);
getimage(5600, 0, 6399, 599, fundo2);
closegraph();
initwindow(LarTela, AltTela, "Teste");
tamC2 = imagesize(0, 0, 74, 74);
for(i = 0; i <= QntP; i++) {
Corote[i] = malloc(tamC2);
}
i = 0;
tamC = imagesize(0, 0, 74, 74);
CoroteM = malloc(tamC);
// Player
readimagefile("circulo.bmp", 0, 0, 225, 74);
for(i = 0; i <= QntP; i++) {
getimage(75*i, 0, 74+75*i, 74, Corote[i]);
}
// Player
readimagefile("circulomascara.bmp", 0, 0, 74, 74);
getimage(0, 0, 74, 74, CoroteM);
y = AltTela-200;
x = 100;
passoX = 0.5;
passoY = 0.3;
gt1 = GetTickCount();
while(tecla != ESC) {
gt2 = GetTickCount();
if (gt2 - gt1 > 1000/FPS) { /* este if garante que o programa só desenhará no momento certo */
gt1 = gt2;
}
if (pg == 1) pg = 2; else pg=1;
setactivepage(pg);
cleardevice();
putimage(CamX, 0, fundo, COPY_PUT);
putimage(x, y, CoroteM, AND_PUT);
putimage(x, y, Corote[itroca], OR_PUT);
if (anda == true){
CamX = 0;
CamT = 750;
putimage(0, 0, fundo2, COPY_PUT);
putimage(x, y, CoroteM, AND_PUT);
putimage(x, y, Corote[itroca], OR_PUT);
}
if (troca == true ){
itroca ++;
if (itroca >= QntP){
itroca = 0;
}
}
//troca = false;
if (jump == true){
y= -passoY;
// y++;
// y -= grav;
// y= -passoY;
y+= passoY+y;
// x+=passoX+x;
//delay(1);
itroca = 2;
}
jump = false;
chao = true;
if (chao == true)
{
if ( y < passoY *2)
{
// y+= grav * massa;
jump = false;
}
}
// pulo=passoY+y;
// y += grav * massa;
y+= grav;
// y-= grav;
setvisualpage(pg);
//define a força da gravidade
//y += grav;
// definindo colisão com a area direita da tela
// Movimentação da Camera (direita)
if (x > CamT ){
x = CamT-1; // = 700
CamX -= CamV * a; // Movimentação da Camera (direita)
b ++;
if (b == 280){
anda = true;
}
}
//definido a colisão com a area esqueda da tela
if (x < CamT2 ){
x = CamT2; // = 0
//CamX += CamV * a;/ // Movimentação da Camera (esquerda)
}
// definindo a colisão com o chão
if (y > AltTela-151 ){
y = AltTela-150;
}
//definindo a altura maxima do pulo
if (y < 200){
y = 200;
}
gt2 = GetTickCount();
fflush(stdin);
if(tecla ==LEFT) {
x = x - passoX*a;
troca= true;
//tecla=0;
}
//if (tecla==0)
// troca=false;
if(GetKeyState(VK_RIGHT)&0x80) x = x + passoX*a;
//troca = true;
if (GetKeyState (VK_UP)&0x80&& y == AltTela-150) {
jump=true;
// if (y==100)
//y-= passoY+y;
//y -= grav;
//delay(5);
}
// detecta e trata o pressionamento das teclas A, D, W, S
if(GetKeyState(0x41)&0x80) x = x - passoX*a; // A
if(GetKeyState(0x44)&0x80) x = x + passoX*a; // D
if(GetKeyState(0x57)&0x80) y = y - passoY*a; // W
if (kbhit()){
tecla = getch();
/*if (tecla == UP){
y = y - passoY*a*a;
tecla = 0;
}*/
}
}
closegraph();
return 0;
}
Testejogo2semestre.zip