Jump to content

SUBIECTE NOI
« 1 / 5 »
RSS
Filtru sedimente inainte de pompa?

Paște fericit!

electrician constructor video curs

Cum pot bloca transferul de date ...
 Ce reprezinta in chimie abrevieri...

Google pay ma taxeaza in timp ce ...

Kia Picanto 2022 - Problema motor?

Durere umar AC Joint
 Care este cea mai sanatoasa paine?

Zgomot ritmic ce urmeaza rotirea ...

Merita Lumix FZ82 in 2024?

Nu pot activa Memory Integrity
 Supratensiuni accidentale

Cuțit/ briceag drumetie

Cum am acces la o parte dintr-un ...

Mother's Day
 

[Python]Pong

- - - - -
  • Please log in to reply
2 replies to this topic

#1
FollowLight

FollowLight

    New Member

  • Grup: Members
  • Posts: 14
  • Înscris: 16.11.2014
Salut,am facut acest joc cu ceva timp in urma si m-am decis sa-l public aici.
Cat despre jocul in sine pot spune doar ca este foarte primitv si nu beneficiaza de optiunii foarte avansate.De asemenea,fizica nu este chiar atat de stralucita(daca se poate numi fizica) si inca are 1 bug destul de enervat.

Sper ca acest "joc" sa poata fi folosit macar ca o referinta.

try:
from pygame.locals import *
import pygame
import sys
import os
except ImportError as e:
print("[Missing//Error]: {}".format(e))
print("The following game is a clone of the original PONG.")
print("I programmed it to learn pygame and i'm not responsible of what you do with it.")
print("This game is provided as it is.")
print("Author: {}".format("FollowLight"))
print("Date: {}".format("10/12/2014"))
print("-" * 50)
print("CONTROLS")
print("-" * 50)
print("Player1 [LEFT] Controls : UP Arrow - Moving up\t// DOWN Arrow - Moving down.")
print("PLAYER2 [RIGHT] Controls : mouse.")
class Game(object):
def __init__(self, x, y, text_x = 0, text_y = 0):
	 self.x = x
	 self.y = y
	 self.windows_sz = (self.x, self.y) #tuple with the window size
	 #Text position
	 self.text_x = text_x
	 self.text_y = text_y
	 #Score
	 self.score_player1 = 0
	 self.score_player2 = 0
	 #Player1 coords
	 self.dx_p1 = 5
	 self.dy_p1 = 125
	 #Player2 coords
	 self.dx_p2 = 805
	 self.dy_p2 = 125
	 #Ball const
	 self.BALL_x	 = 400
	 self.BALL_y	 = 400
	 self.BALL_velocity = 2
	 self.directionX = 1
	 self.directionY = 1
	 #Color selection
	 self.colors = {
		 "red" : (255, 0, 0),
		 "green" : (0, 255, 0),
		 "blue" : (0, 0, 255),
		 "darkBlue" : (0, 0, 128),
		 "white" : (255, 255, 255),
		 "black" : (0, 0, 0),
		 "pink" : (255, 200, 200)
	 }
	 #Change the cwd to the script current location
	 os.chdir(os.getcwd())
	 #File I/O
	 if not os.path.isfile("highscore.txt"):
		 print("\nhighscore.txt file dosen't exists\nCreating...")
		 open("highscore.txt","w+")
	 else:
		 print("\nFile exists\nSkipping...")
	 #MENU
	 print("\nEnter y for yes or press enter if you don't want that.")
	 self.AI	 = bool(input("Do you want AI?[y - yes / enter - no]: "))
	 self.highSC = bool(input("Do you want to record highscore/score from the game? [y - yes / enter - no]:"))

	 #Init the field
	 self.window = pygame.display.set_mode(self.windows_sz)
	 self.window_sz = self.window.get_size()
	 self.clock	 = pygame.time.Clock()
	 pygame.display.set_caption("Python - PONG")

