converting an image to a rect - python

this script spawns a alien that follows the player, i just want to know how to make the alien (nPc) and the player (mouse_c) a rect so i make the alien kill the player when the imagers overlap. any help would really help
thanks
import pygame, sys, random, time, math
from pygame.locals import *
pygame.init()
bifl = 'screeing.jpg'
milf = 'character.png'
alien = 'alien_1.png'
screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
nPc = pygame.image.load(alien).convert_alpha()
mouse_c = pygame.Rect((10, 10))
nPc = pygame.Rect((10, 10))
x, y = 0, 0
movex, movey = 0, 0
z, w = random.randint(10, 480), random.randint(10, 640)
movez, movew = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_w:
movey = -4
elif event.key == K_s:
movey = +4
elif event.key == K_a:
movex = -4
elif event.key == K_d:
movex = +4
if event.type == KEYUP:
if event.key == K_w:
movey = 0
elif event.key == K_s:
movey = 0
elif event.key == K_a:
movex = 0
elif event.key == K_d:
movex = 0
if w < x:
movew =+ 0.4
if w > x:
movew =- 0.4
if z < y:
movez =+ 0.4
if z > y:
movez =- 0.4
x += movex
y += movey
w += movew
z += movez
print('charecter pos: ' + str(x) + str(y))
print('alien pos: ' + str(w) + str(z))
chpos = x + y
alpos = w + z
print(alpos, chpos)
screen.blit(background, (0, 0))
screen.blit(mouse_c, (x, y))
screen.blit(nPc, (w, z))
pygame.display.update()

You could use Pygame Sprites
mouse_c = pygame.sprite.Sprite()
mouse_c.image = pygame.image.load(milf).convert_alpha()
mouse_c.rect = mouse_c.image.get_rect()
mouse_c.rect.move_ip(10,10)
nPc = pygame.sprite.Sprite()
nPc.image = pygame.image.load(milf).convert_alpha()
nPc.rect = nPc.image.get_rect()
nPc.rect.move_ip(10,10)
Then blit:
screen.blit(mouse_c.image, mouse_c.rect.topleft)
screen.blit(nPc.image, nPc.rect.topleft)

Related

Can anyone tell me how to increase the snake size in my code?

