Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Cockroach help
#1
Hello guys, I'm getting started with pygame and python and trying to to rewrite one of my previous codes. Basically it's a very simple game, where the object(cockroach. For now it's just a square) is running across the field and has some chance to turn left or right in process, but he can't go backwards. Also he leaves a trace of it's way. Now I want to make it better, so I'm trying to make cockroach run when player presses any button(up, down, left or right arrows) or when player moves the mouse. If you can help me, I'll be very thankfull. Below I'll post my python code and what I've written with pygame

default python
from random import randint
import time
import os
 
pos = [10,10]
 
direction = 'up'
 
step = 0
full_way = []
way = [[0 for y in range(21)]for x in range(21)]
 
while step < 40:
    if direction == 'up':
        pos[0] -= 1
    if direction == 'down':
        pos[0] += 1
    if direction == 'left':
        pos[1] -= 1
    if direction == 'right':
        pos[1] += 1
 
    if pos[0] > 20:
        pos[0] = 0
    if pos[0] < 0:
        pos[0] = 20
    if pos[1] > 20:
        pos[1] = 0
    if pos[1] < 0:
        pos[1] = 20
 
    chance = randint(1, 10)
    if chance == 2 or chance == 8:
        if direction in 'up':
            direction = ['left', 'right'][randint(0,1)]
        elif direction in ['left', 'right']:
            direction = 'up'
 
    way[pos[0]][pos[1]] = 1
    print('\n'.join([' '.join([str(cell) for cell in row]) for row in way]))
    print('---------------------------------------------')
    clear = lambda: os.system('cls')#Очистка
    #time.sleep(1) #To check a result with each step
    full_way.append((pos[0],pos[1]))#Add a coordinate to the list
    step += 1 #New step
    print(full_way)#List with coodinates


pygame
import pygame
from random import randint
pygame.init()

screen_width, screen_heigth = 640, 640
screen = pygame.display.set_mode((screen_width, screen_heigth)) #окно игры

x = screen_width /2
y = screen_heigth/2


direction = 'up'
width = 10
heigth = 10
speed = 10
step = 0
runtime = True

while runtime:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			runtime = False
	keys = pygame.key.get_pressed()

	while step < 40:
		if direction == 'up':
			y -= speed
		if direction == 'down':
			y += speed
		if direction == 'left':
			x -= speed
		if direction == 'right':
			x += speed

		if y > screen_heigth:
			y = 0
		if y < 0:
			y = screen_heigth - heigth
		if x > screen_width:
			x = 0
		if x < 0:
			x = screen_width - width
		chance = randint(1, 10)
		if chance == 2 or chance == 8:
			if direction in 'up':
				direction == ['left', 'right'][randint(0,1)]
			elif direction in ['left', 'right']:
				direction = 'up'
		step += 1

	screen.fill((0,0,0))
	pygame.draw.rect(screen, (255,255,0), (x, y, width, heigth))
	pygame.display.update()
	pygame.display.flip()

pygame.QUIT()
Reply
#2
Maybe increase your python skills first. Learn to use classes.
Using classes can make code more readable and easier to program.

example
import pygame
from random import randint
pygame.init()

class Roach:
    def __init__(self):
        self.rect = pygame.Rect(Game.screen.centerx, Game.screen.centery, 10, 10)
        self.direction = 'up'
        self.speed = 10
        self.step = 0
        self.tick = pygame.time.get_ticks() + 100

    def update(self, tick):
        if tick > self.tick:
            self.tick += randint(90, 110)
            if randint(1,10) in [2, 8]:
                if self.direction in ['up', 'down']:
                    self.direction = ['left', 'right'][randint(0,1)]
                else:
                    self.direction = ['up', 'down'][randint(0,1)]

            if self.direction == 'up':
                self.rect.y -= self.speed
            elif self.direction == 'left':
                self.rect.x -= self.speed
            elif self.direction == 'right':
                self.rect.x += self.speed
            elif self.direction == 'down':
                self.rect.y += self.speed

            self.rect.clamp_ip(Game.screen)

    def draw(self, surface):
        pygame.draw.rect(surface, (255,255,0), self.rect)

class Game:
    screen = pygame.Rect(0,0,640,640)

    def __init__(self, caption):
        pygame.display.set_caption(caption)
        self.surface = pygame.display.set_mode(Game.screen.size)
        self.clock = pygame.time.Clock()
        self.roach = Roach()

    def loop(self):
        self.running = True
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False

            tick = pygame.time.get_ticks()
            self.roach.update(tick)

            self.surface.fill((0,0,0))
            self.roach.draw(self.surface)
            pygame.display.flip()
            self.clock.tick(30)

def main():
    game = Game('Roach')
    game.loop()

    pygame.quit()

main()
99 percent of computer problems exists between chair and keyboard.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020