def PLAYERS(self):
	 while True:
		 #Check for closing
		 for event in pygame.event.get():
			 if event.type == pygame.QUIT:
				
				 if self.highSC:
					 self.highscore()
				 pygame.quit()		 #Close the window
				 sys.exit("Exiting...") #Exit the infinite loop
		 #User input
		 key = pygame.key.get_pressed()
		 if key[pygame.K_UP]:
			 self.dy_p1 -= 7
		 if key[pygame.K_DOWN]:
			 self.dy_p1 += 7
		 #AI Part
		 #This is very rudimentary but it does the job with some problems tho
		 #BUG: the player1 rect will exit out of the screen for a portion if the rect is moving up
		 if self.AI:
			 self.dy_p1 = self.BALL_y - 90
			 self.dy_p2 = self.BALL_y - 90
		 #Fill the screen with the specified color as a tuple
		 self.window.fill(pygame.Color("black"))
		 #Draw a line at the middle of the field
		 pygame.draw.line(self.window, pygame.Color("white"),
							 (self.window_sz[0] - 400, self.window_sz[-1]),
							 (self.window_sz[0] - 400, self.window_sz[-1] - 700))
		 #Display the current fps on the screen
		 self.window.blit(self.font("FPS: {currentFPS}".format(currentFPS = str(self.clock.get_fps()).split(".")[0]),
										 "Arial", 16, 1, pygame.Color("white"), pygame.Color("black")),
							 (self.text_x, self.text_y))
		 #Display the score of the player 1
		 self.window.blit(self.font(str(self.score_player1), "Arial", 22, 1, pygame.Color("white"),
									 pygame.Color("black")),
									 (self.text_x + 200, self.text_y + 10))
		 #Display the score of the player 2
		 self.window.blit(self.font(str(self.score_player2), "Arial", 22, 1, pygame.Color("white"),
									 pygame.Color("black")),
									 (self.text_x + 500, self.text_y + 10))
		 #Limit FPS to 60
		 self.clock.tick(160)
		 #Draw a rectangle
		 player1 = pygame.draw.rect(self.window, self.colors.get("red", "error"), (self.dx_p1, self.dy_p1, 1, 100), 8)
		 #Draw the ball
		 ball = pygame.draw.circle(self.window, self.colors.get("red", "error"), (self.BALL_x, self.BALL_y), 10, 10)
		 #Draw the second player
		 player2 = pygame.draw.rect(self.window, pygame.Color("white"), (self.dx_p2, self.dy_p2, 1, 100), 8)
		 rect_p1 = pygame.Rect(player1)
		 rect_p2 = pygame.Rect(player2)
		 rect_ball = pygame.Rect(ball)
		 if rect_ball.colliderect(rect_p2):
			 self.directionY *= -1
			 self.directionX *= -1
		 if rect_ball.colliderect(rect_p1):
			 self.directionX *= -1
			 self.directionY *= -1
		 self.BALL_x += self.BALL_velocity * self.directionX
		 self.BALL_y += self.BALL_velocity * self.directionY
		 #Limit the movement to the screen limit
		 if self.dy_p1 > (self.window_sz[1] - 100):
			 self.dy_p1 = self.dy_p1 - 7
		 if self.dy_p1 <= 0:
			 self.dy_p1 = 0
		 #Ball bound detection
		 #Only on the y direction
		 if self.BALL_y > 600 or self.BALL_y <= 0:
			 self.directionY *= -1
		 if self.BALL_x > self.window_sz[0]:
			 self.score_player1 += 1
			 #Remove the old one
			 del ball
			 del rect_ball
			 #Re-spawn the ball
			 self.BALL_x = 400
			 self.BALL_y = 400
			 self.BALL_x += self.BALL_velocity * self.directionX
			 self.BALL_y += self.BALL_velocity * self.directionY
		 elif self.BALL_x < 0:
			 self.score_player2 += 1
			 #Remove the old one
			 del ball
			 del rect_ball
			 #Re-spawn the ball
			 self.BALL_x = 400
			 self.BALL_y = 400
			 self.BALL_x += self.BALL_velocity * self.directionX
			 self.BALL_y += self.BALL_velocity * self.directionY
		 #Player 2 check for bounding him to the window bounds
		 mouse_pos = pygame.mouse.get_pos()
		 self.dy_p2 = mouse_pos[1]
		 #Player2 - Mouse bound detection
		 if self.dx_p2 + 10 > self.window_sz[0]:
			 self.dx_p2 = self.window_sz[0] - 5
		 if self.dy_p2 > self.window_sz[1] - 100:
			 self.dy_p2 = self.window_sz[1] - 100
		 pygame.display.update()
def font(self, text = "", font_name = "Arial", size = 24, AA = 1, F_color = (), B_color = ()):
	 """
	 Return a font object witch can be used with blit to output text on the screen
	 """
	 #INIT pygame's font module
	 pygame.font.init()
	 font = pygame.font.SysFont(font_name, size)
	 font = font.render(text, AA, F_color, B_color)
	 return font
def highscore(self):
	 """
	 Search for an highscore.txt file to read/write the scores in it
	 """
	 try:
		 #Write the highscores to the hightscore.txt file
		 with open("highscore.txt", "a") as highFILE:
			 #Get and write the highest score
			 #Also format the things really nicely :)
			 highFILE.write("\n")
			 highFILE.write("\nHighscore: {}\n".format(max(self.score_player1, self.score_player2)))
			 highFILE.write("\n")
			 highFILE.write("-" * 90)
			 highFILE.write("\n")
			 highFILE.write("\nPLAYER1 Score: {}\n".format(self.score_player1))
			 highFILE.write("PLAYER2 Score: {}".format(self.score_player2))
	 except IOError as e : print("Error -> {}".format(e))
	 except Exception as e: print("Error -> {}".format(e))
if __name__ == "__main__":
g = Game(800, 600, 10, 5)
g.PLAYERS()
g.highscore()


Edited by FollowLight, 16 November 2014 - 15:33.


#2
Ombilic

Ombilic

    Member

  • Grup: Members
  • Posts: 641
  • Înscris: 01.04.2011
daca ar fi si identat corect...

#3
FollowLight

FollowLight

    New Member

  • Grup: Members
  • Posts: 14
  • Înscris: 16.11.2014
Problema este de la forum:

http://pastebin.com/DUtRVQng

Anunturi

Chirurgia cranio-cerebrală minim invazivă Chirurgia cranio-cerebrală minim invazivă

Tehnicile minim invazive impun utilizarea unei tehnologii ultramoderne.

Endoscoapele operatorii de diverse tipuri, microscopul operator dedicat, neuronavigația, neuroelectrofiziologia, tehnicile avansate de anestezie, chirurgia cu pacientul treaz reprezintă armamentarium fără de care neurochirurgia prin "gaura cheii" nu ar fi posibilă. Folosind tehnicile de mai sus, tratăm un spectru larg de patologii cranio-cerebrale.

www.neurohope.ro

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Forumul Softpedia foloseste "cookies" pentru a imbunatati experienta utilizatorilor Accept
Pentru detalii si optiuni legate de cookies si datele personale, consultati Politica de utilizare cookies si Politica de confidentialitate