Game crashes when reaching "while creating:" loop [duplicate] - python

This question already has answers here:
Pygame unresponsive display
(1 answer)
Pygame window not responding after a few seconds
(3 answers)
Closed 2 years ago.
The Title says it all.
import pygame
import os
pygame.init()
displayWidth = 1280
displayHeight = 720
black = (0,0,0)
white = (255,255,255)
# Defining variables that determine what points the code has reached.
Running = True
intro = True
menu = True
gender = True
charactercreation = True
genderpicked = False
mcgender = "Null"
displaycharactercreation = True # Defining a loop so that the character creation screen doesn't jitter, blitting multiple times.
creating_character = True
creating = True
event = pygame.event.wait()
key = pygame.key.get_pressed()
n = 1
# Defining a textbox maker
def text_objects(text, font, colour):
textSurface = font.render(text, True, colour)
return textSurface, textSurface.get_rect()
# Defining a fade function
def fade(direction):
if direction == "Out":
black = (0, 0, 0)
fade_opacity = 0
fading = True
while fading:
fade_opacity += 1
fadeshape = pygame.Surface((1280, 720))
fadeshape.set_alpha(fade_opacity)
fadeshape.fill(black)
display.blit(fadeshape, (0,0))
pygame.display.update()
if fade_opacity == 100:
fading = False
elif direction == "In":
black = (0, 0, 0)
fade_opacity = 255
fading = True
while fading:
fade_opacity -= 1
fadeshape = pygame.Surface((1280,720))
fadeshape.set_alpha(fade_opacity)
fadeshape.fill(black)
display.blit(fadeshape, (0,0))
pygame.display.update()
if fade_opacity == 0:
fading = False
# Creating window and defining images
display = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption("Blazing Badge")
clock = pygame.time.Clock()
warriorImage = pygame.image.load("warrior.png")
grassImage = pygame.image.load("grass.png")
playButton = pygame.image.load("play button.png")
durandal = pygame.image.load("durandal.png")
mainscreen = pygame.image.load("mainmenu.jpg")
logo = pygame.image.load("logo.png")
arrow = pygame.image.load(os.path.join("graphics", "left_arrow.png"))
pygame.display.set_icon(durandal) # Setting the Window Icon
while Running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
mouse = pygame.mouse.get_pos()
pressed = pygame.mouse.get_pressed()
# Main menu follows ----------------
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
display.fill(white)
largeText = pygame.font.Font("The Fighter.otf", 115)
TextSurf, TextRect = text_objects("Tech Demo", largeText, black)
TextSurf = pygame.transform.rotate(TextSurf, 15)
TextRect.center = ((displayWidth*0.68), (displayHeight*0.4))
playpos = (((displayWidth/2)-100), (displayHeight)*0.7)
durandalpos = (((displayWidth/2)-280), (displayHeight*0.2))
display.blit(mainscreen, (0,0))
display.blit(playButton, playpos)
durandalresized = pygame.transform.scale(durandal, (561, 333))
display.blit(durandalresized, durandalpos)
display.blit(logo, ((displayWidth*0.2), (displayHeight*0.35)))
display.blit(TextSurf, TextRect)
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
print(mouse)
if 580 < mouse[0] < 710 and 532 < mouse[1] < 674:
if click[0] == 1:
print("Start Game")
fade(direction="Out")
menu = False
pygame.display.update()
clock.tick(15)
print("I have broken out of the main menu loop.")
while charactercreation:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gender_symbols = pygame.image.load(os.path.join("graphics\Character Creation", "Gender Symbols.png"))
creation_background = pygame.image.load(os.path.join("graphics\Character Creation", "creationbackground.jpg"))
TextSurf, TextRect = text_objects("Choose your gender", pygame.font.Font("The Fighter.otf", 115), white)
display.blit(creation_background, (0, 0))
display.blit(TextSurf, (((1280 / 2) - 500), displayHeight * 0.1))
display.blit(gender_symbols, (340, (displayHeight * 0.6)))
pygame.display.update()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
charactercreation = False
print("I have broken out of the character creation loop.")
while genderpicked == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 365 < mouse[0] < 602 and 457 < mouse[1] < 702 and click[0] == 1:
mcgender = "Female"
genderpicked = True
print(mcgender)
elif 457 < mouse[1] < 702 and 677 < mouse[0] < 916 and click[0] == 1:
mcgender = "Male"
genderpicked = True
print(mcgender)
print("I have broken out of the gender picking loop.")
while displaycharactercreation:
display.blit(creation_background, (0, 0))
pygame.display.update()
print(mcgender)
if mcgender == "Male":
gendercolour = (0, 128, 255)
elif mcgender == "Female":
gendercolour = (255, 0, 127)
else:
gendercolour = white
# Creating the prompts for the creation screen.
LetterQ1, LetterQ2 = text_objects("<- Q", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterQ1, (100, 50))
LetterE1, LetterE2 = text_objects("E->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterE1, (1080, 50))
LetterA1, LetterA2 = text_objects("<- A", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterA1,(100, 310))
LetterD1, LetterD2 = text_objects("D ->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterD1, (1080, 310))
LetterZ1, LetterZ2 = text_objects("<- Z", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterZ1, (100, 570))
LetterC1, LetterC2 = text_objects("C ->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterC1, (1080, 570))
pygame.display.update() # Applying all of the prompts
displaycharactercreation = False
print("I have stopped displaying the prompts for character creation")
while creating_character:
if mcgender == "Male":
print("I have reached male")
while creating:
print("I have reached creation loop male")
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
This is the code so far, running python and pygame. Sorry if the code is just a bit all over the place, it's how I'm used to coding,
When reaching this point:
while creating_character:
if mcgender == "Male":
print("I have reached male")
while creating:
print("I have reached creation loop male")
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
if key[pygame.K_RETURN]:
creating = False
creating_character = False
The code crashes and the window begins not responding past the point of while creating: I still get the interpreter returning "I have reached creation loop male", over and over again.

The code does not crash, but it is not responding, because the event handling is missing.
The array of key states, which is returned by pygame.key.get_pressed(), is evaluated when the events are handled by either pygame.event.pump() or pygame.event.get(). When a keyboard event occurse, then the internal states of the key is updated and pygame.key.get_pressed() can return the new states.
Call pygame.event.pump() in the inner loop:
while creating:
# handle events
pygame.event.pump()
print("I have reached creation loop male")
# get the current key states
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
if key[pygame.K_RETURN]:
creating = False
creating_character = False

your variable "creating" contains true and isn't changed anywhere, so you have an infinite while true loop.

Related

Pygame makes the game unplayable with lag

I am making a game where you just click on the circles, and i just got it working when i noticed the game really laggs out sometimes. It just would not generate new position. This is my code:
import pygame
from pygame.font import SysFont
from pygame.display import flip
from random import randint, choice
# Bools
r = True
title = True
game = False
# Floats
# Ints
points = 0
deletewhat = [True, False]
# Strings
# Lists
spots = []
pointchoice = [1,1,1,2]
# Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
GRAY = (20,20,20)
# Pygame init
pygame.init()
pygame.font.init()
# Pygame userevents
delete = pygame.USEREVENT
# Pygame timers
pygame.time.set_timer(delete, 1000)
# Pygame Fonts
titlefont = SysFont("Arial", 70)
headfont = SysFont("Arial", 20)
startfont = SysFont("Arial", 80)
pointsfont = SysFont("Arial", 25)
# Pygame font one-time render
titletext = titlefont.render("The Spot Spotter", False, BLACK)
headtext = headfont.render("Click the spots and earn points!", False, BLACK)
starttext = startfont.render("START", False, RED)
# Other Pygame things
screen = pygame.display.set_mode((900,750))
class Spot:
def __init__(self, x, y, points):
global WHITE, GRAY
self.x = x
self.y = y
self.points = points
if self.points == 1:
self.spotcolor = WHITE
else:
self.spotcolor = GRAY
def draw(self):
pygame.draw.ellipse(screen, self.spotcolor, (self.x, self.y, 50,50))
def get_pos(self):
return self.x, self.y
def get_points(self):
return self.points
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
deleteone = choice(deletewhat)
if deleteone:
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
if mouse[0] > 249 and mouse[0] < 801:
if mouse[1] > 299 and mouse[1] < 426:
if title:
title = False
game = True
try:
spot1.get_pos()
except NameError:
pass
else:
spot1pos = spot1.get_pos()
if mouse[0] > (spot1pos[0] - 1) and mouse[0] < (spot1pos[0] + 51):
if mouse[1] > (spot1pos[1] - 1) and mouse[1] < (spot1pos[1] + 51):
if spot1ready:
spot1ready = False
points += spot1.get_points()
try:
spot2.get_pos()
except NameError:
pass
else:
spot2pos = spot2.get_pos()
if mouse[0] > (spot2pos[0] - 1) and mouse[0] < (spot2pos[0] + 51):
if mouse[1] > (spot2pos[1] - 1) and mouse[1] < (spot2pos[1] + 51):
if spot2ready:
spot2ready = False
points += spot2.get_points()
if title:
screen.fill(WHITE)
screen.blit(titletext, (250, 0))
screen.blit(headtext, (350, 100))
pygame.draw.rect(screen, YELLOW, (200, 300, 550, 125)) # Start Button
screen.blit(starttext, (375, 315))
flip()
elif game:
pointstext = pointsfont.render(f"Points: {points}", False, BLACK)
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, (0, 600, 900, 150))
screen.blit(pointstext, (20, 610))
try:
spot1.draw()
except NameError:
pass
else:
spot1.draw()
try:
spot2.draw()
except NameError:
pass
else:
spot2.draw()
flip()
pygame.quit()
If you are wondering, the bools game and title are both for detecting which tab needs to be rendered. if game is true and title is false then the game knows hey, i need to render the game.
Also please note that i am not that good in pygame.
The problem is the line deleteone = choice(deletewhat). This may generate multiple False in a row.
Add a variable wait_delete. Decrement the variable when the delete event occurs. Set a new random value with randint if wait_delete is 0.
wait_delete = 1
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
wait_delete -= 1
if wait_delete == 0:
wait_delete = randint(1, 3)
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
# [...]

Python helicopter game does not update score

as part of my Pygame learning course I have to create simple helicopter game, similar to flappy bird.
It also should have a score count - so everytime you pass gap between blocks with helicopter the score should add 1.
Game logic and everything else works fine, except everytime helicopter pases thru the blocks the score is not added, so all the time score shows 0.
Below is the code, can anyone please help
import pygame
import time
from random import randint
black = (0,0,0)
white = (255,255,255)
pygame.init()
surfaceWidth = 1280
surfaceHeight = 720
imageHeight = 30
imageWidth = 60
surface = pygame.display.set_mode((surfaceWidth,surfaceHeight))
pygame.display.set_caption('EVGENY GAME')
#clock = frames per second
clock = pygame.time.Clock()
img = pygame.image.load('Helicopter.jpg')
def score(count):
font = pygame.font.Font('freesansbold.ttf', 20)
text = font.render("Score: "+str(count), True, white)
surface.blit(text, [0,0])
def blocks(x_block, y_block, block_width, block_height, gap):
pygame.draw.rect(surface, white, [x_block, y_block, block_width, block_height])
pygame.draw.rect(surface, white, [x_block, y_block+block_height+gap, block_width, surfaceHeight])
def replay_or_quit():
for event in pygame.event.get([pygame.KEYDOWN, pygame.KEYUP, pygame.QUIT]):
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
continue
return event.key
return None
def makeTextObjs(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def msgSurface(text):
smallText = pygame.font.Font('freesansbold.ttf', 20)
largeText = pygame.font.Font('freesansbold.ttf', 150)
titleTextSurf, titleTextRect = makeTextObjs(text, largeText)
titleTextRect.center = surfaceWidth / 2, surfaceHeight / 2
surface.blit(titleTextSurf, titleTextRect)
typTextSurf, typTextRect = makeTextObjs('Press any key to continue', smallText)
typTextRect.center = surfaceWidth / 2, ((surfaceHeight / 2) + 100)
surface.blit(typTextSurf, typTextRect)
pygame.display.update()
time.sleep(1)
while replay_or_quit() == None:
clock.tick()
main()
def gameover():
msgSurface('GAME OVER')
def helicopter(x, y, image):
surface.blit(img, (x,y,))
# first constance = game over, while not true we are playing game
def main():
x = 50
y = 100
y_move = 0
x_block = surfaceWidth
y_block = 0
block_width = 100
block_height = randint(0, surfaceHeight/2)
gap = imageHeight * 8
block_move = 3
current_score = 0
game_over = False
while not game_over:#this will keep running until it hits pygame.quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_move = -10
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_move = 5
y += y_move
surface.fill(black)
helicopter(x,y,img)
score(current_score)
blocks(x_block, y_block, block_width, block_height, gap)
x_block -= block_move
if y > surfaceHeight-40 or y < 0:
gameover()
if x_block < (-1*block_width):
x_block = surfaceWidth
block_height = randint(0, surfaceHeight/2)
if x + imageWidth > x_block:
if x < x_block + block_width:
if y < block_height:
if x - imageWidth < block_width + x_block:
gameover()
if x + imageWidth > x_block:
if y + imageHeight > block_height+gap:
gameover()
if x < x_block and x > x_block-block_move:
current_score += 1
pygame.display.update()#update, updates specific area on display, flip - updates whole display
clock.tick(100)#100 frames per second
main()
pygame.quit()
quit() enter code here
Your score counter never updates because your score counter condition is never reached. Change
if x < x_block and x > x_block-block_move:
to
if x_block >= x > x_block-block_move:

Pygame Snake - Apple spawning inside snake

i'm learning how to make a snake game in pygame from the thenewboston tutorials on youtube and make it my own.
There's a problem in the game where the 'apple' spawns behind the snake's position which is something that i don't want.
I'm sure i have to state that apple position can't be the same as the snake but can't figure it out how:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
Full code:
import pygame
import random
pygame.init()
# Game Title
pygame.display.set_caption("Original Snake")
# Game display 4:3
screen_w = 640
screen_h = 480
surface = pygame.display.set_mode((screen_w, screen_h))
bg_color = (170, 204, 102)
box_color = (43, 51, 26)
box_size = screen_h / 24
# PLAYING FIELD
field_x = screen_w - (box_size*2)
field_y = screen_h - (box_size*2)
# Frames per Second
clock = pygame.time.Clock()
FPS = 8
# Font settings
kongtext = "C:\Windows\Fonts\kongtext.ttf"
verysmall = pygame.font.Font(kongtext, 12)
small = pygame.font.Font(kongtext, 15)
medium = pygame.font.Font(kongtext, 30)
large = pygame.font.Font(kongtext, 60)
verylarge = pygame.font.Font(kongtext, 80)
# sound settings
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
eat_apple_sound = pygame.mixer.Sound("sounds/eat_apple.wav")
def snake(box_size, snakelist):
for XnY in snakelist:
pygame.draw.rect(surface, box_color, [XnY[0], XnY[1], box_size, box_size])
# Text Object
def text_objects(text, color, size):
if size == "small":
text_surface = small.render(text, True, color)
elif size == "verysmall":
text_surface = verysmall.render(text, True, color)
elif size == "medium":
text_surface = medium.render(text, True, color)
elif size == "large":
text_surface = large.render(text, True, color)
elif size == "verylarge":
text_surface = large.render(text, True, color)
return text_surface, text_surface.get_rect()
# Start screen
def start_screen():
intro = True
while intro:
# IF USER CLICKS ON THE X
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Start Game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
intro = False
surface.fill(bg_color)
# SCREEN FIELD WITH BORDER 3
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# START SCREEN
message_to_screen("SNAKE", box_color, -25, size="verylarge")
message_to_screen("PRESS SPACE TO PLAY", box_color, 35, size="verysmall")
pygame.display.update()
clock.tick(15)
# Message to screen
def message_to_screen(msg, color, text_y_pos=0, size="small"):
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = (screen_w / 2), (screen_h / 2)+text_y_pos
surface.blit(text_surf, text_rect)
def score(score):
text = small.render("Score: "+str((score*10)-20), True, box_color)
surface.blit(text, [box_size, screen_h-box_size-7])
def game_loop():
direction = "right"
quit_game = False
game_over = False
# Box settings
box_color = (43, 51, 26)
# Defining snake position
snakelist = []
snakelength = 3
snake_x_pos = screen_w / 2
snake_y_pos= screen_h / 2
snake_x_chg = box_size
snake_y_chg = 0
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
while not quit_game:
# Game Over
while game_over:
surface.fill(bg_color)
message_to_screen("GAME OVER", box_color, -10, size="large")
message_to_screen("PRESS SPACE TO PLAY AGAIN OR Q TO QUIT", box_color, 50, size="small")
# PLAYING FIELD
pygame.draw.rect(surface, box_color,
[16, 16, screen_w - 33, screen_h - 33 - box_size], 3)
# SCORE
score(snakelength - 1)
pygame.display.update()
# Closing Game Over screen with X
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Closing Game Over screen with Q or Restart with space
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
quit_game = True
game_over = False
if event.key == pygame.K_SPACE:
direction = "right"
game_loop()
for event in pygame.event.get():
# Closing the game
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Controlling the snake
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT) and direction != "right":
snake_x_chg = -box_size
snake_y_chg = 0
direction = "left"
elif (event.key == pygame.K_RIGHT) and direction != "left":
snake_x_chg = box_size
snake_y_chg = 0
direction = "right"
elif (event.key == pygame.K_UP) and direction != "down":
snake_y_chg = -box_size
snake_x_chg = 0
direction = "up"
elif (event.key == pygame.K_DOWN) and direction != "up":
snake_y_chg = box_size
snake_x_chg = 0
direction = "down"
# Screen boundaries
if snake_x_pos > (field_x) or snake_x_pos < box_size or snake_y_pos > (field_y) or snake_y_pos < box_size:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
# Snake new position
snake_x_pos += snake_x_chg
snake_y_pos += snake_y_chg
# Clear screen
surface.fill(bg_color)
# Draw and update
pygame.draw.rect(surface, box_color, [apple_x, apple_y, box_size, box_size])
snakehead = []
snakehead.append(snake_x_pos)
snakehead.append(snake_y_pos)
snakelist.append(snakehead)
if len(snakelist) > snakelength:
del snakelist[0]
for snaketail in snakelist[:-1]:
if snaketail == snakehead:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
snake(box_size, snakelist)
# PLAYING FIELD
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# SCORE
score(snakelength-1)
pygame.display.update()
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
clock.tick(FPS)
pygame.quit()
quit()
start_screen()
game_loop()
Create a rectangle at the new random "apple" position:
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
Check for each position (pos) in snakelist if the "apple" rectangle collides with the part of the snake by pygame.Rect.collidepoint:
apple_rect.collidepoint(*pos)
Use any() to check if the apple "collides" with any part of the snake:
any(apple_rect.collidepoint(*pos) for pos in snakelist)
If the apple "collides" with the snake the create a new random point and repeat the process:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
while True:
apple_x, apple_y = (random.randrange(box_size, fs, box_size) for fs in (field_x, field_y))
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
if not any(apple_rect.collidepoint(*pos) for pos in snakelist):
break
The snake seems to be a list of "boxes", held in the list snakelist. So to ensure the apple does not appear inside the parts of the snake, the generated random point needs to be created outside the snake's boxes.
A simple (but inefficient) way to do this is to keep generating random points, and testing them for collision.
collision = True
while collision == True:
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
# Check apple not within snake
collision = False
for XnY in snakelist:
part = pygame.Rect( XnY[0], XnY[1], box_size, box_size )
# is the apple-point within the snake part?
if part.collidepoint( apple_x, apple_y ) == True:
collision = True
break # any collision is final, stop checking
It would be worth thinking of a more efficient way to move the point away from the snake instead of looping over-and-over. Picking a random point may simply pick the same point, or a near-by bad point again. Also the longer the snake gets, the worse this looping will be as there are less "non-snake" points on the screen. I guess there's some known safe-spots, like the space the snake just moved out of, but these are obviously not random.

Python flask game not initializing

I have my flask file and a seperate file which contains a pygame. Both work seperately, How would i combine the flask so that when i press my link on my webpage it starts running the external file, how would I call it?
from flask import Flask, render_template
import going
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/my-link/')
def my_link():
return going.main()
if __name__ == '__main__':
app.run(debug=True)
At the moment I am trying to run the main() method to initialize the program.
import pygame
##1100 * 800
size = [1100, 800]
score1 = 0
score2 = 0
blue = (100, 149, 237)
black = (0, 0, 0)
brown = (165,42,42)
white = (255, 255, 255)
green =(0,100,0)
red = (255,0,0)
dark_red = (200,0,0)
grey = (100,100,100)
other_grey = (0,0,100)
background = 'Mahogany.jpg'
pass_count = 0
player = 1
clock = pygame.time.Clock()
class Player(object):
def ___init__(self,id):
self.id = 1
def quitGame(self):
pygame.quit()
quit()
def pass_turn(self):
global pass_count
pass_count += 1
if pass_count == 2:
quitGame()
def score(player_text, score):
return player_text + str(score)
class Stone(object):
def __init__(self,board,position,color):
self.board = board
self.position = position
self.color = color
self.placeStone()
def placeStone(self):
coords = (self.position[0] * 50, self.position[1] * 50)
pygame.draw.circle(self.board,self.color,coords,20,0)
pygame.display.update()
class Board(object):
def draw_board(self):
for i in range(12):
for j in range(12):
rect = pygame.Rect(55 + (50 * i), 100 + (50 * j), 50, 50)
pygame.draw.rect(background, blue, rect, 1)
screen.blit(background, (0,0))
pygame.display.update()
def text_objects(self,text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(self,msg,x,y,w,h,ic,ac,action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = self.text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
screen.blit(textSurf, textRect)
def game_intro(self):
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(background, (0,0))
largeText = pygame.font.SysFont("comicsansms",60)
TextSurf, TextRect = self.text_objects("GONLINE", largeText)
TextRect.center = ((1100/2),(800/2))
screen.blit(TextSurf, TextRect)
self.button("Play!",200,500,100,100,grey,other_grey,self.play_game)
self.button("Quit!",700,500,100,100,red,dark_red,Player.quitGame)
pygame.display.update()
clock.tick(15)
def play_game(self):
width = 20
height = 20
space_between = 5
global player
finish = False
self.draw_board()
while not finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
elif event.type == pygame.MOUSEBUTTONDOWN and player == 1:
position = pygame.mouse.get_pos()
if (event.button == 1) and (position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1]) / 50.0), 0))
Stone(screen,(x,y),white)
player = 2
elif event.type == pygame.MOUSEBUTTONDOWN and player == 2:
position = pygame.mouse.get_pos()
if (event.button == 1) and(position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1] ) / 50.0), 0))
Stone(screen,(x,y),black)
player = 1
clock.tick(60)
self.button("Pass!",750,200,100,100,grey,other_grey,Player.pass_turn)
self.button("Quit!",950,200,100,100,red,dark_red,Player.quitGame)
self.button(score("Player 1: ", score1),750,400,300,110,white,white)
self.button(score("Player 2: ",score2),750,600,300,110,white, white)
pygame.display.update()
pygame.quit()
def main():
player = Player()
board = Board()
board.game_intro()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
Here is the main game file
It seems that the two ways you try to call your game are slightly different.
The successful way, which seems to be something like
$ python going.py
runs this code
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
The flask route, when triggered runs this
return going.main()
You're missing some setup. My guess is that the bottom of your going.py should look like this.
def main():
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
player = Player()
board = Board()
board.game_intro()
if __name__ == '__main__':
main()

