Jul-04-2020, 08:37 PM
Python beginner here. I coded waves / tides washing up on a beach. The "resolution" of the image depends on the value assigned to the "squaresize" variable. It looks much nicer with a lower squaresize, but runs much slower.
Please share tips on how to improve performance!
Please share tips on how to improve performance!
import pygame import random from noise import pnoise2 import math pygame.init() screenwidth = 1000 screenheight = 600 squaresize = 6 xSquares = int(screenwidth / squaresize) ySquares = int(screenheight / squaresize) screen = pygame.display.set_mode((screenwidth,screenheight)) pygame.display.set_caption("Tides") screen.fill((250,250,250)) noiseOffset = random.randint(0, 9999) tideheight = 8 tidespeed = 0.05 wetpersistence = 60 class Terrain: def __init__(self, x, y, size, height): self.x = x self.y = y self.size = size self.height = height self.lastWetCount = -2000 def relativeHeight(self): return self.height + math.sin(count * tidespeed) * tideheight #@property def lastWet(self): if self.relativeHeight() < 0: self.lastWetCount = count return self.lastWetCount def colour(self): if self.relativeHeight() < 0: self.lastWet() if self.relativeHeight() > 0: if count - self.lastWet() > wetpersistence: return (200, 180, 120) else: return (170, 150, 90) elif self.relativeHeight() > -0.6: rand = random.randint(1, 2) if rand == 1: return (190, 210, 230) else: return (220, 240, 250) elif self.relativeHeight() > -1.2: rand = random.randint(1, 2) if rand == 1: return (100, 130, 200) else: return (160, 190, 220) elif self.relativeHeight() > -10: return (60, 90, 190) else: return (50, 60, 180) def genTerrain(): global terrainlist terrainlist = [] for i in range(0, ySquares): for j in range(0, xSquares): terrainlist.append(Terrain(j*squaresize, i*squaresize, squaresize, 0)) for i in range(0, len(terrainlist)): terrainlist[i].height = ((screenheight * 0.4) - terrainlist[i].y) / 10 for i in range(0, len(terrainlist)): terrainlist[i].height += pnoise2((terrainlist[i].x / xSquares) + noiseOffset, (terrainlist[i].y / ySquares) + noiseOffset) * 6 for i in range(0, len(terrainlist)): terrainlist[i].height += pnoise2((terrainlist[i].x / xSquares) * 2 + noiseOffset, (terrainlist[i].y / ySquares) * 2 + noiseOffset) * 3 def drawTerrain(): for i in range(0, len(terrainlist)): pygame.draw.rect(screen, terrainlist[i].colour(), [terrainlist[i].x, terrainlist[i].y, terrainlist[i].size, terrainlist[i].size]) def main(): global count count = -900 running = True genTerrain() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False drawTerrain() pygame.display.update() count += 1 main()