Here is my code below. Every time when I try to increase the length, It does not seem to increase and when I run the game.
When I run the game, It sometimes makes the head of the snake flicker/blink certain times and when snake eats the food, still it does not increase the length instead of blinking little at certain times
I have attached code with my applied logic. Please is there any solution to this problem?
Here is my code with what I applied as the increase length logic:
Here is my logic:
import pygame
import time
import sys
import random
a = print("1) Easy")
b = print("2) Medium")
c = print("3) Hard")
while True:
difficulty = input("Enter Difficulty Level: ")
if difficulty == "1":
speed = 5
break
elif difficulty == "2":
speed = 6
break
elif difficulty == "3":
speed = 8
else:
print("Choose from Above Options Only!")
# Initialise Game
pygame.init()
clock = pygame.time.Clock()
# Screen and Window Size:
screen_width = 800
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
caption = pygame.display.set_caption("Snake Game")
icon = pygame.image.load("snake.png")
pygame.display.set_icon(icon)
# Colors
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
white = (255, 255, 255)
# Snake Editing
x1 = 350
y1 = 300
snake = pygame.Rect([x1, y1, 20, 20])
x1_change = 0
y1_change = 0
snake_size = 15
snk_list = []
snk_length = 1
# Snake Food
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
food_height = 15
food_width = 15
# Game State
game_over = True
# Game over
font = pygame.font.SysFont("freelansbold.tff", 64)
# Score Counter
score = 0
score_font = pygame.font.SysFont("chiller", 50)
# TO INCREASE SNAKE LENGTH LOGIC:
def plot_snake(gameWindow, color, snk_list, snake_size):
for x, y in snk_list:
pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])
def game_over_text(text, color):
x = font.render(text, True, (240, 0, 0))
screen.blit(x, [screen_width//2 - 135, screen_height//2 - 25])
def score_show():
text = score_font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(text, (20, 10))
def main_loop():
global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size, snk_length
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = speed * -1
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = speed
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = speed * -1
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = speed
x1_change = 0
# Game Over Checking
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over = False
x1 += x1_change
y1 += y1_change
if abs(x1 - food_x) < 7 and abs(y1 - food_y) < 7:
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 0.2
snk_length += 5
# Drawing On Screen
screen.fill((0, 0, 0))
pygame.draw.rect(screen, red, [x1, y1, 15, 15])
pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
score_show()
pygame.display.flip()
#SNAKE LENGTH LOGIC
head = []
head.append(x1)
head.append(y1)
snk_list.append(head)
if len(snk_list) > snk_length:
del snk_list[0]
plot_snake(screen, red, snk_list, snake_size)
# Final Initialisation
pygame.display.flip()
clock.tick(70)
# Main Game Loop
while game_over:
main_loop()
# Game_Over
screen.fill((0, 0, 0))
game_over_text("Game Over!!!", (255, 0, 0))
pygame.display.flip()
time.sleep(2)
pygame.quit()
quit()
The moving distance of the snake must be "snake_size":
def main_loop():
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = snake_size
x1_change = 0
But use pygame.time.Clock to control the frames per second and thus the game speed.
def main_loop():
# [...]
clock.tick(speed)
Use pygame.Rect and collidrect to find the collision of the snake and the food. See also How to detect collisions between two rectangular objects or images in pygame. Increment snk_length, when a collision is detected:
def main_loop():
# [...]
global snk_length
# [...]
snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
if snake_rect.colliderect(food_rect):
snk_length += 1
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 1
Follow the instructions of How do I chain the movement of a snake's body?. Put the new head position of the snake at the head of snk_list, but delete the elements at the tail:
def main_loop():
# [...]
#SNAKE LENGTH LOGIC
snk_list.insert(0, [x1, y1])
if len(snk_list) > snk_length:
del snk_list[-1]
Complete main_loop:
def main_loop():
global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size
global snk_length
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = snake_size
x1_change = 0
# Game Over Checking
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over = False
x1 += x1_change
y1 += y1_change
snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
if snake_rect.colliderect(food_rect):
snk_length += 1
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 1
# Drawing On Screen
screen.fill((0, 0, 0))
pygame.draw.rect(screen, red, [x1, y1, 15, 15])
pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
score_show()
pygame.display.flip()
#SNAKE LENGTH LOGIC
snk_list.insert(0, [x1, y1])
if len(snk_list) > snk_length:
del snk_list[-1]
plot_snake(screen, red, snk_list, snake_size)
# Final Initialisation
pygame.display.flip()
clock.tick(speed)

Pygame malfunctioning

This is a game for teens.
The main guy is displayed well, the time, sound and the background are showing too.
But the bad guys and the key to press to move the bad guy are not working.
# 1 - Importing library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initializing the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = {True, False, False, False}
playerpos =[100,100]
acc = [0,0]
arrows = []
badtimer = 100
badtimer1 = 0
badguys = [[300,100]]
healthvalue = 194
pygame.mixer.init()
# 3 - Loading images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
# 4 - keep looping through
running = 1
exitcode = 0
# 5 - clearing the screen before drawing it again
screen.fill(0)
while running:
badtimer -= 1
for x in range(int(width / grass.get_width() + 1)):
for y in range(int(height / grass.get_height() + 1)):
screen.blit(grass, (x * 100, y * 100))
screen.blit(castle, (0, 30))
screen.blit(castle, (0, 135))
screen.blit(castle, (0, 240))
screen.blit(castle, (0, 345))
# 6.1 - Seting player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26))
playerrot = pygame.transform.rotate(player, 360 - angle * 57.29)
playerpos1 = (playerpos[0] - playerrot.get_rect().width / 10, playerpos[1] - playerrot.get_rect().height / 2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index = 0
velx = math.cos(bullet[0]) * 10
vely = math.sin(bullet[0]) * 10
bullet[1] += velx
bullet[2] += vely
if bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:
arrows.pop(index)
# 6.3.1 - Attack castle
for bullet in arrows:
bullrect = pygame.Rect(arrow.get_rect())
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
acc[0] += 1
badguys.pop(index)
arrows.pop(index1)
index1 += 1
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top = badguy[1]
badrect.left = badguy[0]
if badrect.left < 64:
healthvalue -= random.randint(5, 20)
badguys.pop(index)
# section 6.3.1 after if badrect.left<64:
hit.play()
# section 6.3.2 after if badrect.colliderect(bullrect):
enemy.play()
# 6.3.2 - Check for collisions
index1 = 0
# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
# 6.3.3 - Next bad guy
index += 1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer == 0:
badguys.append([640, random.randint(50, 430)])
badtimer = 100 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
index = 0
for badguy in badguys:
if badguy[0] < -64:
badguys.pop(index)
badguy[0] -= 7
index += 1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks()))+":"+str((pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - updating the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
exit(0)
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
You have wrong indentations.
You check keys inside if event.type == pygame.QUIT: so they are checked only when you close window.
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
# the same indentation like for other event.type
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
# the same indentation like for other event.type
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
# the same indentation like for other event.type
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# it should be outside `for event` loop
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
Similar problem is with drawing badguy.
BTW: instead of all thess settings and checkings of keys you could use pygame.key.get_pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
playerpos[1] -= 5
elif keys[pygame.K_a]:
playerpos[1] += 5
if keys[pygame.K_s]:
playerpos[0] -= 5
elif keys[pygame.K_d]:
playerpos[0] += 5

getting an int from a list (pygame)

i am trying to make a 'snake'-like game in python.
My problem right now is that I can't use the defined values from my 'coinlist' in my for-loop. This is the error that i receive if i execute it: TypeError: 'int' object is not subscriptable. Thanks for your help.
import pygame
import random
pygame.init()
rot = (255,0,0)
grün = (0,255,0)
blau = (0,0,255)
gelb = (255,255,0)
schwarz = (0,0,0)
weiß = (255,255,255)
uhr = pygame.time.Clock()
display = pygame.display.set_mode((800, 600))
pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake')
display.fill(weiß)
def arialmsg(msg, color, x, y, s):
header = pygame.font.SysFont("Arial", s)
text = header.render(msg, True, color)
display.blit(text, [x, y])
def mainloop():
gameExit = False
start = False
movex = 400
movey = 300
changex = 0
changey = -2
rx = random.randrange(10, 790)
ry = random.randrange(10, 590)
snakelist = []
snakelenght = 20
#coinlist defined here:
coinlist = []
while start == False:
display.fill(schwarz)
arialmsg('Snake', grün, 350, 200, 25)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
start = True
pygame.display.flip()
#gameloop:
while gameExit == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
changey = 2
changex = 0
elif event.key == pygame.K_UP:
changey = -2
changex = 0
elif event.key == pygame.K_RIGHT:
changex = 2
changey = 0
elif event.key == pygame.K_LEFT:
changex = -2
changey = 0
movex += changex
movey += changey
snakehead = []
snakehead.append(movex)
snakehead.append(movey)
snakelist.append(snakehead)
display.fill(schwarz)
if len(coinlist) < 1:
rx = random.randrange(10, 790)
ry = random.randrange(10, 590)
coinlist.append(rx)
coinlist.append(ry)
for XY in snakelist:
pygame.draw.circle(display, grün, (XY[0], XY[1]), 10, 10)
for-loop for the coinlist:
for coin in coinlist:
pygame.draw.rect(display, grün, (coin[0], coin[1], 10, 10))
pygame.display.flip()
if snakelenght < len(snakelist):
del snakelist[:1]
if movex >= rx - 19 and movex <= rx + 19 and movey >= ry - 19 and movey <= ry + 19:
del coinlist[:1]
snakelenght += 10
uhr.tick(15)
mainloop()
pygame.quit()
quit()
You're appending ints to coinlist (rx and ry are random ints from 10 to 790/590) and later on you're trying to access elements within coinlist as if they are arrays.
Consider doing something like replacing
coinlist.append(rx)
coinlist.append(ry)
with
coinlist.append([rx,ry])

adding boulders to pygame snake in python

i have a snake game i made in python and i want to add him boulders that will appear every 10 "apples" he gets, so can you help me please? this is the code right now
import pygame
import random
__author__ = 'Kfir_Kahanov'
init = pygame.init()
def quit_game():
"""
this function will quit the game
:return:
"""
pygame.quit()
quit()
# this will set a nice sound when the player gets an apple
BLOP = pygame.mixer.Sound("Blop.wav")
pygame.mixer.Sound.set_volume(BLOP, 1.0)
volume = pygame.mixer.Sound.get_volume(BLOP)
# making colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 155, 0)
BLUE = (0, 0, 255)
YELLOW = (217, 217, 0)
SNAKE_RED = (152, 2, 2)
def display_fill():
"""
this will fill the screen with a color of my choice
:return:
"""
game_display.fill(GREEN)
def mute():
"""
this will mute the game or unmute it
:return:
"""
if volume == 1.0:
pygame.mixer.Sound.set_volume(BLOP, 0.0)
else:
pygame.mixer.Sound.set_volume(BLOP, 10.0)
# all the pygame stuff for the display
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
game_display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The hungry Cobra")
ICON = pygame.image.load("apple_icon.png")
pygame.display.set_icon(ICON)
pygame.display.update()
# deciding on FPS, the size of the snake, apples, and making the fonts for the text
CLOCK = pygame.time.Clock()
BLOCK_SIZE = 20
APPLE_THICKNESS = 30
fps = 15
# BOULDER_THICKNESS = 30
direction = "right" # deciding the starting direction
tiny_font = pygame.font.SysFont("comicsansms", 10)
small_font = pygame.font.SysFont("comicsansms", 25)
med_font = pygame.font.SysFont("comicsansms", 50)
large_font = pygame.font.SysFont("comicsansms", 80)
def text_objects(text, color, size):
"""
defining the text
:param text:
:param color:
:param size:
:return:
"""
global text_surface
if size == "tiny":
text_surface = tiny_font.render(text, True, color)
if size == "small":
text_surface = small_font.render(text, True, color)
if size == "medium":
text_surface = med_font.render(text, True, color)
if size == "large":
text_surface = large_font.render(text, True, color)
return text_surface, text_surface.get_rect()
# loading apple and snake img
IMG = pygame.image.load("snake_head.png")
APPLE_IMG = pygame.image.load("apple_icon.png")
# BOULDER_IMG = pygame.image.load("boulder.png")
def rand_apple_gen():
"""
making apple function
:return:
"""
rand_apple_x = round(random.randrange(10, DISPLAY_WIDTH - APPLE_THICKNESS)) # / 10.0 * 10.0
rand_apple_y = round(random.randrange(10, DISPLAY_HEIGHT - APPLE_THICKNESS)) # / 10.0 * 10.0
return rand_apple_x, rand_apple_y
"""
def rand_boulder_gen():
making the boulder parameters
:return:
rand_boulder_x = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
rand_boulder_y = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
return rand_boulder_x, rand_boulder_y
"""
def message(msg, color, y_displace=0, size="small"):
"""
making a function for the making of the text
:param msg:
:param color:
:param y_displace:
:param size:
:return:
"""
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = ((DISPLAY_WIDTH / 2), (DISPLAY_HEIGHT / 2) + y_displace)
game_display.blit(text_surf, text_rect)
def intro_message():
"""
making the intro
:return:
"""
intro = True
while intro:
display_fill()
message("Welcome to ", BLACK, -200, "large")
message("The hungry Cobra!", BLACK, -100, "large")
message("Eat apples to grow, but be care full", BLACK)
message("if you run into yourself or outside the screen", BLACK, 30)
message("you gonna have a bad time", BLACK, 60)
message("Press S to start or E to exit", BLACK, 90)
message("Created by Kfir Kahanov", BLACK, 200, "tiny")
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_s:
intro = False
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
score_edit = 0
def score_f(score):
"""
making a score_f on the top left
:param score:
:return:
"""
text = small_font.render("Score:" + str(score + score_edit), True, YELLOW)
game_display.blit(text, [0, 0])
def pause_f():
"""
making a pause_f screen
:return:
"""
pause = True
if pause:
message("Paused", RED, -50, "large")
message("Press R to start over, E to exit or C to continue", BLACK)
pygame.display.update()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_c or pygame.K_ESCAPE or pygame.K_p:
pause = False
if event.key == pygame.K_r:
global score_edit, direction, cheat1, cheat4, cheat3, cheat2
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
CLOCK.tick(5)
# making cheats
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
def snake(snake_list):
"""
defining the snake head
:param snake_list:
:return:
"""
global head
if direction == "right":
head = pygame.transform.rotate(IMG, 270)
elif direction == "left":
head = pygame.transform.rotate(IMG, 90)
elif direction == "down":
head = pygame.transform.rotate(IMG, 180)
elif direction == "up":
head = IMG
game_display.blit(head, (snake_list[-1][0], snake_list[-1][1]))
for x_n_y in snake_list[:-1]:
pygame.draw.rect(game_display, SNAKE_RED, [x_n_y[0], x_n_y[1], BLOCK_SIZE, BLOCK_SIZE])
def game_loop():
"""
this will be the game itself
:return:
"""
global cheat1
global cheat2
global cheat3
global cheat4
global direction
global fps
game_exit = False
game_over = False
global score_edit
lead_x = DISPLAY_WIDTH / 2
lead_y = DISPLAY_HEIGHT / 2
# rand_boulder_x, rand_boulder_y = -50, -50
lead_x_change = 10
lead_y_change = 0
snake_list = []
snake_length = 1
rand_apple_x, rand_apple_y = rand_apple_gen()
while not game_exit:
if game_over:
message("Game over!", RED, -50, "large")
message("Press E to exit or R to retry.", BLACK, 20, "medium")
pygame.display.update()
while game_over:
fps = 15
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_e:
game_exit = True
game_over = False
if event.key == pygame.K_r:
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_LEFT and lead_x_change is not BLOCK_SIZE and direction is not "right":
lead_x_change = -BLOCK_SIZE
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT and lead_x_change is not -BLOCK_SIZE and direction is not "left":
lead_x_change = BLOCK_SIZE
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP and lead_y_change is not BLOCK_SIZE and direction is not "down":
lead_y_change = -BLOCK_SIZE
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN and lead_y_change is not -BLOCK_SIZE and direction is not "up":
lead_y_change = BLOCK_SIZE
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_p:
pause_f()
elif event.key == pygame.K_ESCAPE:
pause_f()
elif event.key == pygame.K_k: # the cheat
cheat1 = 0
elif event.key == pygame.K_f:
cheat2 = 4
elif event.key == pygame.K_i:
cheat3 = 0
elif event.key == pygame.K_r:
cheat4 = 3
elif cheat1 == 0 and cheat2 == 4 and cheat3 == 0 and cheat4 == 3:
score_edit = 10000
if lead_x >= DISPLAY_WIDTH or lead_x < 0 or lead_y >= DISPLAY_HEIGHT or lead_y < 0:
game_over = True
lead_x += lead_x_change
lead_y += lead_y_change
display_fill()
game_display.blit(APPLE_IMG, (rand_apple_x, rand_apple_y))
snake_head = [lead_x, lead_y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for eachSegment in snake_list[:-1]:
if eachSegment == snake_head:
game_over = True
snake(snake_list)
score_f(snake_length * 10 - 10)
pygame.display.update()
if rand_apple_x < lead_x < rand_apple_x + APPLE_THICKNESS or rand_apple_x < lead_x + BLOCK_SIZE < rand_apple_x \
+ APPLE_THICKNESS:
if rand_apple_y < lead_y < rand_apple_y + APPLE_THICKNESS or rand_apple_y < lead_y + BLOCK_SIZE < \
rand_apple_y + APPLE_THICKNESS:
pygame.mixer.Sound.play(BLOP)
rand_apple_x, rand_apple_y = rand_apple_gen()
snake_length += 1
fps += 0.15
"""
if snake_length * 10 - 10 == 20:
rand_boulder_x, rand_boulder_y = rand_boulder_gen()
game_display.blit(BOULDER_IMG, (rand_boulder_x, rand_boulder_y))
elif rand_boulder_x < lead_x < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_x < lead_x + BLOCK_SIZE < \
rand_boulder_x + BOULDER_THICKNESS:
if rand_boulder_x < lead_y < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_y < lead_y + BLOCK_SIZE < \
rand_boulder_y + BOULDER_THICKNESS:
game_over = True
"""
CLOCK.tick(fps)
display_fill()
pygame.display.update()
quit_game()
intro_message()
game_loop()
Maybe try explaining what you have tried and why it isn't working. You would get better help that way.
From what I can see from your code though....
You seem to be on the right track in your commented out code. Evaluating the snake length or score variable during your game loop, then generating a random boulder to the screen. The next step is just handling the collision logic for all the boulders, which I see two ways of doing. First way is creating a lists of the boulder attributes like the x,y positions, similar to how you did the snake list. The second way would be to create a class for boulders, then when the score, or snake length, reaches 10, create a new boulder object. Using a class may make the collision logic much easier to handle.

Python sprite not moving when key is held down

I'm working on the basics of a game right now, but for some reason I cannot get my sprite to move. I know that it's registering when I'm pressing the key down, but the sprite for some reason just stays still.
import pygame
import sys
from pygame.locals import *
import time
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("RADICAL")
screen.fill(black)
imga = pygame.image.load('coina.png')
imgb = pygame.image.load('coinb.png')
sound = pygame.mixer.Sound('coin.mp3')
FPS = 80
imgx = 10
imgy = 10
pixMove = 10
steps = 0
x1 = 0
y1 = 0
keystate = pygame.key.get_pressed()
GameOver = False
while not GameOver:
screen.fill(white)
points = (steps)
font = pygame.font.SysFont(None, 30)
text = font.render('Score: '+str(points), True, black)
screen.blit(text, (0,0))
if steps % 2 == 0:
screen.blit(imga, (imgx, imgy))
else:
screen.blit(imgb, (imgx, imgy))
for event in pygame.event.get():
print event
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if keystate[pygame.K_UP]:
y1 -= pixMove
elif keystate[pygame.K_DOWN]:
y1 += pixMove
elif keystate[pygame.K_LEFT]:
x1 -= pixMove
elif keystate[pygame.K_RIGHT]:
x1 += pixMove
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x1 = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y1 = 0
steps +=1
if event.type == K_SPACE:
sound.play()
time.sleep(1)
sound.stop()
pygame.display.update()
fpsTime.tick(FPS)
Generally you blit() images on to the screen (pygame.display.set_mode()), for the changes to to reflect on the screen we call pygame.display.update(), In your case the game never comes the statement, which is out of while loop.

Categories

Resources