What syntax am I not seeing or entering correctly via python?

I've been learning Python the easy (for me) way: simple video game example tutorials from sentdex on youtube. The concepts which I had not already known are made much clearer in the context of something for which I see value like a simple game. Anyway, I have come to an issue; for some reason, I cannot get a menu page to blit. I originally followed the tutorial very closely, with an eye for punctuation, capitalization and proper indentation as I see that seems to be the n00bs most consistent pitfall. However, the tutorial did not work for that section, and the program goes right into the game loop, even when game over. I have tried other methods prescribed throughout here, google, and youtube, but nothing seems to be working! I get a non-descriptive "syntax error", but as far as I can tell, the vital bits are wired up right. I'm sure I'm just being a blind noob, but some simple analysis would be much appreciated on this code!
NOTE: I know I have some danglers like how I imported Pickle but haven't used it yet, those are all just reminders for the next steps, soon to be fleshed out as soon as this menu problem is resolved.
Running python (with pygame) 2.7, since I cant get pygame to work on python 3.
I have both Eric5 and pycharm, I am running Debian Jessie with a backported Cinnamon (And I believe the kernel to, but I might be wrong)
#!/urs/bin/python2.7
import random
import pygame
import time
##import pickle
pygame.init()
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Zoomin' Zigs")
#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
#asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
menuactive = True
#FUNCTIONS
##def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
##def leftclick():
##
## if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
## mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades (smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
time.sleep(3)
menuscreen()
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
if x+w > mousecoords[0] > x and y+h > mousecoords[1] >y:
pygame.quit()
quit()
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, blue)
gamedisplay.blit(text, (30,100))
################################MENU###################################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
else:
time.sleep(3)
game_loop()
gamedisplay.blit(menuimage (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP###############################################
def game_loop():
#CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
#SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
while not menuactive:
for event in pygame.event.get():
# GAME QUIT EVENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades (smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
#OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
#DODGE COUNT
dodged += 1
#CRASHESloop
if y <= smbar_starty+smbar_height and y >= smbar_starty+smbar_height and x <= smbar_startx+car_width and x >= smbar_startx-car_width:
crash()
menuactive = True
pygame.display.update()
clock.tick(60)
########################################################################################
menuscreen()
game_loop()
pygame.quit()
quit()
Hey I saw your code and did necessary changes And Its Working now next time kindly provide us the whole details.
#!/urs/bin/python2.7
import random
import pygame
import time
# import pickle
menuactive = True
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Zoomin' Zigs")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
# asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
# FUNCTIONS
# def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
# def leftclick():
##
# if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades(smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
# menuscreen()
# def button(x, y, w, h,):
# mousecoords = pygame.mouse.get_pos()
# if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
# pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x + w > mousecoords[0] > x and y + h > mousecoords[1] > y:
# pygame.quit()
# quit()
global menuactive
menuactive = False
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, blue)
gamedisplay.blit(text, (30, 100))
################################MENU######################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
global menuactive
while menuactive:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
menuactive = False
else:
# time.sleep(3)
game_loop()
gamedisplay.blit(menuimage, (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP#################################
def game_loop():
# CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
# SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
global menuactive
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit()
menuactive = False
# CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades(smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
# OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
# DODGE COUNT
dodged += 1
# CRASHESloop
if y <= smbar_starty + smbar_height and y >= smbar_starty + smbar_height and x <= smbar_startx + car_width and x >= smbar_startx - car_width:
crash()
menuactive = False
pygame.display.update()
clock.tick(60)
##########################################################################
if __name__ == '__main__':
pygame.init()
menuscreen()
# game_loop()
pygame.quit()
quit()

Categories

Resources